From 385615658f4040ae1ce6150b8d5872a3f1810b64 Mon Sep 17 00:00:00 2001 From: Jan Galinski Date: Wed, 13 Mar 2024 12:16:42 +0100 Subject: [PATCH] feat: add cockpit and history plugin --- examples/java-c7/pom.xml | 7 +- .../camunda/app/cockpit/scripts/config.js | 98 + .../scripts/definition-historic-activities.js | 12230 +++ .../scripts/instance-historic-activities.js | 8779 ++ .../cockpit/scripts/instance-route-history.js | 71760 ++++++++++++++++ .../app/cockpit/scripts/robot-module.js | 479 + .../src/main/resources/application.yml | 11 + 7 files changed, 93363 insertions(+), 1 deletion(-) create mode 100644 examples/java-c7/src/main/resources/META-INF/resources/webjars/camunda/app/cockpit/scripts/config.js create mode 100644 examples/java-c7/src/main/resources/META-INF/resources/webjars/camunda/app/cockpit/scripts/definition-historic-activities.js create mode 100644 examples/java-c7/src/main/resources/META-INF/resources/webjars/camunda/app/cockpit/scripts/instance-historic-activities.js create mode 100644 examples/java-c7/src/main/resources/META-INF/resources/webjars/camunda/app/cockpit/scripts/instance-route-history.js create mode 100644 examples/java-c7/src/main/resources/META-INF/resources/webjars/camunda/app/cockpit/scripts/robot-module.js diff --git a/examples/java-c7/pom.xml b/examples/java-c7/pom.xml index 7d39bd8..d921e9e 100644 --- a/examples/java-c7/pom.xml +++ b/examples/java-c7/pom.xml @@ -41,7 +41,12 @@ org.camunda.bpm.springboot - camunda-bpm-spring-boot-starter + camunda-bpm-spring-boot-starter-webapp + + + io.holunda + camunda-platform-7-autologin + 0.1.0 dev.bpm-crafters.process-engine-api diff --git a/examples/java-c7/src/main/resources/META-INF/resources/webjars/camunda/app/cockpit/scripts/config.js b/examples/java-c7/src/main/resources/META-INF/resources/webjars/camunda/app/cockpit/scripts/config.js new file mode 100644 index 0000000..7de6b42 --- /dev/null +++ b/examples/java-c7/src/main/resources/META-INF/resources/webjars/camunda/app/cockpit/scripts/config.js @@ -0,0 +1,98 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export default { + // // change the app name and vendor + // app: { + // name: 'Operations', + // vendor: 'Company' + // }, + customScripts: [ + // // If you have a folder called 'my-custom-script' (in the 'cockpit' folder) + // // with a file called 'customScript.js' in it + // // 'my-custom-script/customScript' + 'scripts/definition-historic-activities.js', + 'scripts/instance-historic-activities.js', + 'scripts/instance-route-history.js' + // 'scripts/instance-tab-modify.js' + ], + // requireJsConfig: { + // // AngularJS module names + // ngDeps: ['ui.bootstrap'], + // // RequireJS configuration for a complete configuration documentation see: + // // http://requirejs.org/docs/api.html#config + // deps: ['jquery', 'custom-ui'], + // paths: { + // // if you have a folder called `custom-ui` (in the `cockpit` folder) + // // with a file called `scripts.js` in it and defining the `custom-ui` AMD module + // 'custom-ui': 'custom-ui/scripts' + // } + // }, + // historicActivityInstanceMetrics: { + // adjustablePeriod: true, + // //select from the default time period: day, week, month, complete + // period: { + // unit: 'week' + // } + // }, + // runtimeActivityInstanceMetrics: { + // display: true + // }, + // 'locales': { + // 'availableLocales': ['en', 'de'], + // 'fallbackLocale': 'en' + // }, + // skipCustomListeners: { + // default: true, + // hidden: false + // }, + // skipIoMappings: { + // default: true, + // hidden: false + // }, + // 'batchOperation' : { + // // select mode of query for process instances or decision instances + // // possible values: filter, search + // 'mode': 'filter', + // + // // select if Historic Batches should be loaded automatically when navigating to #/batch + // 'autoLoadEnded': true + // }, + bpmnJs: { + // moddleExtensions: { + // // if you have a folder called 'my-custom-moddle' (in the 'cockpit' folder) + // // with a file called 'camunda.json' in it defining the 'camunda' moddle extension + // camunda: 'my-custom-moddle/camunda' + // }, + additionalModules: [ + // // if you have a folder called 'my-custom-module' (in the 'cockpit' folder) + // // with a file called 'module.js' in it + // 'my-custom-module/module' + 'scripts/robot-module.js' + ], + }, + // defaultFilter: { + // historicProcessDefinitionInstancesSearch: { + // lastDays: 5, + // event: 'started' + // } + // }, + // csrfCookieName: 'XSRF-TOKEN', + disableWelcomeMessage: true, + // userOperationLogAnnotationLength: 5000, + previewHtml: true +}; diff --git a/examples/java-c7/src/main/resources/META-INF/resources/webjars/camunda/app/cockpit/scripts/definition-historic-activities.js b/examples/java-c7/src/main/resources/META-INF/resources/webjars/camunda/app/cockpit/scripts/definition-historic-activities.js new file mode 100644 index 0000000..519206b --- /dev/null +++ b/examples/java-c7/src/main/resources/META-INF/resources/webjars/camunda/app/cockpit/scripts/definition-historic-activities.js @@ -0,0 +1,12230 @@ +function ___$insertStylesToHeader(css) { + if (!css) { + return + } + if (typeof window === 'undefined') { + return + } + + const style = document.createElement('style'); + + style.setAttribute('type', 'text/css'); + style.innerHTML = css; + document.head.appendChild(style); + return css +} + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +var __assign$1 = function() { + __assign$1 = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + return __assign$1.apply(this, arguments); +}; + +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +var react$1 = {exports: {}}; + +var react_production_min$1 = {}; + +/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +var l=Symbol.for("react.element"),n=Symbol.for("react.portal"),p$1=Symbol.for("react.fragment"),q=Symbol.for("react.strict_mode"),r$1=Symbol.for("react.profiler"),t=Symbol.for("react.provider"),u=Symbol.for("react.context"),v$1=Symbol.for("react.forward_ref"),w=Symbol.for("react.suspense"),x=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),z$1=Symbol.iterator;function A$1(a){if(null===a||"object"!==typeof a)return null;a=z$1&&a[z$1]||a["@@iterator"];return "function"===typeof a?a:null} +var B$1={isMounted:function(){return !1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C$1=Object.assign,D$1={};function E$1(a,b,e){this.props=a;this.context=b;this.refs=D$1;this.updater=e||B$1;}E$1.prototype.isReactComponent={}; +E$1.prototype.setState=function(a,b){if("object"!==typeof a&&"function"!==typeof a&&null!=a)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,a,b,"setState");};E$1.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,"forceUpdate");};function F(){}F.prototype=E$1.prototype;function G$1(a,b,e){this.props=a;this.context=b;this.refs=D$1;this.updater=e||B$1;}var H$1=G$1.prototype=new F; +H$1.constructor=G$1;C$1(H$1,E$1.prototype);H$1.isPureReactComponent=!0;var I$1=Array.isArray,J=Object.prototype.hasOwnProperty,K$1={current:null},L$1={key:!0,ref:!0,__self:!0,__source:!0}; +function M$1(a,b,e){var d,c={},k=null,h=null;if(null!=b)for(d in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(k=""+b.key),b)J.call(b,d)&&!L$1.hasOwnProperty(d)&&(c[d]=b[d]);var g=arguments.length-2;if(1===g)c.children=e;else if(1>>1,e=a[d];if(0>>1;dg(C,c))ng(x,C)?(a[d]=x,a[n]=c,d=n):(a[d]=C,a[m]=c,d=m);else if(ng(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b} + function g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}if("object"===typeof performance&&"function"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now()};}else {var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q};}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D="function"===typeof setTimeout?setTimeout:null,E="function"===typeof clearTimeout?clearTimeout:null,F="undefined"!==typeof setImmediate?setImmediate:null; + "undefined"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t);}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else {var b=h(t);null!==b&&K(H,b.startTime-a);}} + function J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if("function"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();"function"===typeof e?v.callback=e:v===h(r)&&k(r);G(b);}else k(r);v=h(r);}if(null!==v)var w=!0;else {var m=h(t);null!==m&&K(H,m.startTime-b);w=!1;}return w}finally{v=null,y=c,z=!1;}}var N=!1,O=null,L=-1,P=5,Q=-1; + function M(){return exports.unstable_now()-Qa||125d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a}; + exports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c;}}}; +} (scheduler_production_min$1)); + +{ + scheduler$1.exports = scheduler_production_min$1; +} + +var schedulerExports = scheduler$1.exports; + +/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +var aa=reactExports,ca=schedulerExports;function p(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;cb}return !1}function v(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g;}var z={}; +"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){z[a]=new v(a,0,!1,a,null,!1,!1);});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];z[b]=new v(b,1,!1,a[1],null,!1,!1);});["contentEditable","draggable","spellCheck","value"].forEach(function(a){z[a]=new v(a,2,!1,a.toLowerCase(),null,!1,!1);}); +["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){z[a]=new v(a,2,!1,a,null,!1,!1);});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){z[a]=new v(a,3,!1,a.toLowerCase(),null,!1,!1);}); +["checked","multiple","muted","selected"].forEach(function(a){z[a]=new v(a,3,!0,a,null,!1,!1);});["capture","download"].forEach(function(a){z[a]=new v(a,4,!1,a,null,!1,!1);});["cols","rows","size","span"].forEach(function(a){z[a]=new v(a,6,!1,a,null,!1,!1);});["rowSpan","start"].forEach(function(a){z[a]=new v(a,5,!1,a.toLowerCase(),null,!1,!1);});var ra=/[\-:]([a-z])/g;function sa(a){return a[1].toUpperCase()} +"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=a.replace(ra, +sa);z[b]=new v(b,1,!1,a,null,!1,!1);});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,"http://www.w3.org/1999/xlink",!1,!1);});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1,!1);});["tabIndex","crossOrigin"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!1,!1);}); +z.xlinkHref=new v("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!0,!0);}); +function ta(a,b,c,d){var e=z.hasOwnProperty(b)?z[b]:null;if(null!==e?0!==e.type:d||!(2h||e[g]!==f[h]){var k="\n"+e[g].replace(" at new "," at ");a.displayName&&k.includes("")&&(k=k.replace("",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{Na=!1,Error.prepareStackTrace=c;}return (a=a?a.displayName||a.name:"")?Ma(a):""} +function Pa(a){switch(a.tag){case 5:return Ma(a.type);case 16:return Ma("Lazy");case 13:return Ma("Suspense");case 19:return Ma("SuspenseList");case 0:case 2:case 15:return a=Oa(a.type,!1),a;case 11:return a=Oa(a.type.render,!1),a;case 1:return a=Oa(a.type,!0),a;default:return ""}} +function Qa(a){if(null==a)return null;if("function"===typeof a)return a.displayName||a.name||null;if("string"===typeof a)return a;switch(a){case ya:return "Fragment";case wa:return "Portal";case Aa:return "Profiler";case za:return "StrictMode";case Ea:return "Suspense";case Fa:return "SuspenseList"}if("object"===typeof a)switch(a.$$typeof){case Ca:return (a.displayName||"Context")+".Consumer";case Ba:return (a._context.displayName||"Context")+".Provider";case Da:var b=a.render;a=a.displayName;a||(a=b.displayName|| +b.name||"",a=""!==a?"ForwardRef("+a+")":"ForwardRef");return a;case Ga:return b=a.displayName||null,null!==b?b:Qa(a.type)||"Memo";case Ha:b=a._payload;a=a._init;try{return Qa(a(b))}catch(c){}}return null} +function Ra(a){var b=a.type;switch(a.tag){case 24:return "Cache";case 9:return (b.displayName||"Context")+".Consumer";case 10:return (b._context.displayName||"Context")+".Provider";case 18:return "DehydratedFragment";case 11:return a=b.render,a=a.displayName||a.name||"",b.displayName||(""!==a?"ForwardRef("+a+")":"ForwardRef");case 7:return "Fragment";case 5:return b;case 4:return "Portal";case 3:return "Root";case 6:return "Text";case 16:return Qa(b);case 8:return b===za?"StrictMode":"Mode";case 22:return "Offscreen"; +case 12:return "Profiler";case 21:return "Scope";case 13:return "Suspense";case 19:return "SuspenseList";case 25:return "TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if("function"===typeof b)return b.displayName||b.name||null;if("string"===typeof b)return b}return null}function Sa(a){switch(typeof a){case "boolean":case "number":case "string":case "undefined":return a;case "object":return a;default:return ""}} +function Ta(a){var b=a.type;return (a=a.nodeName)&&"input"===a.toLowerCase()&&("checkbox"===b||"radio"===b)} +function Ua(a){var b=Ta(a)?"checked":"value",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=""+a[b];if(!a.hasOwnProperty(b)&&"undefined"!==typeof c&&"function"===typeof c.get&&"function"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=""+a;f.call(this,a);}});Object.defineProperty(a,b,{enumerable:c.enumerable});return {getValue:function(){return d},setValue:function(a){d=""+a;},stopTracking:function(){a._valueTracker= +null;delete a[b];}}}}function Va(a){a._valueTracker||(a._valueTracker=Ua(a));}function Wa(a){if(!a)return !1;var b=a._valueTracker;if(!b)return !0;var c=b.getValue();var d="";a&&(d=Ta(a)?a.checked?"true":"false":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}function Xa(a){a=a||("undefined"!==typeof document?document:void 0);if("undefined"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}} +function Ya(a,b){var c=b.checked;return A({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}function Za(a,b){var c=null==b.defaultValue?"":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=Sa(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:"checkbox"===b.type||"radio"===b.type?null!=b.checked:null!=b.value};}function ab(a,b){b=b.checked;null!=b&&ta(a,"checked",b,!1);} +function bb(a,b){ab(a,b);var c=Sa(b.value),d=b.type;if(null!=c)if("number"===d){if(0===c&&""===a.value||a.value!=c)a.value=""+c;}else a.value!==""+c&&(a.value=""+c);else if("submit"===d||"reset"===d){a.removeAttribute("value");return}b.hasOwnProperty("value")?cb(a,b.type,c):b.hasOwnProperty("defaultValue")&&cb(a,b.type,Sa(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked);} +function db(a,b,c){if(b.hasOwnProperty("value")||b.hasOwnProperty("defaultValue")){var d=b.type;if(!("submit"!==d&&"reset"!==d||void 0!==b.value&&null!==b.value))return;b=""+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b;}c=a.name;""!==c&&(a.name="");a.defaultChecked=!!a._wrapperState.initialChecked;""!==c&&(a.name=c);} +function cb(a,b,c){if("number"!==b||Xa(a.ownerDocument)!==a)null==c?a.defaultValue=""+a._wrapperState.initialValue:a.defaultValue!==""+c&&(a.defaultValue=""+c);}var eb=Array.isArray; +function fb(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e"+b.valueOf().toString()+"";for(b=mb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild);}}); +function ob(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b;} +var pb={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0, +zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},qb=["Webkit","ms","Moz","O"];Object.keys(pb).forEach(function(a){qb.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);pb[b]=pb[a];});});function rb(a,b,c){return null==b||"boolean"===typeof b||""===b?"":c||"number"!==typeof b||0===b||pb.hasOwnProperty(a)&&pb[a]?(""+b).trim():b+"px"} +function sb(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf("--"),e=rb(c,b[c],d);"float"===c&&(c="cssFloat");d?a.setProperty(c,e):a[c]=e;}}var tb=A({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0}); +function ub(a,b){if(b){if(tb[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(p(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(p(60));if("object"!==typeof b.dangerouslySetInnerHTML||!("__html"in b.dangerouslySetInnerHTML))throw Error(p(61));}if(null!=b.style&&"object"!==typeof b.style)throw Error(p(62));}} +function vb(a,b){if(-1===a.indexOf("-"))return "string"===typeof b.is;switch(a){case "annotation-xml":case "color-profile":case "font-face":case "font-face-src":case "font-face-uri":case "font-face-format":case "font-face-name":case "missing-glyph":return !1;default:return !0}}var wb=null;function xb(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}var yb=null,zb=null,Ab=null; +function Bb(a){if(a=Cb(a)){if("function"!==typeof yb)throw Error(p(280));var b=a.stateNode;b&&(b=Db(b),yb(a.stateNode,a.type,b));}}function Eb(a){zb?Ab?Ab.push(a):Ab=[a]:zb=a;}function Fb(){if(zb){var a=zb,b=Ab;Ab=zb=null;Bb(a);if(b)for(a=0;a>>=0;return 0===a?32:31-(pc(a)/qc|0)|0}var rc=64,sc=4194304; +function tc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824; +default:return a}}function uc(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=tc(h):(f&=g,0!==f&&(d=tc(f)));}else g=c&~e,0!==g?d=tc(g):0!==f&&(d=tc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0c;c++)b.push(a);return b} +function Ac(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-oc(b);a[b]=c;}function Bc(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0=be$1),ee=String.fromCharCode(32),fe$1=!1; +function ge$1(a,b){switch(a){case "keyup":return -1!==$d.indexOf(b.keyCode);case "keydown":return 229!==b.keyCode;case "keypress":case "mousedown":case "focusout":return !0;default:return !1}}function he$1(a){a=a.detail;return "object"===typeof a&&"data"in a?a.data:null}var ie=!1;function je$1(a,b){switch(a){case "compositionend":return he$1(b);case "keypress":if(32!==b.which)return null;fe$1=!0;return ee;case "textInput":return a=b.data,a===ee&&fe$1?null:a;default:return null}} +function ke$1(a,b){if(ie)return "compositionend"===a||!ae&&ge$1(a,b)?(a=nd(),md=ld=kd=null,ie=!1,a):null;switch(a){case "paste":return null;case "keypress":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1=b)return {node:c,offset:b-a};a=d;}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode;}c=void 0;}c=Je(c);}}function Le$1(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Le$1(a,b.parentNode):"contains"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1} +function Me$1(){for(var a=window,b=Xa();b instanceof a.HTMLIFrameElement;){try{var c="string"===typeof b.contentWindow.location.href;}catch(d){c=!1;}if(c)a=b.contentWindow;else break;b=Xa(a.document);}return b}function Ne$1(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&("input"===b&&("text"===a.type||"search"===a.type||"tel"===a.type||"url"===a.type||"password"===a.type)||"textarea"===b||"true"===a.contentEditable)} +function Oe$1(a){var b=Me$1(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&Le$1(c.ownerDocument.documentElement,c)){if(null!==d&&Ne$1(c))if(b=d.start,a=d.end,void 0===a&&(a=b),"selectionStart"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=Ke$1(c,f);var g=Ke$1(c, +d);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset),a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),a.addRange(b)));}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});"function"===typeof c.focus&&c.focus();for(c=0;c=document.documentMode,Qe$1=null,Re$1=null,Se$1=null,Te$1=!1; +function Ue$1(a,b,c){var d=c.window===c?c.document:9===c.nodeType?c:c.ownerDocument;Te$1||null==Qe$1||Qe$1!==Xa(d)||(d=Qe$1,"selectionStart"in d&&Ne$1(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Se$1&&Ie$1(Se$1,d)||(Se$1=d,d=oe(Re$1,"onSelect"),0Tf||(a.current=Sf[Tf],Sf[Tf]=null,Tf--);}function G(a,b){Tf++;Sf[Tf]=a.current;a.current=b;}var Vf={},H=Uf(Vf),Wf=Uf(!1),Xf=Vf;function Yf(a,b){var c=a.type.contextTypes;if(!c)return Vf;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e} +function Zf(a){a=a.childContextTypes;return null!==a&&void 0!==a}function $f(){E(Wf);E(H);}function ag(a,b,c){if(H.current!==Vf)throw Error(p(168));G(H,b);G(Wf,c);}function bg(a,b,c){var d=a.stateNode;b=b.childContextTypes;if("function"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(p(108,Ra(a)||"Unknown",e));return A({},c,d)} +function cg(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Vf;Xf=H.current;G(H,a);G(Wf,Wf.current);return !0}function dg(a,b,c){var d=a.stateNode;if(!d)throw Error(p(169));c?(a=bg(a,b,Xf),d.__reactInternalMemoizedMergedChildContext=a,E(Wf),E(H),G(H,a)):E(Wf);G(Wf,c);}var eg=null,fg=!1,gg=!1;function hg(a){null===eg?eg=[a]:eg.push(a);}function ig(a){fg=!0;hg(a);} +function jg(){if(!gg&&null!==eg){gg=!0;var a=0,b=C;try{var c=eg;for(C=1;a>=g;e-=g;rg=1<<32-oc(b)+e|c<w?(x=u,u=null):x=u.sibling;var n=r(e,u,h[w],k);if(null===n){null===u&&(u=x);break}a&&u&&null===n.alternate&&b(e,u);g=f(n,g,w);null===m?l=n:m.sibling=n;m=n;u=x;}if(w===h.length)return c(e,u),I&&tg(e,w),l;if(null===u){for(;ww?(x=m,m=null):x=m.sibling;var t=r(e,m,n.value,k);if(null===t){null===m&&(m=x);break}a&&m&&null===t.alternate&&b(e,m);g=f(t,g,w);null===u?l=t:u.sibling=t;u=t;m=x;}if(n.done)return c(e, +m),I&&tg(e,w),l;if(null===m){for(;!n.done;w++,n=h.next())n=q(e,n.value,k),null!==n&&(g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);I&&tg(e,w);return l}for(m=d(e,m);!n.done;w++,n=h.next())n=y(m,e,w,n.value,k),null!==n&&(a&&null!==n.alternate&&m.delete(null===n.key?w:n.key),g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);a&&m.forEach(function(a){return b(e,a)});I&&tg(e,w);return l}function J(a,d,f,h){"object"===typeof f&&null!==f&&f.type===ya&&null===f.key&&(f=f.props.children);if("object"===typeof f&&null!==f){switch(f.$$typeof){case va:a:{for(var k= +f.key,l=d;null!==l;){if(l.key===k){k=f.type;if(k===ya){if(7===l.tag){c(a,l.sibling);d=e(l,f.props.children);d.return=a;a=d;break a}}else if(l.elementType===k||"object"===typeof k&&null!==k&&k.$$typeof===Ha&&uh(k)===l.type){c(a,l.sibling);d=e(l,f.props);d.ref=sh(a,l,f);d.return=a;a=d;break a}c(a,l);break}else b(a,l);l=l.sibling;}f.type===ya?(d=Ah(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=yh(f.type,f.key,f.props,null,a.mode,h),h.ref=sh(a,d,f),h.return=a,a=h);}return g(a);case wa:a:{for(l=f.key;null!== +d;){if(d.key===l)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else {c(a,d);break}else b(a,d);d=d.sibling;}d=zh(f,a.mode,h);d.return=a;a=d;}return g(a);case Ha:return l=f._init,J(a,d,l(f._payload),h)}if(eb(f))return n(a,d,f,h);if(Ka(f))return t(a,d,f,h);th(a,f);}return "string"===typeof f&&""!==f||"number"===typeof f?(f=""+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d): +(c(a,d),d=xh(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d)}return J}var Bh=vh(!0),Ch=vh(!1),Dh={},Eh=Uf(Dh),Fh=Uf(Dh),Gh=Uf(Dh);function Hh(a){if(a===Dh)throw Error(p(174));return a}function Ih(a,b){G(Gh,b);G(Fh,a);G(Eh,Dh);a=b.nodeType;switch(a){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:lb(null,"");break;default:a=8===a?b.parentNode:b,b=a.namespaceURI||null,a=a.tagName,b=lb(b,a);}E(Eh);G(Eh,b);}function Jh(){E(Eh);E(Fh);E(Gh);} +function Kh(a){Hh(Gh.current);var b=Hh(Eh.current);var c=lb(b,a.type);b!==c&&(G(Fh,a),G(Eh,c));}function Lh(a){Fh.current===a&&(E(Eh),E(Fh));}var M=Uf(0); +function Mh(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||"$?"===c.data||"$!"===c.data))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.flags&128))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return;}b.sibling.return=b.return;b=b.sibling;}return null}var Nh=[]; +function Oh(){for(var a=0;ac?c:4;a(!0);var d=Qh.transition;Qh.transition={};try{a(!1),b();}finally{C=c,Qh.transition=d;}}function Fi(){return di().memoizedState} +function Gi(a,b,c){var d=lh(a);c={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(b,c);else if(c=Yg(a,b,c,d),null!==c){var e=L();mh(c,a,d,e);Ji(c,b,d);}} +function ri(a,b,c){var d=lh(a),e={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(b,e);else {var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(He$1(h,g)){var k=b.interleaved;null===k?(e.next=e,Xg(b)):(e.next=k.next,k.next=e);b.interleaved=e;return}}catch(l){}finally{}c=Yg(a,b,e,d);null!==c&&(e=L(),mh(c,a,d,e),Ji(c,b,d));}} +function Hi(a){var b=a.alternate;return a===N||null!==b&&b===N}function Ii(a,b){Th=Sh=!0;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b;}function Ji(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c);}} +var ai={readContext:Vg,useCallback:Q,useContext:Q,useEffect:Q,useImperativeHandle:Q,useInsertionEffect:Q,useLayoutEffect:Q,useMemo:Q,useReducer:Q,useRef:Q,useState:Q,useDebugValue:Q,useDeferredValue:Q,useTransition:Q,useMutableSource:Q,useSyncExternalStore:Q,useId:Q,unstable_isNewReconciler:!1},Yh={readContext:Vg,useCallback:function(a,b){ci().memoizedState=[a,void 0===b?null:b];return a},useContext:Vg,useEffect:vi,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ti(4194308, +4,yi.bind(null,b,a),c)},useLayoutEffect:function(a,b){return ti(4194308,4,a,b)},useInsertionEffect:function(a,b){return ti(4,2,a,b)},useMemo:function(a,b){var c=ci();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=ci();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=Gi.bind(null,N,a);return [d.memoizedState,a]},useRef:function(a){var b= +ci();a={current:a};return b.memoizedState=a},useState:qi,useDebugValue:Ai,useDeferredValue:function(a){return ci().memoizedState=a},useTransition:function(){var a=qi(!1),b=a[0];a=Ei.bind(null,a[1]);ci().memoizedState=a;return [b,a]},useMutableSource:function(){},useSyncExternalStore:function(a,b,c){var d=N,e=ci();if(I){if(void 0===c)throw Error(p(407));c=c();}else {c=b();if(null===R)throw Error(p(349));0!==(Rh&30)||ni(d,b,c);}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;vi(ki.bind(null,d, +f,a),[a]);d.flags|=2048;li(9,mi.bind(null,d,f,c,b),void 0,null);return c},useId:function(){var a=ci(),b=R.identifierPrefix;if(I){var c=sg;var d=rg;c=(d&~(1<<32-oc(d)-1)).toString(32)+c;b=":"+b+"R"+c;c=Uh++;0\x3c/script>",a=a.removeChild(a.firstChild)): +"string"===typeof d.is?a=g.createElement(c,{is:d.is}):(a=g.createElement(c),"select"===c&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,c);a[Of]=b;a[Pf]=d;Aj(a,b,!1,!1);b.stateNode=a;a:{g=vb(c,d);switch(c){case "dialog":D("cancel",a);D("close",a);e=d;break;case "iframe":case "object":case "embed":D("load",a);e=d;break;case "video":case "audio":for(e=0;eHj&&(b.flags|=128,d=!0,Ej(f,!1),b.lanes=4194304);}else {if(!d)if(a=Mh(g),null!==a){if(b.flags|=128,d=!0,c=a.updateQueue,null!==c&&(b.updateQueue=c,b.flags|=4),Ej(f,!0),null===f.tail&&"hidden"===f.tailMode&&!g.alternate&&!I)return S(b),null}else 2*B()-f.renderingStartTime>Hj&&1073741824!==c&&(b.flags|=128,d=!0,Ej(f,!1),b.lanes=4194304);f.isBackwards?(g.sibling=b.child,b.child=g):(c=f.last,null!==c?c.sibling=g:b.child=g,f.last=g);}if(null!==f.tail)return b=f.tail,f.rendering= +b,f.tail=b.sibling,f.renderingStartTime=B(),b.sibling=null,c=M.current,G(M,d?c&1|2:c&1),b;S(b);return null;case 22:case 23:return Ij(),d=null!==b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(gj&1073741824)&&(S(b),b.subtreeFlags&6&&(b.flags|=8192)):S(b),null;case 24:return null;case 25:return null}throw Error(p(156,b.tag));} +function Jj(a,b){wg(b);switch(b.tag){case 1:return Zf(b.type)&&$f(),a=b.flags,a&65536?(b.flags=a&-65537|128,b):null;case 3:return Jh(),E(Wf),E(H),Oh(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return Lh(b),null;case 13:E(M);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(p(340));Ig();}a=b.flags;return a&65536?(b.flags=a&-65537|128,b):null;case 19:return E(M),null;case 4:return Jh(),null;case 10:return Rg(b.type._context),null;case 22:case 23:return Ij(), +null;case 24:return null;default:return null}}var Kj=!1,U=!1,Lj="function"===typeof WeakSet?WeakSet:Set,V=null;function Mj(a,b){var c=a.ref;if(null!==c)if("function"===typeof c)try{c(null);}catch(d){W(a,b,d);}else c.current=null;}function Nj(a,b,c){try{c();}catch(d){W(a,b,d);}}var Oj=!1; +function Pj(a,b){Cf=dd;a=Me$1();if(Ne$1(a)){if("selectionStart"in a)var c={start:a.selectionStart,end:a.selectionEnd};else a:{c=(c=a.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&0!==d.rangeCount){c=d.anchorNode;var e=d.anchorOffset,f=d.focusNode;d=d.focusOffset;try{c.nodeType,f.nodeType;}catch(F){c=null;break a}var g=0,h=-1,k=-1,l=0,m=0,q=a,r=null;b:for(;;){for(var y;;){q!==c||0!==e&&3!==q.nodeType||(h=g+e);q!==f||0!==d&&3!==q.nodeType||(k=g+d);3===q.nodeType&&(g+= +q.nodeValue.length);if(null===(y=q.firstChild))break;r=q;q=y;}for(;;){if(q===a)break b;r===c&&++l===e&&(h=g);r===f&&++m===d&&(k=g);if(null!==(y=q.nextSibling))break;q=r;r=q.parentNode;}q=y;}c=-1===h||-1===k?null:{start:h,end:k};}else c=null;}c=c||{start:0,end:0};}else c=null;Df={focusedElem:a,selectionRange:c};dd=!1;for(V=b;null!==V;)if(b=V,a=b.child,0!==(b.subtreeFlags&1028)&&null!==a)a.return=b,V=a;else for(;null!==V;){b=V;try{var n=b.alternate;if(0!==(b.flags&1024))switch(b.tag){case 0:case 11:case 15:break; +case 1:if(null!==n){var t=n.memoizedProps,J=n.memoizedState,x=b.stateNode,w=x.getSnapshotBeforeUpdate(b.elementType===b.type?t:Lg(b.type,t),J);x.__reactInternalSnapshotBeforeUpdate=w;}break;case 3:var u=b.stateNode.containerInfo;1===u.nodeType?u.textContent="":9===u.nodeType&&u.documentElement&&u.removeChild(u.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(p(163));}}catch(F){W(b,b.return,F);}a=b.sibling;if(null!==a){a.return=b.return;V=a;break}V=b.return;}n=Oj;Oj=!1;return n} +function Qj(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&Nj(b,c,f);}e=e.next;}while(e!==d)}}function Rj(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d();}c=c.next;}while(c!==b)}}function Sj(a){var b=a.ref;if(null!==b){var c=a.stateNode;switch(a.tag){case 5:a=c;break;default:a=c;}"function"===typeof b?b(a):b.current=a;}} +function Tj(a){var b=a.alternate;null!==b&&(a.alternate=null,Tj(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&(delete b[Of],delete b[Pf],delete b[of],delete b[Qf],delete b[Rf]));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null;}function Uj(a){return 5===a.tag||3===a.tag||4===a.tag} +function Vj(a){a:for(;;){for(;null===a.sibling;){if(null===a.return||Uj(a.return))return null;a=a.return;}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child;}if(!(a.flags&2))return a.stateNode}} +function Wj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?8===c.nodeType?c.parentNode.insertBefore(a,b):c.insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,null!==c&&void 0!==c||null!==b.onclick||(b.onclick=Bf));else if(4!==d&&(a=a.child,null!==a))for(Wj(a,b,c),a=a.sibling;null!==a;)Wj(a,b,c),a=a.sibling;} +function Xj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(Xj(a,b,c),a=a.sibling;null!==a;)Xj(a,b,c),a=a.sibling;}var X=null,Yj=!1;function Zj(a,b,c){for(c=c.child;null!==c;)ak(a,b,c),c=c.sibling;} +function ak(a,b,c){if(lc&&"function"===typeof lc.onCommitFiberUnmount)try{lc.onCommitFiberUnmount(kc,c);}catch(h){}switch(c.tag){case 5:U||Mj(c,b);case 6:var d=X,e=Yj;X=null;Zj(a,b,c);X=d;Yj=e;null!==X&&(Yj?(a=X,c=c.stateNode,8===a.nodeType?a.parentNode.removeChild(c):a.removeChild(c)):X.removeChild(c.stateNode));break;case 18:null!==X&&(Yj?(a=X,c=c.stateNode,8===a.nodeType?Kf(a.parentNode,c):1===a.nodeType&&Kf(a,c),bd(a)):Kf(X,c.stateNode));break;case 4:d=X;e=Yj;X=c.stateNode.containerInfo;Yj=!0; +Zj(a,b,c);X=d;Yj=e;break;case 0:case 11:case 14:case 15:if(!U&&(d=c.updateQueue,null!==d&&(d=d.lastEffect,null!==d))){e=d=d.next;do{var f=e,g=f.destroy;f=f.tag;void 0!==g&&(0!==(f&2)?Nj(c,b,g):0!==(f&4)&&Nj(c,b,g));e=e.next;}while(e!==d)}Zj(a,b,c);break;case 1:if(!U&&(Mj(c,b),d=c.stateNode,"function"===typeof d.componentWillUnmount))try{d.props=c.memoizedProps,d.state=c.memoizedState,d.componentWillUnmount();}catch(h){W(c,b,h);}Zj(a,b,c);break;case 21:Zj(a,b,c);break;case 22:c.mode&1?(U=(d=U)||null!== +c.memoizedState,Zj(a,b,c),U=d):Zj(a,b,c);break;default:Zj(a,b,c);}}function bk(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Lj);b.forEach(function(b){var d=ck.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d));});}} +function dk(a,b){var c=b.deletions;if(null!==c)for(var d=0;de&&(e=g);d&=~f;}d=e;d=B()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*mk(d/1960))-d;if(10a?16:a;if(null===xk)var d=!1;else {a=xk;xk=null;yk=0;if(0!==(K&6))throw Error(p(331));var e=K;K|=4;for(V=a.current;null!==V;){var f=V,g=f.child;if(0!==(V.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;kB()-gk?Lk(a,0):sk|=c);Ek(a,b);}function Zk(a,b){0===b&&(0===(a.mode&1)?b=1:(b=sc,sc<<=1,0===(sc&130023424)&&(sc=4194304)));var c=L();a=Zg(a,b);null!==a&&(Ac(a,b,c),Ek(a,c));}function vj(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);Zk(a,c);} +function ck(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);break;case 19:d=a.stateNode;break;default:throw Error(p(314));}null!==d&&d.delete(b);Zk(a,c);}var Wk; +Wk=function(a,b,c){if(null!==a)if(a.memoizedProps!==b.pendingProps||Wf.current)Ug=!0;else {if(0===(a.lanes&c)&&0===(b.flags&128))return Ug=!1,zj(a,b,c);Ug=0!==(a.flags&131072)?!0:!1;}else Ug=!1,I&&0!==(b.flags&1048576)&&ug(b,ng,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;jj(a,b);a=b.pendingProps;var e=Yf(b,H.current);Tg(b,c);e=Xh(null,b,d,a,e,c);var f=bi();b.flags|=1;"object"===typeof e&&null!==e&&"function"===typeof e.render&&void 0===e.$$typeof?(b.tag=1,b.memoizedState=null,b.updateQueue= +null,Zf(d)?(f=!0,cg(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,ah(b),e.updater=nh,b.stateNode=e,e._reactInternals=b,rh(b,d,a,c),b=kj(null,b,d,!0,f,c)):(b.tag=0,I&&f&&vg(b),Yi(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{jj(a,b);a=b.pendingProps;e=d._init;d=e(d._payload);b.type=d;e=b.tag=$k(d);a=Lg(d,a);switch(e){case 0:b=dj(null,b,d,a,c);break a;case 1:b=ij(null,b,d,a,c);break a;case 11:b=Zi(null,b,d,a,c);break a;case 14:b=aj(null,b,d,Lg(d.type,a),c);break a}throw Error(p(306, +d,""));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),dj(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),ij(a,b,d,e,c);case 3:a:{lj(b);if(null===a)throw Error(p(387));d=b.pendingProps;f=b.memoizedState;e=f.element;bh(a,b);gh(b,d,null,c);var g=b.memoizedState;d=g.element;if(f.isDehydrated)if(f={element:d,isDehydrated:!1,cache:g.cache,pendingSuspenseBoundaries:g.pendingSuspenseBoundaries,transitions:g.transitions},b.updateQueue.baseState= +f,b.memoizedState=f,b.flags&256){e=Ki(Error(p(423)),b);b=mj(a,b,d,c,e);break a}else if(d!==e){e=Ki(Error(p(424)),b);b=mj(a,b,d,c,e);break a}else for(yg=Lf(b.stateNode.containerInfo.firstChild),xg=b,I=!0,zg=null,c=Ch(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else {Ig();if(d===e){b=$i(a,b,c);break a}Yi(a,b,d,c);}b=b.child;}return b;case 5:return Kh(b),null===a&&Eg(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,Ef(d,e)?g=null:null!==f&&Ef(d,f)&&(b.flags|=32), +hj(a,b),Yi(a,b,g,c),b.child;case 6:return null===a&&Eg(b),null;case 13:return pj(a,b,c);case 4:return Ih(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=Bh(b,null,d,c):Yi(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),Zi(a,b,d,e,c);case 7:return Yi(a,b,b.pendingProps,c),b.child;case 8:return Yi(a,b,b.pendingProps.children,c),b.child;case 12:return Yi(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;f=b.memoizedProps; +g=e.value;G(Mg,d._currentValue);d._currentValue=g;if(null!==f)if(He$1(f.value,g)){if(f.children===e.children&&!Wf.current){b=$i(a,b,c);break a}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=ch(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var m=l.pending;null===m?k.next=k:(k.next=m.next,m.next=k);l.pending=k;}}f.lanes|=c;k=f.alternate;null!==k&&(k.lanes|=c);Sg(f.return, +c,b);h.lanes|=c;break}k=k.next;}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===f.tag){g=f.return;if(null===g)throw Error(p(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);Sg(g,c,b);g=f.sibling;}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break}f=g.sibling;if(null!==f){f.return=g.return;g=f;break}g=g.return;}f=g;}Yi(a,b,e.children,c);b=b.child;}return b;case 9:return e=b.type,d=b.pendingProps.children,Tg(b,c),e=Vg(e),d=d(e),b.flags|=1,Yi(a,b,d,c), +b.child;case 14:return d=b.type,e=Lg(d,b.pendingProps),e=Lg(d.type,e),aj(a,b,d,e,c);case 15:return cj(a,b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),jj(a,b),b.tag=1,Zf(d)?(a=!0,cg(b)):a=!1,Tg(b,c),ph(b,d,e),rh(b,d,e,c),kj(null,b,d,!0,a,c);case 19:return yj(a,b,c);case 22:return ej(a,b,c)}throw Error(p(156,b.tag));};function Gk(a,b){return ac(a,b)} +function al(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null;}function Bg(a,b,c,d){return new al(a,b,c,d)}function bj(a){a=a.prototype;return !(!a||!a.isReactComponent)} +function $k(a){if("function"===typeof a)return bj(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===Da)return 11;if(a===Ga)return 14}return 2} +function wh(a,b){var c=a.alternate;null===c?(c=Bg(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.subtreeFlags=0,c.deletions=null);c.flags=a.flags&14680064;c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{lanes:b.lanes,firstContext:b.firstContext}; +c.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c} +function yh(a,b,c,d,e,f){var g=2;d=a;if("function"===typeof a)bj(a)&&(g=1);else if("string"===typeof a)g=5;else a:switch(a){case ya:return Ah(c.children,e,f,b);case za:g=8;e|=8;break;case Aa:return a=Bg(12,c,b,e|2),a.elementType=Aa,a.lanes=f,a;case Ea:return a=Bg(13,c,b,e),a.elementType=Ea,a.lanes=f,a;case Fa:return a=Bg(19,c,b,e),a.elementType=Fa,a.lanes=f,a;case Ia:return qj(c,e,f,b);default:if("object"===typeof a&&null!==a)switch(a.$$typeof){case Ba:g=10;break a;case Ca:g=9;break a;case Da:g=11; +break a;case Ga:g=14;break a;case Ha:g=16;d=null;break a}throw Error(p(130,null==a?a:typeof a,""));}b=Bg(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function Ah(a,b,c,d){a=Bg(7,a,d,b);a.lanes=c;return a}function qj(a,b,c,d){a=Bg(22,a,d,b);a.elementType=Ia;a.lanes=c;a.stateNode={isHidden:!1};return a}function xh(a,b,c){a=Bg(6,a,null,b);a.lanes=c;return a} +function zh(a,b,c){b=Bg(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b} +function bl(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=-1;this.callbackNode=this.pendingContext=this.context=null;this.callbackPriority=0;this.eventTimes=zc(0);this.expirationTimes=zc(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=zc(0);this.identifierPrefix=d;this.onRecoverableError=e;this.mutableSourceEagerHydrationData= +null;}function cl(a,b,c,d,e,f,g,h,k){a=new bl(a,b,c,h,k);1===b?(b=1,!0===f&&(b|=8)):b=0;f=Bg(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null,pendingSuspenseBoundaries:null};ah(f);return a}function dl(a,b,c){var d=3Q.length&&Q.push(a);} + function T(a,b,c,e){var d=typeof a;if("undefined"===d||"boolean"===d)a=null;var g=!1;if(null===a)g=!0;else switch(d){case "string":case "number":g=!0;break;case "object":switch(a.$$typeof){case p:case q:g=!0;}}if(g)return c(e,a,""===b?"."+U(a,0):b),1;g=0;b=""===b?".":b+":";if(Array.isArray(a))for(var k=0;k=G};l=function(){};exports.unstable_forceFrameRate=function(a){0>a||125>>1,e=a[d];if(void 0!==e&&0K(n,c))void 0!==r&&0>K(r,n)?(a[d]=r,a[v]=c,d=v):(a[d]=n,a[m]=c,d=m);else if(void 0!==r&&0>K(r,c))a[d]=r,a[v]=c,d=v;else break a}}return b}return null}function K(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}var N=[],O=[],P=1,Q=null,R=3,S=!1,T=!1,U=!1; + function V(a){for(var b=L(O);null!==b;){if(null===b.callback)M(O);else if(b.startTime<=a)M(O),b.sortIndex=b.expirationTime,J(N,b);else break;b=L(O);}}function W(a){U=!1;V(a);if(!T)if(null!==L(N))T=!0,f(X);else {var b=L(O);null!==b&&g(W,b.startTime-a);}} + function X(a,b){T=!1;U&&(U=!1,h());S=!0;var c=R;try{V(b);for(Q=L(N);null!==Q&&(!(Q.expirationTime>b)||a&&!k());){var d=Q.callback;if(null!==d){Q.callback=null;R=Q.priorityLevel;var e=d(Q.expirationTime<=b);b=exports.unstable_now();"function"===typeof e?Q.callback=e:Q===L(N)&&M(N);V(b);}else M(N);Q=L(N);}if(null!==Q)var m=!0;else {var n=L(O);null!==n&&g(W,n.startTime-b);m=!1;}return m}finally{Q=null,R=c,S=!1;}} + function Y(a){switch(a){case 1:return -1;case 2:return 250;case 5:return 1073741823;case 4:return 1E4;default:return 5E3}}var Z=l;exports.unstable_IdlePriority=5;exports.unstable_ImmediatePriority=1;exports.unstable_LowPriority=4;exports.unstable_NormalPriority=3;exports.unstable_Profiling=null;exports.unstable_UserBlockingPriority=2;exports.unstable_cancelCallback=function(a){a.callback=null;};exports.unstable_continueExecution=function(){T||S||(T=!0,f(X));}; + exports.unstable_getCurrentPriorityLevel=function(){return R};exports.unstable_getFirstCallbackNode=function(){return L(N)};exports.unstable_next=function(a){switch(R){case 1:case 2:case 3:var b=3;break;default:b=R;}var c=R;R=b;try{return a()}finally{R=c;}};exports.unstable_pauseExecution=function(){};exports.unstable_requestPaint=Z;exports.unstable_runWithPriority=function(a,b){switch(a){case 1:case 2:case 3:case 4:case 5:break;default:a=3;}var c=R;R=a;try{return b()}finally{R=c;}}; + exports.unstable_scheduleCallback=function(a,b,c){var d=exports.unstable_now();if("object"===typeof c&&null!==c){var e=c.delay;e="number"===typeof e&&0d?(a.sortIndex=e,J(O,a),null===L(N)&&a===L(O)&&(U?h():U=!0,g(W,e-d))):(a.sortIndex=c,J(N,a),T||S||(T=!0,f(X)));return a}; + exports.unstable_shouldYield=function(){var a=exports.unstable_now();V(a);var b=L(N);return b!==Q&&null!==Q&&null!==b&&null!==b.callback&&b.startTime<=a&&b.expirationTimeb}return !1}function v(a,b,c,d,e,f){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;}var C={}; + "children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){C[a]=new v(a,0,!1,a,null,!1);});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];C[b]=new v(b,1,!1,a[1],null,!1);});["contentEditable","draggable","spellCheck","value"].forEach(function(a){C[a]=new v(a,2,!1,a.toLowerCase(),null,!1);}); + ["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){C[a]=new v(a,2,!1,a,null,!1);});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){C[a]=new v(a,3,!1,a.toLowerCase(),null,!1);}); + ["checked","multiple","muted","selected"].forEach(function(a){C[a]=new v(a,3,!0,a,null,!1);});["capture","download"].forEach(function(a){C[a]=new v(a,4,!1,a,null,!1);});["cols","rows","size","span"].forEach(function(a){C[a]=new v(a,6,!1,a,null,!1);});["rowSpan","start"].forEach(function(a){C[a]=new v(a,5,!1,a.toLowerCase(),null,!1);});var Ua=/[\-:]([a-z])/g;function Va(a){return a[1].toUpperCase()} + "accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=a.replace(Ua, + Va);C[b]=new v(b,1,!1,a,null,!1);});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(Ua,Va);C[b]=new v(b,1,!1,a,"http://www.w3.org/1999/xlink",!1);});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(Ua,Va);C[b]=new v(b,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1);});["tabIndex","crossOrigin"].forEach(function(a){C[a]=new v(a,1,!1,a.toLowerCase(),null,!1);}); + C.xlinkHref=new v("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0);["src","href","action","formAction"].forEach(function(a){C[a]=new v(a,1,!1,a.toLowerCase(),null,!0);});var Wa=aa.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;Wa.hasOwnProperty("ReactCurrentDispatcher")||(Wa.ReactCurrentDispatcher={current:null});Wa.hasOwnProperty("ReactCurrentBatchConfig")||(Wa.ReactCurrentBatchConfig={suspense:null}); + function Xa(a,b,c,d){var e=C.hasOwnProperty(b)?C[b]:null;var f=null!==e?0===e.type:d?!1:!(2=c.length))throw Error(u(93));c=c[0];}b=c;}null==b&&(b="");c=b;}a._wrapperState={initialValue:rb(c)};} + function Kb(a,b){var c=rb(b.value),d=rb(b.defaultValue);null!=c&&(c=""+c,c!==a.value&&(a.value=c),null==b.defaultValue&&a.defaultValue!==c&&(a.defaultValue=c));null!=d&&(a.defaultValue=""+d);}function Lb(a){var b=a.textContent;b===a._wrapperState.initialValue&&""!==b&&null!==b&&(a.value=b);}var Mb={html:"http://www.w3.org/1999/xhtml",mathml:"http://www.w3.org/1998/Math/MathML",svg:"http://www.w3.org/2000/svg"}; + function Nb(a){switch(a){case "svg":return "http://www.w3.org/2000/svg";case "math":return "http://www.w3.org/1998/Math/MathML";default:return "http://www.w3.org/1999/xhtml"}}function Ob(a,b){return null==a||"http://www.w3.org/1999/xhtml"===a?Nb(b):"http://www.w3.org/2000/svg"===a&&"foreignObject"===b?"http://www.w3.org/1999/xhtml":a} + var Pb,Qb=function(a){return "undefined"!==typeof MSApp&&MSApp.execUnsafeLocalFunction?function(b,c,d,e){MSApp.execUnsafeLocalFunction(function(){return a(b,c,d,e)});}:a}(function(a,b){if(a.namespaceURI!==Mb.svg||"innerHTML"in a)a.innerHTML=b;else {Pb=Pb||document.createElement("div");Pb.innerHTML=""+b.valueOf().toString()+"";for(b=Pb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild);}}); + function Rb(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b;}function Sb(a,b){var c={};c[a.toLowerCase()]=b.toLowerCase();c["Webkit"+a]="webkit"+b;c["Moz"+a]="moz"+b;return c}var Tb={animationend:Sb("Animation","AnimationEnd"),animationiteration:Sb("Animation","AnimationIteration"),animationstart:Sb("Animation","AnimationStart"),transitionend:Sb("Transition","TransitionEnd")},Ub={},Vb={}; + ya&&(Vb=document.createElement("div").style,"AnimationEvent"in window||(delete Tb.animationend.animation,delete Tb.animationiteration.animation,delete Tb.animationstart.animation),"TransitionEvent"in window||delete Tb.transitionend.transition);function Wb(a){if(Ub[a])return Ub[a];if(!Tb[a])return a;var b=Tb[a],c;for(c in b)if(b.hasOwnProperty(c)&&c in Vb)return Ub[a]=b[c];return a} + var Xb=Wb("animationend"),Yb=Wb("animationiteration"),Zb=Wb("animationstart"),$b=Wb("transitionend"),ac="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),bc=new ("function"===typeof WeakMap?WeakMap:Map);function cc(a){var b=bc.get(a);void 0===b&&(b=new Map,bc.set(a,b));return b} + function dc(a){var b=a,c=a;if(a.alternate)for(;b.return;)b=b.return;else {a=b;do b=a,0!==(b.effectTag&1026)&&(c=b.return),a=b.return;while(a)}return 3===b.tag?c:null}function ec(a){if(13===a.tag){var b=a.memoizedState;null===b&&(a=a.alternate,null!==a&&(b=a.memoizedState));if(null!==b)return b.dehydrated}return null}function fc(a){if(dc(a)!==a)throw Error(u(188));} + function gc(a){var b=a.alternate;if(!b){b=dc(a);if(null===b)throw Error(u(188));return b!==a?null:a}for(var c=a,d=b;;){var e=c.return;if(null===e)break;var f=e.alternate;if(null===f){d=e.return;if(null!==d){c=d;continue}break}if(e.child===f.child){for(f=e.child;f;){if(f===c)return fc(e),a;if(f===d)return fc(e),b;f=f.sibling;}throw Error(u(188));}if(c.return!==d.return)c=e,d=f;else {for(var g=!1,h=e.child;h;){if(h===c){g=!0;c=e;d=f;break}if(h===d){g=!0;d=e;c=f;break}h=h.sibling;}if(!g){for(h=f.child;h;){if(h=== + c){g=!0;c=f;d=e;break}if(h===d){g=!0;d=f;c=e;break}h=h.sibling;}if(!g)throw Error(u(189));}}if(c.alternate!==d)throw Error(u(190));}if(3!==c.tag)throw Error(u(188));return c.stateNode.current===c?a:b}function hc(a){a=gc(a);if(!a)return null;for(var b=a;;){if(5===b.tag||6===b.tag)return b;if(b.child)b.child.return=b,b=b.child;else {if(b===a)break;for(;!b.sibling;){if(!b.return||b.return===a)return null;b=b.return;}b.sibling.return=b.return;b=b.sibling;}}return null} + function ic(a,b){if(null==b)throw Error(u(30));if(null==a)return b;if(Array.isArray(a)){if(Array.isArray(b))return a.push.apply(a,b),a;a.push(b);return a}return Array.isArray(b)?[a].concat(b):[a,b]}function jc(a,b,c){Array.isArray(a)?a.forEach(b,c):a&&b.call(c,a);}var kc=null; + function lc(a){if(a){var b=a._dispatchListeners,c=a._dispatchInstances;if(Array.isArray(b))for(var d=0;dpc.length&&pc.push(a);} + function rc(a,b,c,d){if(pc.length){var e=pc.pop();e.topLevelType=a;e.eventSystemFlags=d;e.nativeEvent=b;e.targetInst=c;return e}return {topLevelType:a,eventSystemFlags:d,nativeEvent:b,targetInst:c,ancestors:[]}} + function sc(a){var b=a.targetInst,c=b;do{if(!c){a.ancestors.push(c);break}var d=c;if(3===d.tag)d=d.stateNode.containerInfo;else {for(;d.return;)d=d.return;d=3!==d.tag?null:d.stateNode.containerInfo;}if(!d)break;b=c.tag;5!==b&&6!==b||a.ancestors.push(c);c=tc(d);}while(c);for(c=0;c=b)return {node:c,offset:b-a};a=d;}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode;}c=void 0;}c=ud(c);}} + function wd(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?wd(a,b.parentNode):"contains"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1}function xd(){for(var a=window,b=td();b instanceof a.HTMLIFrameElement;){try{var c="string"===typeof b.contentWindow.location.href;}catch(d){c=!1;}if(c)a=b.contentWindow;else break;b=td(a.document);}return b} + function yd(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&("input"===b&&("text"===a.type||"search"===a.type||"tel"===a.type||"url"===a.type||"password"===a.type)||"textarea"===b||"true"===a.contentEditable)}var zd="$",Ad="/$",Bd="$?",Cd="$!",Dd=null,Ed=null;function Fd(a,b){switch(a){case "button":case "input":case "select":case "textarea":return !!b.autoFocus}return !1} + function Gd(a,b){return "textarea"===a||"option"===a||"noscript"===a||"string"===typeof b.children||"number"===typeof b.children||"object"===typeof b.dangerouslySetInnerHTML&&null!==b.dangerouslySetInnerHTML&&null!=b.dangerouslySetInnerHTML.__html}var Hd="function"===typeof setTimeout?setTimeout:void 0,Id="function"===typeof clearTimeout?clearTimeout:void 0;function Jd(a){for(;null!=a;a=a.nextSibling){var b=a.nodeType;if(1===b||3===b)break}return a} + function Kd(a){a=a.previousSibling;for(var b=0;a;){if(8===a.nodeType){var c=a.data;if(c===zd||c===Cd||c===Bd){if(0===b)return a;b--;}else c===Ad&&b++;}a=a.previousSibling;}return null}var Ld=Math.random().toString(36).slice(2),Md="__reactInternalInstance$"+Ld,Nd="__reactEventHandlers$"+Ld,Od="__reactContainere$"+Ld; + function tc(a){var b=a[Md];if(b)return b;for(var c=a.parentNode;c;){if(b=c[Od]||c[Md]){c=b.alternate;if(null!==b.child||null!==c&&null!==c.child)for(a=Kd(a);null!==a;){if(c=a[Md])return c;a=Kd(a);}return b}a=c;c=a.parentNode;}return null}function Nc(a){a=a[Md]||a[Od];return !a||5!==a.tag&&6!==a.tag&&13!==a.tag&&3!==a.tag?null:a}function Pd(a){if(5===a.tag||6===a.tag)return a.stateNode;throw Error(u(33));}function Qd(a){return a[Nd]||null} + function Rd(a){do a=a.return;while(a&&5!==a.tag);return a?a:null} + function Sd(a,b){var c=a.stateNode;if(!c)return null;var d=la(c);if(!d)return null;c=d[b];a:switch(b){case "onClick":case "onClickCapture":case "onDoubleClick":case "onDoubleClickCapture":case "onMouseDown":case "onMouseDownCapture":case "onMouseMove":case "onMouseMoveCapture":case "onMouseUp":case "onMouseUpCapture":case "onMouseEnter":(d=!d.disabled)||(a=a.type,d=!("button"===a||"input"===a||"select"===a||"textarea"===a));a=!d;break a;default:a=!1;}if(a)return null;if(c&&"function"!==typeof c)throw Error(u(231, + b,typeof c));return c}function Td(a,b,c){if(b=Sd(a,c.dispatchConfig.phasedRegistrationNames[b]))c._dispatchListeners=ic(c._dispatchListeners,b),c._dispatchInstances=ic(c._dispatchInstances,a);}function Ud(a){if(a&&a.dispatchConfig.phasedRegistrationNames){for(var b=a._targetInst,c=[];b;)c.push(b),b=Rd(b);for(b=c.length;0this.eventPool.length&&this.eventPool.push(a);}function de(a){a.eventPool=[];a.getPooled=ee;a.release=fe;}var ge=G.extend({data:null}),he=G.extend({data:null}),ie=[9,13,27,32],je=ya&&"CompositionEvent"in window,ke=null;ya&&"documentMode"in document&&(ke=document.documentMode); + var le=ya&&"TextEvent"in window&&!ke,me=ya&&(!je||ke&&8=ke),ne=String.fromCharCode(32),oe={beforeInput:{phasedRegistrationNames:{bubbled:"onBeforeInput",captured:"onBeforeInputCapture"},dependencies:["compositionend","keypress","textInput","paste"]},compositionEnd:{phasedRegistrationNames:{bubbled:"onCompositionEnd",captured:"onCompositionEndCapture"},dependencies:"blur compositionend keydown keypress keyup mousedown".split(" ")},compositionStart:{phasedRegistrationNames:{bubbled:"onCompositionStart", + captured:"onCompositionStartCapture"},dependencies:"blur compositionstart keydown keypress keyup mousedown".split(" ")},compositionUpdate:{phasedRegistrationNames:{bubbled:"onCompositionUpdate",captured:"onCompositionUpdateCapture"},dependencies:"blur compositionupdate keydown keypress keyup mousedown".split(" ")}},pe=!1; + function qe(a,b){switch(a){case "keyup":return -1!==ie.indexOf(b.keyCode);case "keydown":return 229!==b.keyCode;case "keypress":case "mousedown":case "blur":return !0;default:return !1}}function re(a){a=a.detail;return "object"===typeof a&&"data"in a?a.data:null}var se=!1;function te(a,b){switch(a){case "compositionend":return re(b);case "keypress":if(32!==b.which)return null;pe=!0;return ne;case "textInput":return a=b.data,a===ne&&pe?null:a;default:return null}} + function ue(a,b){if(se)return "compositionend"===a||!je&&qe(a,b)?(a=ae(),$d=Zd=Yd=null,se=!1,a):null;switch(a){case "paste":return null;case "keypress":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1=document.documentMode,df={select:{phasedRegistrationNames:{bubbled:"onSelect",captured:"onSelectCapture"},dependencies:"blur contextmenu dragend focus keydown keyup mousedown mouseup selectionchange".split(" ")}},ef=null,ff=null,gf=null,hf=!1; + function jf(a,b){var c=b.window===b?b.document:9===b.nodeType?b:b.ownerDocument;if(hf||null==ef||ef!==td(c))return null;c=ef;"selectionStart"in c&&yd(c)?c={start:c.selectionStart,end:c.selectionEnd}:(c=(c.ownerDocument&&c.ownerDocument.defaultView||window).getSelection(),c={anchorNode:c.anchorNode,anchorOffset:c.anchorOffset,focusNode:c.focusNode,focusOffset:c.focusOffset});return gf&&bf(gf,c)?null:(gf=c,a=G.getPooled(df.select,ff,a,b),a.type="select",a.target=ef,Xd(a),a)} + var kf={eventTypes:df,extractEvents:function(a,b,c,d,e,f){e=f||(d.window===d?d.document:9===d.nodeType?d:d.ownerDocument);if(!(f=!e)){a:{e=cc(e);f=wa.onSelect;for(var g=0;gzf||(a.current=yf[zf],yf[zf]=null,zf--);} + function I(a,b){zf++;yf[zf]=a.current;a.current=b;}var Af={},J={current:Af},K={current:!1},Bf=Af;function Cf(a,b){var c=a.type.contextTypes;if(!c)return Af;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}function L(a){a=a.childContextTypes;return null!==a&&void 0!==a} + function Df(){H(K);H(J);}function Ef(a,b,c){if(J.current!==Af)throw Error(u(168));I(J,b);I(K,c);}function Ff(a,b,c){var d=a.stateNode;a=b.childContextTypes;if("function"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in a))throw Error(u(108,pb(b)||"Unknown",e));return n({},c,{},d)}function Gf(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Af;Bf=J.current;I(J,a);I(K,K.current);return !0} + function Hf(a,b,c){var d=a.stateNode;if(!d)throw Error(u(169));c?(a=Ff(a,b,Bf),d.__reactInternalMemoizedMergedChildContext=a,H(K),H(J),I(J,a)):H(K);I(K,c);} + var If=r.unstable_runWithPriority,Jf=r.unstable_scheduleCallback,Kf=r.unstable_cancelCallback,Lf=r.unstable_requestPaint,Mf=r.unstable_now,Nf=r.unstable_getCurrentPriorityLevel,Of=r.unstable_ImmediatePriority,Pf=r.unstable_UserBlockingPriority,Qf=r.unstable_NormalPriority,Rf=r.unstable_LowPriority,Sf=r.unstable_IdlePriority,Tf={},Uf=r.unstable_shouldYield,Vf=void 0!==Lf?Lf:function(){},Wf=null,Xf=null,Yf=!1,Zf=Mf(),$f=1E4>Zf?Mf:function(){return Mf()-Zf}; + function ag(){switch(Nf()){case Of:return 99;case Pf:return 98;case Qf:return 97;case Rf:return 96;case Sf:return 95;default:throw Error(u(332));}}function bg(a){switch(a){case 99:return Of;case 98:return Pf;case 97:return Qf;case 96:return Rf;case 95:return Sf;default:throw Error(u(332));}}function cg(a,b){a=bg(a);return If(a,b)}function dg(a,b,c){a=bg(a);return Jf(a,b,c)}function eg(a){null===Wf?(Wf=[a],Xf=Jf(Of,fg)):Wf.push(a);return Tf}function gg(){if(null!==Xf){var a=Xf;Xf=null;Kf(a);}fg();} + function fg(){if(!Yf&&null!==Wf){Yf=!0;var a=0;try{var b=Wf;cg(99,function(){for(;a=b&&(rg=!0),a.firstContext=null);} + function sg(a,b){if(mg!==a&&!1!==b&&0!==b){if("number"!==typeof b||1073741823===b)mg=a,b=1073741823;b={context:a,observedBits:b,next:null};if(null===lg){if(null===kg)throw Error(u(308));lg=b;kg.dependencies={expirationTime:0,firstContext:b,responders:null};}else lg=lg.next=b;}return a._currentValue}var tg=!1;function ug(a){a.updateQueue={baseState:a.memoizedState,baseQueue:null,shared:{pending:null},effects:null};} + function vg(a,b){a=a.updateQueue;b.updateQueue===a&&(b.updateQueue={baseState:a.baseState,baseQueue:a.baseQueue,shared:a.shared,effects:a.effects});}function wg(a,b){a={expirationTime:a,suspenseConfig:b,tag:0,payload:null,callback:null,next:null};return a.next=a}function xg(a,b){a=a.updateQueue;if(null!==a){a=a.shared;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b;}} + function yg(a,b){var c=a.alternate;null!==c&&vg(c,a);a=a.updateQueue;c=a.baseQueue;null===c?(a.baseQueue=b.next=b,b.next=b):(b.next=c.next,c.next=b);} + function zg(a,b,c,d){var e=a.updateQueue;tg=!1;var f=e.baseQueue,g=e.shared.pending;if(null!==g){if(null!==f){var h=f.next;f.next=g.next;g.next=h;}f=g;e.shared.pending=null;h=a.alternate;null!==h&&(h=h.updateQueue,null!==h&&(h.baseQueue=g));}if(null!==f){h=f.next;var k=e.baseState,l=0,m=null,p=null,x=null;if(null!==h){var z=h;do{g=z.expirationTime;if(gl&&(l=g);}else {null!==x&&(x=x.next={expirationTime:1073741823,suspenseConfig:z.suspenseConfig,tag:z.tag,payload:z.payload,callback:z.callback,next:null});Ag(g,z.suspenseConfig);a:{var D=a,t=z;g=b;ca=c;switch(t.tag){case 1:D=t.payload;if("function"===typeof D){k=D.call(ca,k,g);break a}k=D;break a;case 3:D.effectTag=D.effectTag&-4097|64;case 0:D=t.payload;g="function"===typeof D?D.call(ca,k,g):D;if(null===g||void 0===g)break a;k=n({},k,g);break a;case 2:tg=!0;}}null!==z.callback&& + (a.effectTag|=32,g=e.effects,null===g?e.effects=[z]:g.push(z));}z=z.next;if(null===z||z===h)if(g=e.shared.pending,null===g)break;else z=f.next=g.next,g.next=h,e.baseQueue=f=g,e.shared.pending=null;}while(1)}null===x?m=k:x.next=p;e.baseState=m;e.baseQueue=x;Bg(l);a.expirationTime=l;a.memoizedState=k;}} + function Cg(a,b,c){a=b.effects;b.effects=null;if(null!==a)for(b=0;by?(A=m,m=null):A=m.sibling;var q=x(e,m,h[y],k);if(null===q){null===m&&(m=A);break}a&& + m&&null===q.alternate&&b(e,m);g=f(q,g,y);null===t?l=q:t.sibling=q;t=q;m=A;}if(y===h.length)return c(e,m),l;if(null===m){for(;yy?(A=t,t=null):A=t.sibling;var D=x(e,t,q.value,l);if(null===D){null===t&&(t=A);break}a&&t&&null===D.alternate&&b(e,t);g=f(D,g,y);null===m?k=D:m.sibling=D;m=D;t=A;}if(q.done)return c(e,t),k;if(null===t){for(;!q.done;y++,q=h.next())q=p(e,q.value,l),null!==q&&(g=f(q,g,y),null===m?k=q:m.sibling=q,m=q);return k}for(t=d(e,t);!q.done;y++,q=h.next())q=z(t,e,y,q.value,l),null!==q&&(a&&null!== + q.alternate&&t.delete(null===q.key?y:q.key),g=f(q,g,y),null===m?k=q:m.sibling=q,m=q);a&&t.forEach(function(a){return b(e,a)});return k}return function(a,d,f,h){var k="object"===typeof f&&null!==f&&f.type===ab&&null===f.key;k&&(f=f.props.children);var l="object"===typeof f&&null!==f;if(l)switch(f.$$typeof){case Za:a:{l=f.key;for(k=d;null!==k;){if(k.key===l){switch(k.tag){case 7:if(f.type===ab){c(a,k.sibling);d=e(k,f.props.children);d.return=a;a=d;break a}break;default:if(k.elementType===f.type){c(a, + k.sibling);d=e(k,f.props);d.ref=Pg(a,k,f);d.return=a;a=d;break a}}c(a,k);break}else b(a,k);k=k.sibling;}f.type===ab?(d=Wg(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=Ug(f.type,f.key,f.props,null,a.mode,h),h.ref=Pg(a,d,f),h.return=a,a=h);}return g(a);case $a:a:{for(k=f.key;null!==d;){if(d.key===k)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else {c(a,d);break}else b(a,d);d= + d.sibling;}d=Vg(f,a.mode,h);d.return=a;a=d;}return g(a)}if("string"===typeof f||"number"===typeof f)return f=""+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):(c(a,d),d=Tg(f,a.mode,h),d.return=a,a=d),g(a);if(Og(f))return ca(a,d,f,h);if(nb(f))return D(a,d,f,h);l&&Qg(a,f);if("undefined"===typeof f&&!k)switch(a.tag){case 1:case 0:throw a=a.type,Error(u(152,a.displayName||a.name||"Component"));}return c(a,d)}}var Xg=Rg(!0),Yg=Rg(!1),Zg={},$g={current:Zg},ah={current:Zg},bh={current:Zg}; + function ch(a){if(a===Zg)throw Error(u(174));return a}function dh(a,b){I(bh,b);I(ah,a);I($g,Zg);a=b.nodeType;switch(a){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:Ob(null,"");break;default:a=8===a?b.parentNode:b,b=a.namespaceURI||null,a=a.tagName,b=Ob(b,a);}H($g);I($g,b);}function eh(){H($g);H(ah);H(bh);}function fh(a){ch(bh.current);var b=ch($g.current);var c=Ob(b,a.type);b!==c&&(I(ah,a),I($g,c));}function gh(a){ah.current===a&&(H($g),H(ah));}var M={current:0}; + function hh(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||c.data===Bd||c.data===Cd))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.effectTag&64))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return;}b.sibling.return=b.return;b=b.sibling;}return null}function ih(a,b){return {responder:a,props:b}} + var jh=Wa.ReactCurrentDispatcher,kh=Wa.ReactCurrentBatchConfig,lh=0,N=null,O=null,P=null,mh=!1;function Q(){throw Error(u(321));}function nh(a,b){if(null===b)return !1;for(var c=0;cf))throw Error(u(301));f+=1;P=O=null;b.updateQueue=null;jh.current=rh;a=c(d,e);}while(b.expirationTime===lh)}jh.current=sh;b=null!==O&&null!==O.next;lh=0;P=O=N=null;mh=!1;if(b)throw Error(u(300));return a} + function th(){var a={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};null===P?N.memoizedState=P=a:P=P.next=a;return P}function uh(){if(null===O){var a=N.alternate;a=null!==a?a.memoizedState:null;}else a=O.next;var b=null===P?N.memoizedState:P.next;if(null!==b)P=b,O=a;else {if(null===a)throw Error(u(310));O=a;a={memoizedState:O.memoizedState,baseState:O.baseState,baseQueue:O.baseQueue,queue:O.queue,next:null};null===P?N.memoizedState=P=a:P=P.next=a;}return P} + function vh(a,b){return "function"===typeof b?b(a):b} + function wh(a){var b=uh(),c=b.queue;if(null===c)throw Error(u(311));c.lastRenderedReducer=a;var d=O,e=d.baseQueue,f=c.pending;if(null!==f){if(null!==e){var g=e.next;e.next=f.next;f.next=g;}d.baseQueue=e=f;c.pending=null;}if(null!==e){e=e.next;d=d.baseState;var h=g=f=null,k=e;do{var l=k.expirationTime;if(lN.expirationTime&& + (N.expirationTime=l,Bg(l));}else null!==h&&(h=h.next={expirationTime:1073741823,suspenseConfig:k.suspenseConfig,action:k.action,eagerReducer:k.eagerReducer,eagerState:k.eagerState,next:null}),Ag(l,k.suspenseConfig),d=k.eagerReducer===a?k.eagerState:a(d,k.action);k=k.next;}while(null!==k&&k!==e);null===h?f=d:h.next=g;$e(d,b.memoizedState)||(rg=!0);b.memoizedState=d;b.baseState=f;b.baseQueue=h;c.lastRenderedState=d;}return [b.memoizedState,c.dispatch]} + function xh(a){var b=uh(),c=b.queue;if(null===c)throw Error(u(311));c.lastRenderedReducer=a;var d=c.dispatch,e=c.pending,f=b.memoizedState;if(null!==e){c.pending=null;var g=e=e.next;do f=a(f,g.action),g=g.next;while(g!==e);$e(f,b.memoizedState)||(rg=!0);b.memoizedState=f;null===b.baseQueue&&(b.baseState=f);c.lastRenderedState=f;}return [f,d]} + function yh(a){var b=th();"function"===typeof a&&(a=a());b.memoizedState=b.baseState=a;a=b.queue={pending:null,dispatch:null,lastRenderedReducer:vh,lastRenderedState:a};a=a.dispatch=zh.bind(null,N,a);return [b.memoizedState,a]}function Ah(a,b,c,d){a={tag:a,create:b,destroy:c,deps:d,next:null};b=N.updateQueue;null===b?(b={lastEffect:null},N.updateQueue=b,b.lastEffect=a.next=a):(c=b.lastEffect,null===c?b.lastEffect=a.next=a:(d=c.next,c.next=a,a.next=d,b.lastEffect=a));return a} + function Bh(){return uh().memoizedState}function Ch(a,b,c,d){var e=th();N.effectTag|=a;e.memoizedState=Ah(1|b,c,void 0,void 0===d?null:d);}function Dh(a,b,c,d){var e=uh();d=void 0===d?null:d;var f=void 0;if(null!==O){var g=O.memoizedState;f=g.destroy;if(null!==d&&nh(d,g.deps)){Ah(b,c,f,d);return}}N.effectTag|=a;e.memoizedState=Ah(1|b,c,f,d);}function Eh(a,b){return Ch(516,4,a,b)}function Fh(a,b){return Dh(516,4,a,b)}function Gh(a,b){return Dh(4,2,a,b)} + function Hh(a,b){if("function"===typeof b)return a=a(),b(a),function(){b(null);};if(null!==b&&void 0!==b)return a=a(),b.current=a,function(){b.current=null;}}function Ih(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return Dh(4,2,Hh.bind(null,b,a),c)}function Jh(){}function Kh(a,b){th().memoizedState=[a,void 0===b?null:b];return a}function Lh(a,b){var c=uh();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&nh(b,d[1]))return d[0];c.memoizedState=[a,b];return a} + function Mh(a,b){var c=uh();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&nh(b,d[1]))return d[0];a=a();c.memoizedState=[a,b];return a}function Nh(a,b,c){var d=ag();cg(98>d?98:d,function(){a(!0);});cg(97\x3c/script>",a=a.removeChild(a.firstChild)):"string"===typeof d.is?a=g.createElement(e,{is:d.is}):(a=g.createElement(e),"select"===e&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,e);a[Md]=b;a[Nd]=d;ni(a,b,!1,!1);b.stateNode=a;g=pd(e,d);switch(e){case "iframe":case "object":case "embed":F("load", + a);h=d;break;case "video":case "audio":for(h=0;hd.tailExpiration&&1b)&&tj.set(a,b)));}} + function xj(a,b){a.expirationTimea?c:a;return 2>=a&&b!==a?0:a} + function Z(a){if(0!==a.lastExpiredTime)a.callbackExpirationTime=1073741823,a.callbackPriority=99,a.callbackNode=eg(yj.bind(null,a));else {var b=zj(a),c=a.callbackNode;if(0===b)null!==c&&(a.callbackNode=null,a.callbackExpirationTime=0,a.callbackPriority=90);else {var d=Gg();1073741823===b?d=99:1===b||2===b?d=95:(d=10*(1073741821-b)-10*(1073741821-d),d=0>=d?99:250>=d?98:5250>=d?97:95);if(null!==c){var e=a.callbackPriority;if(a.callbackExpirationTime===b&&e>=d)return;c!==Tf&&Kf(c);}a.callbackExpirationTime= + b;a.callbackPriority=d;b=1073741823===b?eg(yj.bind(null,a)):dg(d,Bj.bind(null,a),{timeout:10*(1073741821-b)-$f()});a.callbackNode=b;}}} + function Bj(a,b){wj=0;if(b)return b=Gg(),Cj(a,b),Z(a),null;var c=zj(a);if(0!==c){b=a.callbackNode;if((W&(fj|gj))!==V)throw Error(u(327));Dj();a===T&&c===U||Ej(a,c);if(null!==X){var d=W;W|=fj;var e=Fj();do try{Gj();break}catch(h){Hj(a,h);}while(1);ng();W=d;cj.current=e;if(S===hj)throw b=kj,Ej(a,c),xi(a,c),Z(a),b;if(null===X)switch(e=a.finishedWork=a.current.alternate,a.finishedExpirationTime=c,d=S,T=null,d){case ti:case hj:throw Error(u(345));case ij:Cj(a,2=c){a.lastPingedTime=c;Ej(a,c);break}}f=zj(a);if(0!==f&&f!==c)break;if(0!==d&&d!==c){a.lastPingedTime=d;break}a.timeoutHandle=Hd(Jj.bind(null,a),e);break}Jj(a);break;case vi:xi(a,c);d=a.lastSuspendedTime;c===d&&(a.nextKnownPendingLevel=Ij(e));if(oj&&(e=a.lastPingedTime,0===e||e>=c)){a.lastPingedTime=c;Ej(a,c);break}e=zj(a);if(0!==e&&e!==c)break;if(0!==d&&d!==c){a.lastPingedTime= + d;break}1073741823!==mj?d=10*(1073741821-mj)-$f():1073741823===lj?d=0:(d=10*(1073741821-lj)-5E3,e=$f(),c=10*(1073741821-c)-e,d=e-d,0>d&&(d=0),d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*bj(d/1960))-d,c=d?d=0:(e=g.busyDelayMs|0,f=$f()-(10*(1073741821-f)-(g.timeoutMs|0||5E3)),d=f<=e?0:e+d-f);if(10 component higher in the tree to provide a loading indicator or placeholder to display."+qb(g));}S!== + jj&&(S=ij);h=Ai(h,g);p=f;do{switch(p.tag){case 3:k=h;p.effectTag|=4096;p.expirationTime=b;var B=Xi(p,k,b);yg(p,B);break a;case 1:k=h;var w=p.type,ub=p.stateNode;if(0===(p.effectTag&64)&&("function"===typeof w.getDerivedStateFromError||null!==ub&&"function"===typeof ub.componentDidCatch&&(null===aj||!aj.has(ub)))){p.effectTag|=4096;p.expirationTime=b;var vb=$i(p,k,b);yg(p,vb);break a}}p=p.return;}while(null!==p)}X=Pj(X);}catch(Xc){b=Xc;continue}break}while(1)} + function Fj(){var a=cj.current;cj.current=sh;return null===a?sh:a}function Ag(a,b){awi&&(wi=a);}function Kj(){for(;null!==X;)X=Qj(X);}function Gj(){for(;null!==X&&!Uf();)X=Qj(X);}function Qj(a){var b=Rj(a.alternate,a,U);a.memoizedProps=a.pendingProps;null===b&&(b=Pj(a));dj.current=null;return b} + function Pj(a){X=a;do{var b=X.alternate;a=X.return;if(0===(X.effectTag&2048)){b=si(b,X,U);if(1===U||1!==X.childExpirationTime){for(var c=0,d=X.child;null!==d;){var e=d.expirationTime,f=d.childExpirationTime;e>c&&(c=e);f>c&&(c=f);d=d.sibling;}X.childExpirationTime=c;}if(null!==b)return b;null!==a&&0===(a.effectTag&2048)&&(null===a.firstEffect&&(a.firstEffect=X.firstEffect),null!==X.lastEffect&&(null!==a.lastEffect&&(a.lastEffect.nextEffect=X.firstEffect),a.lastEffect=X.lastEffect),1a?b:a}function Jj(a){var b=ag();cg(99,Sj.bind(null,a,b));return null} + function Sj(a,b){do Dj();while(null!==rj);if((W&(fj|gj))!==V)throw Error(u(327));var c=a.finishedWork,d=a.finishedExpirationTime;if(null===c)return null;a.finishedWork=null;a.finishedExpirationTime=0;if(c===a.current)throw Error(u(177));a.callbackNode=null;a.callbackExpirationTime=0;a.callbackPriority=90;a.nextKnownPendingLevel=0;var e=Ij(c);a.firstPendingTime=e;d<=a.lastSuspendedTime?a.firstSuspendedTime=a.lastSuspendedTime=a.nextKnownPendingLevel=0:d<=a.firstSuspendedTime&&(a.firstSuspendedTime= + d-1);d<=a.lastPingedTime&&(a.lastPingedTime=0);d<=a.lastExpiredTime&&(a.lastExpiredTime=0);a===T&&(X=T=null,U=0);1h&&(l=h,h=g,g=l),l=vd(q,g),m=vd(q,h),l&&m&&(1!==w.rangeCount||w.anchorNode!==l.node||w.anchorOffset!==l.offset||w.focusNode!==m.node||w.focusOffset!==m.offset)&&(B=B.createRange(),B.setStart(l.node,l.offset),w.removeAllRanges(),g>h?(w.addRange(B),w.extend(m.node,m.offset)):(B.setEnd(m.node,m.offset),w.addRange(B))))));B=[];for(w=q;w=w.parentNode;)1===w.nodeType&&B.push({element:w,left:w.scrollLeft, + top:w.scrollTop});"function"===typeof q.focus&&q.focus();for(q=0;q=c)return ji(a,b,c);I(M,M.current&1);b=$h(a,b,c);return null!==b?b.sibling:null}I(M,M.current&1);break;case 19:d=b.childExpirationTime>=c;if(0!==(a.effectTag&64)){if(d)return mi(a,b,c);b.effectTag|=64;}e=b.memoizedState;null!==e&&(e.rendering=null,e.tail=null);I(M,M.current);if(!d)return null}return $h(a,b,c)}rg=!1;}}else rg=!1;b.expirationTime=0;switch(b.tag){case 2:d=b.type;null!==a&&(a.alternate=null,b.alternate=null,b.effectTag|=2);a=b.pendingProps;e=Cf(b,J.current);qg(b,c);e=oh(null, + b,d,a,e,c);b.effectTag|=1;if("object"===typeof e&&null!==e&&"function"===typeof e.render&&void 0===e.$$typeof){b.tag=1;b.memoizedState=null;b.updateQueue=null;if(L(d)){var f=!0;Gf(b);}else f=!1;b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null;ug(b);var g=d.getDerivedStateFromProps;"function"===typeof g&&Fg(b,d,g,a);e.updater=Jg;b.stateNode=e;e._reactInternalFiber=b;Ng(b,d,a,c);b=gi(null,b,d,!0,f,c);}else b.tag=0,R(null,b,e,c),b=b.child;return b;case 16:a:{e=b.elementType;null!==a&&(a.alternate= + null,b.alternate=null,b.effectTag|=2);a=b.pendingProps;ob(e);if(1!==e._status)throw e._result;e=e._result;b.type=e;f=b.tag=Xj(e);a=ig(e,a);switch(f){case 0:b=di(null,b,e,a,c);break a;case 1:b=fi(null,b,e,a,c);break a;case 11:b=Zh(null,b,e,a,c);break a;case 14:b=ai(null,b,e,ig(e.type,a),d,c);break a}throw Error(u(306,e,""));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ig(d,e),di(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ig(d,e),fi(a,b,d,e,c); + case 3:hi(b);d=b.updateQueue;if(null===a||null===d)throw Error(u(282));d=b.pendingProps;e=b.memoizedState;e=null!==e?e.element:null;vg(a,b);zg(b,d,null,c);d=b.memoizedState.element;if(d===e)Xh(),b=$h(a,b,c);else {if(e=b.stateNode.hydrate)Ph=Jd(b.stateNode.containerInfo.firstChild),Oh=b,e=Qh=!0;if(e)for(c=Yg(b,null,d,c),b.child=c;c;)c.effectTag=c.effectTag&-3|1024,c=c.sibling;else R(a,b,d,c),Xh();b=b.child;}return b;case 5:return fh(b),null===a&&Uh(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps: + null,g=e.children,Gd(d,e)?g=null:null!==f&&Gd(d,f)&&(b.effectTag|=16),ei(a,b),b.mode&4&&1!==c&&e.hidden?(b.expirationTime=b.childExpirationTime=1,b=null):(R(a,b,g,c),b=b.child),b;case 6:return null===a&&Uh(b),null;case 13:return ji(a,b,c);case 4:return dh(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=Xg(b,null,d,c):R(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ig(d,e),Zh(a,b,d,e,c);case 7:return R(a,b,b.pendingProps,c),b.child;case 8:return R(a, + b,b.pendingProps.children,c),b.child;case 12:return R(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;g=b.memoizedProps;f=e.value;var h=b.type._context;I(jg,h._currentValue);h._currentValue=f;if(null!==g)if(h=g.value,f=$e(h,f)?0:("function"===typeof d._calculateChangedBits?d._calculateChangedBits(h,f):1073741823)|0,0===f){if(g.children===e.children&&!K.current){b=$h(a,b,c);break a}}else for(h=b.child,null!==h&&(h.return=b);null!==h;){var k=h.dependencies;if(null!== + k){g=h.child;for(var l=k.firstContext;null!==l;){if(l.context===d&&0!==(l.observedBits&f)){1===h.tag&&(l=wg(c,null),l.tag=2,xg(h,l));h.expirationTime=b&&a<=b}function xi(a,b){var c=a.firstSuspendedTime,d=a.lastSuspendedTime;cb||0===c)a.lastSuspendedTime=b;b<=a.lastPingedTime&&(a.lastPingedTime=0);b<=a.lastExpiredTime&&(a.lastExpiredTime=0);} + function yi(a,b){b>a.firstPendingTime&&(a.firstPendingTime=b);var c=a.firstSuspendedTime;0!==c&&(b>=c?a.firstSuspendedTime=a.lastSuspendedTime=a.nextKnownPendingLevel=0:b>=a.lastSuspendedTime&&(a.lastSuspendedTime=b+1),b>a.nextKnownPendingLevel&&(a.nextKnownPendingLevel=b));}function Cj(a,b){var c=a.lastExpiredTime;if(0===c||c>b)a.lastExpiredTime=b;} + function bk(a,b,c,d){var e=b.current,f=Gg(),g=Dg.suspense;f=Hg(f,e,g);a:if(c){c=c._reactInternalFiber;b:{if(dc(c)!==c||1!==c.tag)throw Error(u(170));var h=c;do{switch(h.tag){case 3:h=h.stateNode.context;break b;case 1:if(L(h.type)){h=h.stateNode.__reactInternalMemoizedMergedChildContext;break b}}h=h.return;}while(null!==h);throw Error(u(171));}if(1===c.tag){var k=c.type;if(L(k)){c=Ff(c,k,h);break a}}c=h;}else c=Af;null===b.context?b.context=c:b.pendingContext=c;b=wg(f,g);b.payload={element:a};d=void 0=== + d?null:d;null!==d&&(b.callback=d);xg(e,b);Ig(e,f);return f}function ck(a){a=a.current;if(!a.child)return null;switch(a.child.tag){case 5:return a.child.stateNode;default:return a.child.stateNode}}function dk(a,b){a=a.memoizedState;null!==a&&null!==a.dehydrated&&a.retryTime + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */(function(){var o="Expected a function",a="__lodash_placeholder__",s=[["ary",128],["bind",1],["bindKey",2],["curry",8],["curryRight",16],["flip",512],["partial",32],["partialRight",64],["rearg",256]],l="[object Arguments]",u="[object Array]",c="[object Boolean]",f="[object Date]",h="[object Error]",d="[object Function]",p="[object GeneratorFunction]",v="[object Map]",g="[object Number]",m="[object Object]",y="[object RegExp]",b="[object Set]",w="[object String]",x="[object Symbol]",C="[object WeakMap]",_="[object ArrayBuffer]",S="[object DataView]",k="[object Float32Array]",L="[object Float64Array]",M="[object Int8Array]",T="[object Int16Array]",O="[object Int32Array]",A="[object Uint8Array]",N="[object Uint16Array]",D="[object Uint32Array]",W=/\b__p \+= '';/g,E=/\b(__p \+=) '' \+/g,P=/(__e\(.*?\)|\b__t\)) \+\n'';/g,R=/&(?:amp|lt|gt|quot|#39);/g,H=/[&<>"']/g,F=RegExp(R.source),I=RegExp(H.source),z=/<%-([\s\S]+?)%>/g,j=/<%([\s\S]+?)%>/g,B=/<%=([\s\S]+?)%>/g,U=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,V=/^\w*$/,G=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,K=/[\\^$.*+?()[\]{}|]/g,q=RegExp(K.source),$=/^\s+/,X=/\s/,Y=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,Z=/\{\n\/\* \[wrapped with (.+)\] \*/,J=/,? & /,Q=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,tt=/[()=,{}\[\]\/\s]/,et=/\\(\\)?/g,rt=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,nt=/\w*$/,it=/^[-+]0x[0-9a-f]+$/i,ot=/^0b[01]+$/i,at=/^\[object .+?Constructor\]$/,st=/^0o[0-7]+$/i,lt=/^(?:0|[1-9]\d*)$/,ut=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,ct=/($^)/,ft=/['\n\r\u2028\u2029\\]/g,ht="\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff",dt="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",pt="[\\ud800-\\udfff]",vt="["+dt+"]",gt="["+ht+"]",mt="\\d+",yt="[\\u2700-\\u27bf]",bt="[a-z\\xdf-\\xf6\\xf8-\\xff]",wt="[^\\ud800-\\udfff"+dt+mt+"\\u2700-\\u27bfa-z\\xdf-\\xf6\\xf8-\\xffA-Z\\xc0-\\xd6\\xd8-\\xde]",xt="\\ud83c[\\udffb-\\udfff]",Ct="[^\\ud800-\\udfff]",_t="(?:\\ud83c[\\udde6-\\uddff]){2}",St="[\\ud800-\\udbff][\\udc00-\\udfff]",kt="[A-Z\\xc0-\\xd6\\xd8-\\xde]",Lt="(?:"+bt+"|"+wt+")",Mt="(?:"+kt+"|"+wt+")",Tt="(?:"+gt+"|"+xt+")"+"?",Ot="[\\ufe0e\\ufe0f]?"+Tt+("(?:\\u200d(?:"+[Ct,_t,St].join("|")+")[\\ufe0e\\ufe0f]?"+Tt+")*"),At="(?:"+[yt,_t,St].join("|")+")"+Ot,Nt="(?:"+[Ct+gt+"?",gt,_t,St,pt].join("|")+")",Dt=RegExp("['’]","g"),Wt=RegExp(gt,"g"),Et=RegExp(xt+"(?="+xt+")|"+Nt+Ot,"g"),Pt=RegExp([kt+"?"+bt+"+(?:['’](?:d|ll|m|re|s|t|ve))?(?="+[vt,kt,"$"].join("|")+")",Mt+"+(?:['’](?:D|LL|M|RE|S|T|VE))?(?="+[vt,kt+Lt,"$"].join("|")+")",kt+"?"+Lt+"+(?:['’](?:d|ll|m|re|s|t|ve))?",kt+"+(?:['’](?:D|LL|M|RE|S|T|VE))?","\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",mt,At].join("|"),"g"),Rt=RegExp("[\\u200d\\ud800-\\udfff"+ht+"\\ufe0e\\ufe0f]"),Ht=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,Ft=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],It=-1,zt={};zt[k]=zt[L]=zt[M]=zt[T]=zt[O]=zt[A]=zt["[object Uint8ClampedArray]"]=zt[N]=zt[D]=!0,zt[l]=zt[u]=zt[_]=zt[c]=zt[S]=zt[f]=zt[h]=zt[d]=zt[v]=zt[g]=zt[m]=zt[y]=zt[b]=zt[w]=zt[C]=!1;var jt={};jt[l]=jt[u]=jt[_]=jt[S]=jt[c]=jt[f]=jt[k]=jt[L]=jt[M]=jt[T]=jt[O]=jt[v]=jt[g]=jt[m]=jt[y]=jt[b]=jt[w]=jt[x]=jt[A]=jt["[object Uint8ClampedArray]"]=jt[N]=jt[D]=!0,jt[h]=jt[d]=jt[C]=!1;var Bt={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},Ut=parseFloat,Vt=parseInt,Gt="object"==typeof t&&t&&t.Object===Object&&t,Kt="object"==typeof self&&self&&self.Object===Object&&self,qt=Gt||Kt||Function("return this")(),$t=e&&!e.nodeType&&e,Xt=$t&&"object"==typeof n&&n&&!n.nodeType&&n,Yt=Xt&&Xt.exports===$t,Zt=Yt&&Gt.process,Jt=function(){try{var t=Xt&&Xt.require&&Xt.require("util").types;return t||Zt&&Zt.binding&&Zt.binding("util")}catch(t){}}(),Qt=Jt&&Jt.isArrayBuffer,te=Jt&&Jt.isDate,ee=Jt&&Jt.isMap,re=Jt&&Jt.isRegExp,ne=Jt&&Jt.isSet,ie=Jt&&Jt.isTypedArray;function oe(t,e,r){switch(r.length){case 0:return t.call(e);case 1:return t.call(e,r[0]);case 2:return t.call(e,r[0],r[1]);case 3:return t.call(e,r[0],r[1],r[2])}return t.apply(e,r)}function ae(t,e,r,n){for(var i=-1,o=null==t?0:t.length;++i-1}function he(t,e,r){for(var n=-1,i=null==t?0:t.length;++n-1;);return r}function Pe(t,e){for(var r=t.length;r--&&xe(e,t[r],0)>-1;);return r}function Re(t,e){for(var r=t.length,n=0;r--;)t[r]===e&&++n;return n}var He=Le({"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"}),Fe=Le({"&":"&","<":"<",">":">",'"':""","'":"'"});function Ie(t){return "\\"+Bt[t]}function ze(t){return Rt.test(t)}function je(t){var e=-1,r=Array(t.size);return t.forEach((function(t,n){r[++e]=[n,t];})),r}function Be(t,e){return function(r){return t(e(r))}}function Ue(t,e){for(var r=-1,n=t.length,i=0,o=[];++r",""":'"',"'":"'"});var Ye=function t(e){var r,n=(e=null==e?qt:Ye.defaults(qt.Object(),e,Ye.pick(qt,Ft))).Array,i=e.Date,X=e.Error,ht=e.Function,dt=e.Math,pt=e.Object,vt=e.RegExp,gt=e.String,mt=e.TypeError,yt=n.prototype,bt=ht.prototype,wt=pt.prototype,xt=e["__core-js_shared__"],Ct=bt.toString,_t=wt.hasOwnProperty,St=0,kt=(r=/[^.]+$/.exec(xt&&xt.keys&&xt.keys.IE_PROTO||""))?"Symbol(src)_1."+r:"",Lt=wt.toString,Mt=Ct.call(pt),Tt=qt._,Ot=vt("^"+Ct.call(_t).replace(K,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),At=Yt?e.Buffer:void 0,Nt=e.Symbol,Et=e.Uint8Array,Rt=At?At.allocUnsafe:void 0,Bt=Be(pt.getPrototypeOf,pt),Gt=pt.create,Kt=wt.propertyIsEnumerable,$t=yt.splice,Xt=Nt?Nt.isConcatSpreadable:void 0,Zt=Nt?Nt.iterator:void 0,Jt=Nt?Nt.toStringTag:void 0,ye=function(){try{var t=to(pt,"defineProperty");return t({},"",{}),t}catch(t){}}(),Le=e.clearTimeout!==qt.clearTimeout&&e.clearTimeout,Ze=i&&i.now!==qt.Date.now&&i.now,Je=e.setTimeout!==qt.setTimeout&&e.setTimeout,Qe=dt.ceil,tr=dt.floor,er=pt.getOwnPropertySymbols,rr=At?At.isBuffer:void 0,nr=e.isFinite,ir=yt.join,or=Be(pt.keys,pt),ar=dt.max,sr=dt.min,lr=i.now,ur=e.parseInt,cr=dt.random,fr=yt.reverse,hr=to(e,"DataView"),dr=to(e,"Map"),pr=to(e,"Promise"),vr=to(e,"Set"),gr=to(e,"WeakMap"),mr=to(pt,"create"),yr=gr&&new gr,br={},wr=To(hr),xr=To(dr),Cr=To(pr),_r=To(vr),Sr=To(gr),kr=Nt?Nt.prototype:void 0,Lr=kr?kr.valueOf:void 0,Mr=kr?kr.toString:void 0;function Tr(t){if(Ga(t)&&!Ea(t)&&!(t instanceof Dr)){if(t instanceof Nr)return t;if(_t.call(t,"__wrapped__"))return Oo(t)}return new Nr(t)}var Or=function(){function t(){}return function(e){if(!Va(e))return {};if(Gt)return Gt(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();function Ar(){}function Nr(t,e){this.__wrapped__=t,this.__actions__=[],this.__chain__=!!e,this.__index__=0,this.__values__=void 0;}function Dr(t){this.__wrapped__=t,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=4294967295,this.__views__=[];}function Wr(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e=e?t:e)),t}function Yr(t,e,r,n,i,o){var a,s=1&e,u=2&e,h=4&e;if(r&&(a=i?r(t,n,i,o):r(t)),void 0!==a)return a;if(!Va(t))return t;var C=Ea(t);if(C){if(a=function(t){var e=t.length,r=new t.constructor(e);e&&"string"==typeof t[0]&&_t.call(t,"index")&&(r.index=t.index,r.input=t.input);return r}(t),!s)return yi(t,a)}else {var W=no(t),E=W==d||W==p;if(Fa(t))return hi(t,s);if(W==m||W==l||E&&!i){if(a=u||E?{}:oo(t),!s)return u?function(t,e){return bi(t,ro(t),e)}(t,function(t,e){return t&&bi(e,Cs(e),t)}(a,t)):function(t,e){return bi(t,eo(t),e)}(t,Kr(a,t))}else {if(!jt[W])return i?t:{};a=function(t,e,r){var n=t.constructor;switch(e){case _:return di(t);case c:case f:return new n(+t);case S:return function(t,e){var r=e?di(t.buffer):t.buffer;return new t.constructor(r,t.byteOffset,t.byteLength)}(t,r);case k:case L:case M:case T:case O:case A:case"[object Uint8ClampedArray]":case N:case D:return pi(t,r);case v:return new n;case g:case w:return new n(t);case y:return function(t){var e=new t.constructor(t.source,nt.exec(t));return e.lastIndex=t.lastIndex,e}(t);case b:return new n;case x:return i=t,Lr?pt(Lr.call(i)):{}}var i;}(t,W,s);}}o||(o=new Hr);var P=o.get(t);if(P)return P;o.set(t,a),Ya(t)?t.forEach((function(n){a.add(Yr(n,e,r,n,t,o));})):Ka(t)&&t.forEach((function(n,i){a.set(i,Yr(n,e,r,i,t,o));}));var R=C?void 0:(h?u?qi:Ki:u?Cs:xs)(t);return se(R||t,(function(n,i){R&&(n=t[i=n]),Ur(a,i,Yr(n,e,r,i,t,o));})),a}function Zr(t,e,r){var n=r.length;if(null==t)return !n;for(t=pt(t);n--;){var i=r[n],o=e[i],a=t[i];if(void 0===a&&!(i in t)||!o(a))return !1}return !0}function Jr(t,e,r){if("function"!=typeof t)throw new mt(o);return xo((function(){t.apply(void 0,r);}),e)}function Qr(t,e,r,n){var i=-1,o=fe,a=!0,s=t.length,l=[],u=e.length;if(!s)return l;r&&(e=de(e,Ne(r))),n?(o=he,a=!1):e.length>=200&&(o=We,a=!1,e=new Rr(e));t:for(;++i-1},Er.prototype.set=function(t,e){var r=this.__data__,n=Vr(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this},Pr.prototype.clear=function(){this.size=0,this.__data__={hash:new Wr,map:new(dr||Er),string:new Wr};},Pr.prototype.delete=function(t){var e=Ji(this,t).delete(t);return this.size-=e?1:0,e},Pr.prototype.get=function(t){return Ji(this,t).get(t)},Pr.prototype.has=function(t){return Ji(this,t).has(t)},Pr.prototype.set=function(t,e){var r=Ji(this,t),n=r.size;return r.set(t,e),this.size+=r.size==n?0:1,this},Rr.prototype.add=Rr.prototype.push=function(t){return this.__data__.set(t,"__lodash_hash_undefined__"),this},Rr.prototype.has=function(t){return this.__data__.has(t)},Hr.prototype.clear=function(){this.__data__=new Er,this.size=0;},Hr.prototype.delete=function(t){var e=this.__data__,r=e.delete(t);return this.size=e.size,r},Hr.prototype.get=function(t){return this.__data__.get(t)},Hr.prototype.has=function(t){return this.__data__.has(t)},Hr.prototype.set=function(t,e){var r=this.__data__;if(r instanceof Er){var n=r.__data__;if(!dr||n.length<199)return n.push([t,e]),this.size=++r.size,this;r=this.__data__=new Pr(n);}return r.set(t,e),this.size=r.size,this};var tn=Ci(un),en=Ci(cn,!0);function rn(t,e){var r=!0;return tn(t,(function(t,n,i){return r=!!e(t,n,i)})),r}function nn(t,e,r){for(var n=-1,i=t.length;++n0&&r(s)?e>1?an(s,e-1,r,n,i):pe(i,s):n||(i[i.length]=s);}return i}var sn=_i(),ln=_i(!0);function un(t,e){return t&&sn(t,e,xs)}function cn(t,e){return t&&ln(t,e,xs)}function fn(t,e){return ce(e,(function(e){return ja(t[e])}))}function hn(t,e){for(var r=0,n=(e=li(e,t)).length;null!=t&&re}function gn(t,e){return null!=t&&_t.call(t,e)}function mn(t,e){return null!=t&&e in pt(t)}function yn(t,e,r){for(var i=r?he:fe,o=t[0].length,a=t.length,s=a,l=n(a),u=1/0,c=[];s--;){var f=t[s];s&&e&&(f=de(f,Ne(e))),u=sr(f.length,u),l[s]=!r&&(e||o>=120&&f.length>=120)?new Rr(s&&f):void 0;}f=t[0];var h=-1,d=l[0];t:for(;++h=s)return l;var u=r[n];return l*("desc"==u?-1:1)}}return t.index-e.index}(t,e,r)}))}function En(t,e,r){for(var n=-1,i=e.length,o={};++n-1;)s!==t&&$t.call(s,l,1),$t.call(t,l,1);return t}function Rn(t,e){for(var r=t?e.length:0,n=r-1;r--;){var i=e[r];if(r==n||i!==o){var o=i;so(i)?$t.call(t,i,1):ti(t,i);}}return t}function Hn(t,e){return t+tr(cr()*(e-t+1))}function Fn(t,e){var r="";if(!t||e<1||e>9007199254740991)return r;do{e%2&&(r+=t),(e=tr(e/2))&&(t+=t);}while(e);return r}function In(t,e){return Co(go(t,e,qs),t+"")}function zn(t){return Ir(As(t))}function jn(t,e){var r=As(t);return ko(r,Xr(e,0,r.length))}function Bn(t,e,r,n){if(!Va(t))return t;for(var i=-1,o=(e=li(e,t)).length,a=o-1,s=t;null!=s&&++io?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var a=n(o);++i>>1,a=t[o];null!==a&&!Ja(a)&&(r?a<=e:a=200){var u=e?null:Fi(t);if(u)return Ve(u);a=!1,i=We,l=new Rr;}else l=e?[]:s;t:for(;++n=n?t:Kn(t,e,r)}var fi=Le||function(t){return qt.clearTimeout(t)};function hi(t,e){if(e)return t.slice();var r=t.length,n=Rt?Rt(r):new t.constructor(r);return t.copy(n),n}function di(t){var e=new t.constructor(t.byteLength);return new Et(e).set(new Et(t)),e}function pi(t,e){var r=e?di(t.buffer):t.buffer;return new t.constructor(r,t.byteOffset,t.length)}function vi(t,e){if(t!==e){var r=void 0!==t,n=null===t,i=t==t,o=Ja(t),a=void 0!==e,s=null===e,l=e==e,u=Ja(e);if(!s&&!u&&!o&&t>e||o&&a&&l&&!s&&!u||n&&a&&l||!r&&l||!i)return 1;if(!n&&!o&&!u&&t1?r[i-1]:void 0,a=i>2?r[2]:void 0;for(o=t.length>3&&"function"==typeof o?(i--,o):void 0,a&&lo(r[0],r[1],a)&&(o=i<3?void 0:o,i=1),e=pt(e);++n-1?i[o?e[a]:a]:void 0}}function Ti(t){return Gi((function(e){var r=e.length,n=r,i=Nr.prototype.thru;for(t&&e.reverse();n--;){var a=e[n];if("function"!=typeof a)throw new mt(o);if(i&&!s&&"wrapper"==Xi(a))var s=new Nr([],!0);}for(n=s?n:r;++n1&&b.reverse(),f&&us))return !1;var u=o.get(t),c=o.get(e);if(u&&c)return u==e&&c==t;var f=-1,h=!0,d=2&r?new Rr:void 0;for(o.set(t,e),o.set(e,t);++f-1&&t%1==0&&t1?"& ":"")+e[n],e=e.join(r>2?", ":" "),t.replace(Y,"{\n/* [wrapped with "+e+"] */\n")}(n,function(t,e){return se(s,(function(r){var n="_."+r[0];e&r[1]&&!fe(t,n)&&t.push(n);})),t.sort()}(function(t){var e=t.match(Z);return e?e[1].split(J):[]}(n),r)))}function So(t){var e=0,r=0;return function(){var n=lr(),i=16-(n-r);if(r=n,i>0){if(++e>=800)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}function ko(t,e){var r=-1,n=t.length,i=n-1;for(e=void 0===e?n:e;++r1?t[e-1]:void 0;return r="function"==typeof r?(t.pop(),r):void 0,Xo(t,r)}));function ra(t){var e=Tr(t);return e.__chain__=!0,e}function na(t,e){return e(t)}var ia=Gi((function(t){var e=t.length,r=e?t[0]:0,n=this.__wrapped__,i=function(e){return $r(e,t)};return !(e>1||this.__actions__.length)&&n instanceof Dr&&so(r)?((n=n.slice(r,+r+(e?1:0))).__actions__.push({func:na,args:[i],thisArg:void 0}),new Nr(n,this.__chain__).thru((function(t){return e&&!t.length&&t.push(void 0),t}))):this.thru(i)}));var oa=wi((function(t,e,r){_t.call(t,r)?++t[r]:qr(t,r,1);}));var aa=Mi(Wo),sa=Mi(Eo);function la(t,e){return (Ea(t)?se:tn)(t,Zi(e,3))}function ua(t,e){return (Ea(t)?le:en)(t,Zi(e,3))}var ca=wi((function(t,e,r){_t.call(t,r)?t[r].push(e):qr(t,r,[e]);}));var fa=In((function(t,e,r){var i=-1,o="function"==typeof e,a=Ra(t)?n(t.length):[];return tn(t,(function(t){a[++i]=o?oe(e,t,r):bn(t,e,r);})),a})),ha=wi((function(t,e,r){qr(t,r,e);}));function da(t,e){return (Ea(t)?de:Tn)(t,Zi(e,3))}var pa=wi((function(t,e,r){t[r?0:1].push(e);}),(function(){return [[],[]]}));var va=In((function(t,e){if(null==t)return [];var r=e.length;return r>1&&lo(t,e[0],e[1])?e=[]:r>2&&lo(e[0],e[1],e[2])&&(e=[e[0]]),Wn(t,an(e,1),[])})),ga=Ze||function(){return qt.Date.now()};function ma(t,e,r){return e=r?void 0:e,zi(t,128,void 0,void 0,void 0,void 0,e=t&&null==e?t.length:e)}function ya(t,e){var r;if("function"!=typeof e)throw new mt(o);return t=is(t),function(){return --t>0&&(r=e.apply(this,arguments)),t<=1&&(e=void 0),r}}var ba=In((function(t,e,r){var n=1;if(r.length){var i=Ue(r,Yi(ba));n|=32;}return zi(t,n,e,r,i)})),wa=In((function(t,e,r){var n=3;if(r.length){var i=Ue(r,Yi(wa));n|=32;}return zi(e,n,t,r,i)}));function xa(t,e,r){var n,i,a,s,l,u,c=0,f=!1,h=!1,d=!0;if("function"!=typeof t)throw new mt(o);function p(e){var r=n,o=i;return n=i=void 0,c=e,s=t.apply(o,r)}function v(t){return c=t,l=xo(m,e),f?p(t):s}function g(t){var r=t-u;return void 0===u||r>=e||r<0||h&&t-c>=a}function m(){var t=ga();if(g(t))return y(t);l=xo(m,function(t){var r=e-(t-u);return h?sr(r,a-(t-c)):r}(t));}function y(t){return l=void 0,d&&n?p(t):(n=i=void 0,s)}function b(){var t=ga(),r=g(t);if(n=arguments,i=this,u=t,r){if(void 0===l)return v(u);if(h)return fi(l),l=xo(m,e),p(u)}return void 0===l&&(l=xo(m,e)),s}return e=as(e)||0,Va(r)&&(f=!!r.leading,a=(h="maxWait"in r)?ar(as(r.maxWait)||0,e):a,d="trailing"in r?!!r.trailing:d),b.cancel=function(){void 0!==l&&fi(l),c=0,n=u=i=l=void 0;},b.flush=function(){return void 0===l?s:y(ga())},b}var Ca=In((function(t,e){return Jr(t,1,e)})),_a=In((function(t,e,r){return Jr(t,as(e)||0,r)}));function Sa(t,e){if("function"!=typeof t||null!=e&&"function"!=typeof e)throw new mt(o);var r=function(){var n=arguments,i=e?e.apply(this,n):n[0],o=r.cache;if(o.has(i))return o.get(i);var a=t.apply(this,n);return r.cache=o.set(i,a)||o,a};return r.cache=new(Sa.Cache||Pr),r}function ka(t){if("function"!=typeof t)throw new mt(o);return function(){var e=arguments;switch(e.length){case 0:return !t.call(this);case 1:return !t.call(this,e[0]);case 2:return !t.call(this,e[0],e[1]);case 3:return !t.call(this,e[0],e[1],e[2])}return !t.apply(this,e)}}Sa.Cache=Pr;var La=ui((function(t,e){var r=(e=1==e.length&&Ea(e[0])?de(e[0],Ne(Zi())):de(an(e,1),Ne(Zi()))).length;return In((function(n){for(var i=-1,o=sr(n.length,r);++i=e})),Wa=wn(function(){return arguments}())?wn:function(t){return Ga(t)&&_t.call(t,"callee")&&!Kt.call(t,"callee")},Ea=n.isArray,Pa=Qt?Ne(Qt):function(t){return Ga(t)&&pn(t)==_};function Ra(t){return null!=t&&Ua(t.length)&&!ja(t)}function Ha(t){return Ga(t)&&Ra(t)}var Fa=rr||al,Ia=te?Ne(te):function(t){return Ga(t)&&pn(t)==f};function za(t){if(!Ga(t))return !1;var e=pn(t);return e==h||"[object DOMException]"==e||"string"==typeof t.message&&"string"==typeof t.name&&!$a(t)}function ja(t){if(!Va(t))return !1;var e=pn(t);return e==d||e==p||"[object AsyncFunction]"==e||"[object Proxy]"==e}function Ba(t){return "number"==typeof t&&t==is(t)}function Ua(t){return "number"==typeof t&&t>-1&&t%1==0&&t<=9007199254740991}function Va(t){var e=typeof t;return null!=t&&("object"==e||"function"==e)}function Ga(t){return null!=t&&"object"==typeof t}var Ka=ee?Ne(ee):function(t){return Ga(t)&&no(t)==v};function qa(t){return "number"==typeof t||Ga(t)&&pn(t)==g}function $a(t){if(!Ga(t)||pn(t)!=m)return !1;var e=Bt(t);if(null===e)return !0;var r=_t.call(e,"constructor")&&e.constructor;return "function"==typeof r&&r instanceof r&&Ct.call(r)==Mt}var Xa=re?Ne(re):function(t){return Ga(t)&&pn(t)==y};var Ya=ne?Ne(ne):function(t){return Ga(t)&&no(t)==b};function Za(t){return "string"==typeof t||!Ea(t)&&Ga(t)&&pn(t)==w}function Ja(t){return "symbol"==typeof t||Ga(t)&&pn(t)==x}var Qa=ie?Ne(ie):function(t){return Ga(t)&&Ua(t.length)&&!!zt[pn(t)]};var ts=Pi(Mn),es=Pi((function(t,e){return t<=e}));function rs(t){if(!t)return [];if(Ra(t))return Za(t)?qe(t):yi(t);if(Zt&&t[Zt])return function(t){for(var e,r=[];!(e=t.next()).done;)r.push(e.value);return r}(t[Zt]());var e=no(t);return (e==v?je:e==b?Ve:As)(t)}function ns(t){return t?(t=as(t))===1/0||t===-1/0?17976931348623157e292*(t<0?-1:1):t==t?t:0:0===t?t:0}function is(t){var e=ns(t),r=e%1;return e==e?r?e-r:e:0}function os(t){return t?Xr(is(t),0,4294967295):0}function as(t){if("number"==typeof t)return t;if(Ja(t))return NaN;if(Va(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=Va(e)?e+"":e;}if("string"!=typeof t)return 0===t?t:+t;t=Ae(t);var r=ot.test(t);return r||st.test(t)?Vt(t.slice(2),r?2:8):it.test(t)?NaN:+t}function ss(t){return bi(t,Cs(t))}function ls(t){return null==t?"":Jn(t)}var us=xi((function(t,e){if(ho(e)||Ra(e))bi(e,xs(e),t);else for(var r in e)_t.call(e,r)&&Ur(t,r,e[r]);})),cs=xi((function(t,e){bi(e,Cs(e),t);})),fs=xi((function(t,e,r,n){bi(e,Cs(e),t,n);})),hs=xi((function(t,e,r,n){bi(e,xs(e),t,n);})),ds=Gi($r);var ps=In((function(t,e){t=pt(t);var r=-1,n=e.length,i=n>2?e[2]:void 0;for(i&&lo(e[0],e[1],i)&&(n=1);++r1),e})),bi(t,qi(t),r),n&&(r=Yr(r,7,Ui));for(var i=e.length;i--;)ti(r,e[i]);return r}));var Ls=Gi((function(t,e){return null==t?{}:function(t,e){return En(t,e,(function(e,r){return ms(t,r)}))}(t,e)}));function Ms(t,e){if(null==t)return {};var r=de(qi(t),(function(t){return [t]}));return e=Zi(e),En(t,r,(function(t,r){return e(t,r[0])}))}var Ts=Ii(xs),Os=Ii(Cs);function As(t){return null==t?[]:De(t,xs(t))}var Ns=ki((function(t,e,r){return e=e.toLowerCase(),t+(r?Ds(e):e)}));function Ds(t){return zs(ls(t).toLowerCase())}function Ws(t){return (t=ls(t))&&t.replace(ut,He).replace(Wt,"")}var Es=ki((function(t,e,r){return t+(r?"-":"")+e.toLowerCase()})),Ps=ki((function(t,e,r){return t+(r?" ":"")+e.toLowerCase()})),Rs=Si("toLowerCase");var Hs=ki((function(t,e,r){return t+(r?"_":"")+e.toLowerCase()}));var Fs=ki((function(t,e,r){return t+(r?" ":"")+zs(e)}));var Is=ki((function(t,e,r){return t+(r?" ":"")+e.toUpperCase()})),zs=Si("toUpperCase");function js(t,e,r){return t=ls(t),void 0===(e=r?void 0:e)?function(t){return Ht.test(t)}(t)?function(t){return t.match(Pt)||[]}(t):function(t){return t.match(Q)||[]}(t):t.match(e)||[]}var Bs=In((function(t,e){try{return oe(t,void 0,e)}catch(t){return za(t)?t:new X(t)}})),Us=Gi((function(t,e){return se(e,(function(e){e=Mo(e),qr(t,e,ba(t[e],t));})),t}));function Vs(t){return function(){return t}}var Gs=Ti(),Ks=Ti(!0);function qs(t){return t}function $s(t){return Sn("function"==typeof t?t:Yr(t,1))}var Xs=In((function(t,e){return function(r){return bn(r,t,e)}})),Ys=In((function(t,e){return function(r){return bn(t,r,e)}}));function Zs(t,e,r){var n=xs(e),i=fn(e,n);null!=r||Va(e)&&(i.length||!n.length)||(r=e,e=t,t=this,i=fn(e,xs(e)));var o=!(Va(r)&&"chain"in r&&!r.chain),a=ja(t);return se(i,(function(r){var n=e[r];t[r]=n,a&&(t.prototype[r]=function(){var e=this.__chain__;if(o||e){var r=t(this.__wrapped__),i=r.__actions__=yi(this.__actions__);return i.push({func:n,args:arguments,thisArg:t}),r.__chain__=e,r}return n.apply(t,pe([this.value()],arguments))});})),t}function Js(){}var Qs=Di(de),tl=Di(ue),el=Di(me);function rl(t){return uo(t)?ke(Mo(t)):function(t){return function(e){return hn(e,t)}}(t)}var nl=Ei(),il=Ei(!0);function ol(){return []}function al(){return !1}var sl=Ni((function(t,e){return t+e}),0),ll=Hi("ceil"),ul=Ni((function(t,e){return t/e}),1),cl=Hi("floor");var fl,hl=Ni((function(t,e){return t*e}),1),dl=Hi("round"),pl=Ni((function(t,e){return t-e}),0);return Tr.after=function(t,e){if("function"!=typeof e)throw new mt(o);return t=is(t),function(){if(--t<1)return e.apply(this,arguments)}},Tr.ary=ma,Tr.assign=us,Tr.assignIn=cs,Tr.assignInWith=fs,Tr.assignWith=hs,Tr.at=ds,Tr.before=ya,Tr.bind=ba,Tr.bindAll=Us,Tr.bindKey=wa,Tr.castArray=function(){if(!arguments.length)return [];var t=arguments[0];return Ea(t)?t:[t]},Tr.chain=ra,Tr.chunk=function(t,e,r){e=(r?lo(t,e,r):void 0===e)?1:ar(is(e),0);var i=null==t?0:t.length;if(!i||e<1)return [];for(var o=0,a=0,s=n(Qe(i/e));oi?0:i+r),(n=void 0===n||n>i?i:is(n))<0&&(n+=i),n=r>n?0:os(n);r>>0)?(t=ls(t))&&("string"==typeof e||null!=e&&!Xa(e))&&!(e=Jn(e))&&ze(t)?ci(qe(t),0,r):t.split(e,r):[]},Tr.spread=function(t,e){if("function"!=typeof t)throw new mt(o);return e=null==e?0:ar(is(e),0),In((function(r){var n=r[e],i=ci(r,0,e);return n&&pe(i,n),oe(t,this,i)}))},Tr.tail=function(t){var e=null==t?0:t.length;return e?Kn(t,1,e):[]},Tr.take=function(t,e,r){return t&&t.length?Kn(t,0,(e=r||void 0===e?1:is(e))<0?0:e):[]},Tr.takeRight=function(t,e,r){var n=null==t?0:t.length;return n?Kn(t,(e=n-(e=r||void 0===e?1:is(e)))<0?0:e,n):[]},Tr.takeRightWhile=function(t,e){return t&&t.length?ri(t,Zi(e,3),!1,!0):[]},Tr.takeWhile=function(t,e){return t&&t.length?ri(t,Zi(e,3)):[]},Tr.tap=function(t,e){return e(t),t},Tr.throttle=function(t,e,r){var n=!0,i=!0;if("function"!=typeof t)throw new mt(o);return Va(r)&&(n="leading"in r?!!r.leading:n,i="trailing"in r?!!r.trailing:i),xa(t,e,{leading:n,maxWait:e,trailing:i})},Tr.thru=na,Tr.toArray=rs,Tr.toPairs=Ts,Tr.toPairsIn=Os,Tr.toPath=function(t){return Ea(t)?de(t,Mo):Ja(t)?[t]:yi(Lo(ls(t)))},Tr.toPlainObject=ss,Tr.transform=function(t,e,r){var n=Ea(t),i=n||Fa(t)||Qa(t);if(e=Zi(e,4),null==r){var o=t&&t.constructor;r=i?n?new o:[]:Va(t)&&ja(o)?Or(Bt(t)):{};}return (i?se:un)(t,(function(t,n,i){return e(r,t,n,i)})),r},Tr.unary=function(t){return ma(t,1)},Tr.union=Go,Tr.unionBy=Ko,Tr.unionWith=qo,Tr.uniq=function(t){return t&&t.length?Qn(t):[]},Tr.uniqBy=function(t,e){return t&&t.length?Qn(t,Zi(e,2)):[]},Tr.uniqWith=function(t,e){return e="function"==typeof e?e:void 0,t&&t.length?Qn(t,void 0,e):[]},Tr.unset=function(t,e){return null==t||ti(t,e)},Tr.unzip=$o,Tr.unzipWith=Xo,Tr.update=function(t,e,r){return null==t?t:ei(t,e,si(r))},Tr.updateWith=function(t,e,r,n){return n="function"==typeof n?n:void 0,null==t?t:ei(t,e,si(r),n)},Tr.values=As,Tr.valuesIn=function(t){return null==t?[]:De(t,Cs(t))},Tr.without=Yo,Tr.words=js,Tr.wrap=function(t,e){return Ma(si(e),t)},Tr.xor=Zo,Tr.xorBy=Jo,Tr.xorWith=Qo,Tr.zip=ta,Tr.zipObject=function(t,e){return oi(t||[],e||[],Ur)},Tr.zipObjectDeep=function(t,e){return oi(t||[],e||[],Bn)},Tr.zipWith=ea,Tr.entries=Ts,Tr.entriesIn=Os,Tr.extend=cs,Tr.extendWith=fs,Zs(Tr,Tr),Tr.add=sl,Tr.attempt=Bs,Tr.camelCase=Ns,Tr.capitalize=Ds,Tr.ceil=ll,Tr.clamp=function(t,e,r){return void 0===r&&(r=e,e=void 0),void 0!==r&&(r=(r=as(r))==r?r:0),void 0!==e&&(e=(e=as(e))==e?e:0),Xr(as(t),e,r)},Tr.clone=function(t){return Yr(t,4)},Tr.cloneDeep=function(t){return Yr(t,5)},Tr.cloneDeepWith=function(t,e){return Yr(t,5,e="function"==typeof e?e:void 0)},Tr.cloneWith=function(t,e){return Yr(t,4,e="function"==typeof e?e:void 0)},Tr.conformsTo=function(t,e){return null==e||Zr(t,e,xs(e))},Tr.deburr=Ws,Tr.defaultTo=function(t,e){return null==t||t!=t?e:t},Tr.divide=ul,Tr.endsWith=function(t,e,r){t=ls(t),e=Jn(e);var n=t.length,i=r=void 0===r?n:Xr(is(r),0,n);return (r-=e.length)>=0&&t.slice(r,i)==e},Tr.eq=Aa,Tr.escape=function(t){return (t=ls(t))&&I.test(t)?t.replace(H,Fe):t},Tr.escapeRegExp=function(t){return (t=ls(t))&&q.test(t)?t.replace(K,"\\$&"):t},Tr.every=function(t,e,r){var n=Ea(t)?ue:rn;return r&&lo(t,e,r)&&(e=void 0),n(t,Zi(e,3))},Tr.find=aa,Tr.findIndex=Wo,Tr.findKey=function(t,e){return be(t,Zi(e,3),un)},Tr.findLast=sa,Tr.findLastIndex=Eo,Tr.findLastKey=function(t,e){return be(t,Zi(e,3),cn)},Tr.floor=cl,Tr.forEach=la,Tr.forEachRight=ua,Tr.forIn=function(t,e){return null==t?t:sn(t,Zi(e,3),Cs)},Tr.forInRight=function(t,e){return null==t?t:ln(t,Zi(e,3),Cs)},Tr.forOwn=function(t,e){return t&&un(t,Zi(e,3))},Tr.forOwnRight=function(t,e){return t&&cn(t,Zi(e,3))},Tr.get=gs,Tr.gt=Na,Tr.gte=Da,Tr.has=function(t,e){return null!=t&&io(t,e,gn)},Tr.hasIn=ms,Tr.head=Ro,Tr.identity=qs,Tr.includes=function(t,e,r,n){t=Ra(t)?t:As(t),r=r&&!n?is(r):0;var i=t.length;return r<0&&(r=ar(i+r,0)),Za(t)?r<=i&&t.indexOf(e,r)>-1:!!i&&xe(t,e,r)>-1},Tr.indexOf=function(t,e,r){var n=null==t?0:t.length;if(!n)return -1;var i=null==r?0:is(r);return i<0&&(i=ar(n+i,0)),xe(t,e,i)},Tr.inRange=function(t,e,r){return e=ns(e),void 0===r?(r=e,e=0):r=ns(r),function(t,e,r){return t>=sr(e,r)&&t=-9007199254740991&&t<=9007199254740991},Tr.isSet=Ya,Tr.isString=Za,Tr.isSymbol=Ja,Tr.isTypedArray=Qa,Tr.isUndefined=function(t){return void 0===t},Tr.isWeakMap=function(t){return Ga(t)&&no(t)==C},Tr.isWeakSet=function(t){return Ga(t)&&"[object WeakSet]"==pn(t)},Tr.join=function(t,e){return null==t?"":ir.call(t,e)},Tr.kebabCase=Es,Tr.last=zo,Tr.lastIndexOf=function(t,e,r){var n=null==t?0:t.length;if(!n)return -1;var i=n;return void 0!==r&&(i=(i=is(r))<0?ar(n+i,0):sr(i,n-1)),e==e?function(t,e,r){for(var n=r+1;n--;)if(t[n]===e)return n;return n}(t,e,i):we(t,_e,i,!0)},Tr.lowerCase=Ps,Tr.lowerFirst=Rs,Tr.lt=ts,Tr.lte=es,Tr.max=function(t){return t&&t.length?nn(t,qs,vn):void 0},Tr.maxBy=function(t,e){return t&&t.length?nn(t,Zi(e,2),vn):void 0},Tr.mean=function(t){return Se(t,qs)},Tr.meanBy=function(t,e){return Se(t,Zi(e,2))},Tr.min=function(t){return t&&t.length?nn(t,qs,Mn):void 0},Tr.minBy=function(t,e){return t&&t.length?nn(t,Zi(e,2),Mn):void 0},Tr.stubArray=ol,Tr.stubFalse=al,Tr.stubObject=function(){return {}},Tr.stubString=function(){return ""},Tr.stubTrue=function(){return !0},Tr.multiply=hl,Tr.nth=function(t,e){return t&&t.length?Dn(t,is(e)):void 0},Tr.noConflict=function(){return qt._===this&&(qt._=Tt),this},Tr.noop=Js,Tr.now=ga,Tr.pad=function(t,e,r){t=ls(t);var n=(e=is(e))?Ke(t):0;if(!e||n>=e)return t;var i=(e-n)/2;return Wi(tr(i),r)+t+Wi(Qe(i),r)},Tr.padEnd=function(t,e,r){t=ls(t);var n=(e=is(e))?Ke(t):0;return e&&ne){var n=t;t=e,e=n;}if(r||t%1||e%1){var i=cr();return sr(t+i*(e-t+Ut("1e-"+((i+"").length-1))),e)}return Hn(t,e)},Tr.reduce=function(t,e,r){var n=Ea(t)?ve:Me,i=arguments.length<3;return n(t,Zi(e,4),r,i,tn)},Tr.reduceRight=function(t,e,r){var n=Ea(t)?ge:Me,i=arguments.length<3;return n(t,Zi(e,4),r,i,en)},Tr.repeat=function(t,e,r){return e=(r?lo(t,e,r):void 0===e)?1:is(e),Fn(ls(t),e)},Tr.replace=function(){var t=arguments,e=ls(t[0]);return t.length<3?e:e.replace(t[1],t[2])},Tr.result=function(t,e,r){var n=-1,i=(e=li(e,t)).length;for(i||(i=1,t=void 0);++n9007199254740991)return [];var r=4294967295,n=sr(t,4294967295);t-=4294967295;for(var i=Oe(n,e=Zi(e));++r=o)return t;var s=r-Ke(n);if(s<1)return n;var l=a?ci(a,0,s).join(""):t.slice(0,s);if(void 0===i)return l+n;if(a&&(s+=l.length-s),Xa(i)){if(t.slice(s).search(i)){var u,c=l;for(i.global||(i=vt(i.source,ls(nt.exec(i))+"g")),i.lastIndex=0;u=i.exec(c);)var f=u.index;l=l.slice(0,void 0===f?s:f);}}else if(t.indexOf(Jn(i),s)!=s){var h=l.lastIndexOf(i);h>-1&&(l=l.slice(0,h));}return l+n},Tr.unescape=function(t){return (t=ls(t))&&F.test(t)?t.replace(R,Xe):t},Tr.uniqueId=function(t){var e=++St;return ls(t)+e},Tr.upperCase=Is,Tr.upperFirst=zs,Tr.each=la,Tr.eachRight=ua,Tr.first=Ro,Zs(Tr,(fl={},un(Tr,(function(t,e){_t.call(Tr.prototype,e)||(fl[e]=t);})),fl),{chain:!1}),Tr.VERSION="4.17.21",se(["bind","bindKey","curry","curryRight","partial","partialRight"],(function(t){Tr[t].placeholder=Tr;})),se(["drop","take"],(function(t,e){Dr.prototype[t]=function(r){r=void 0===r?1:ar(is(r),0);var n=this.__filtered__&&!e?new Dr(this):this.clone();return n.__filtered__?n.__takeCount__=sr(r,n.__takeCount__):n.__views__.push({size:sr(r,4294967295),type:t+(n.__dir__<0?"Right":"")}),n},Dr.prototype[t+"Right"]=function(e){return this.reverse()[t](e).reverse()};})),se(["filter","map","takeWhile"],(function(t,e){var r=e+1,n=1==r||3==r;Dr.prototype[t]=function(t){var e=this.clone();return e.__iteratees__.push({iteratee:Zi(t,3),type:r}),e.__filtered__=e.__filtered__||n,e};})),se(["head","last"],(function(t,e){var r="take"+(e?"Right":"");Dr.prototype[t]=function(){return this[r](1).value()[0]};})),se(["initial","tail"],(function(t,e){var r="drop"+(e?"":"Right");Dr.prototype[t]=function(){return this.__filtered__?new Dr(this):this[r](1)};})),Dr.prototype.compact=function(){return this.filter(qs)},Dr.prototype.find=function(t){return this.filter(t).head()},Dr.prototype.findLast=function(t){return this.reverse().find(t)},Dr.prototype.invokeMap=In((function(t,e){return "function"==typeof t?new Dr(this):this.map((function(r){return bn(r,t,e)}))})),Dr.prototype.reject=function(t){return this.filter(ka(Zi(t)))},Dr.prototype.slice=function(t,e){t=is(t);var r=this;return r.__filtered__&&(t>0||e<0)?new Dr(r):(t<0?r=r.takeRight(-t):t&&(r=r.drop(t)),void 0!==e&&(r=(e=is(e))<0?r.dropRight(-e):r.take(e-t)),r)},Dr.prototype.takeRightWhile=function(t){return this.reverse().takeWhile(t).reverse()},Dr.prototype.toArray=function(){return this.take(4294967295)},un(Dr.prototype,(function(t,e){var r=/^(?:filter|find|map|reject)|While$/.test(e),n=/^(?:head|last)$/.test(e),i=Tr[n?"take"+("last"==e?"Right":""):e],o=n||/^find/.test(e);i&&(Tr.prototype[e]=function(){var e=this.__wrapped__,a=n?[1]:arguments,s=e instanceof Dr,l=a[0],u=s||Ea(e),c=function(t){var e=i.apply(Tr,pe([t],a));return n&&f?e[0]:e};u&&r&&"function"==typeof l&&1!=l.length&&(s=u=!1);var f=this.__chain__,h=!!this.__actions__.length,d=o&&!f,p=s&&!h;if(!o&&u){e=p?e:new Dr(this);var v=t.apply(e,a);return v.__actions__.push({func:na,args:[c],thisArg:void 0}),new Nr(v,f)}return d&&p?t.apply(this,a):(v=this.thru(c),d?n?v.value()[0]:v.value():v)});})),se(["pop","push","shift","sort","splice","unshift"],(function(t){var e=yt[t],r=/^(?:push|sort|unshift)$/.test(t)?"tap":"thru",n=/^(?:pop|shift)$/.test(t);Tr.prototype[t]=function(){var t=arguments;if(n&&!this.__chain__){var i=this.value();return e.apply(Ea(i)?i:[],t)}return this[r]((function(r){return e.apply(Ea(r)?r:[],t)}))};})),un(Dr.prototype,(function(t,e){var r=Tr[e];if(r){var n=r.name+"";_t.call(br,n)||(br[n]=[]),br[n].push({name:e,func:r});}})),br[Oi(void 0,2).name]=[{name:"wrapper",func:void 0}],Dr.prototype.clone=function(){var t=new Dr(this.__wrapped__);return t.__actions__=yi(this.__actions__),t.__dir__=this.__dir__,t.__filtered__=this.__filtered__,t.__iteratees__=yi(this.__iteratees__),t.__takeCount__=this.__takeCount__,t.__views__=yi(this.__views__),t},Dr.prototype.reverse=function(){if(this.__filtered__){var t=new Dr(this);t.__dir__=-1,t.__filtered__=!0;}else (t=this.clone()).__dir__*=-1;return t},Dr.prototype.value=function(){var t=this.__wrapped__.value(),e=this.__dir__,r=Ea(t),n=e<0,i=r?t.length:0,o=function(t,e,r){var n=-1,i=r.length;for(;++n=this.__values__.length;return {done:t,value:t?void 0:this.__values__[this.__index__++]}},Tr.prototype.plant=function(t){for(var e,r=this;r instanceof Ar;){var n=Oo(r);n.__index__=0,n.__values__=void 0,e?i.__wrapped__=n:e=n;var i=n;r=r.__wrapped__;}return i.__wrapped__=t,e},Tr.prototype.reverse=function(){var t=this.__wrapped__;if(t instanceof Dr){var e=t;return this.__actions__.length&&(e=new Dr(this)),(e=e.reverse()).__actions__.push({func:na,args:[Vo],thisArg:void 0}),new Nr(e,this.__chain__)}return this.thru(Vo)},Tr.prototype.toJSON=Tr.prototype.valueOf=Tr.prototype.value=function(){return ni(this.__wrapped__,this.__actions__)},Tr.prototype.first=Tr.prototype.head,Zt&&(Tr.prototype[Zt]=function(){return this}),Tr}();qt._=Ye,void 0===(i=function(){return Ye}.call(e,r,e,n))||(n.exports=i);}).call(this);}).call(this,r(7),r(21)(t));},function(e,r){e.exports=t;},function(t,e,r){t.exports=function(){var t=navigator.userAgent,e=navigator.platform,r=/gecko\/\d/i.test(t),n=/MSIE \d/.test(t),i=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(t),o=/Edge\/(\d+)/.exec(t),a=n||i||o,s=a&&(n?document.documentMode||6:+(o||i)[1]),l=!o&&/WebKit\//.test(t),u=l&&/Qt\/\d+\.\d+/.test(t),c=!o&&/Chrome\//.test(t),f=/Opera\//.test(t),h=/Apple Computer/.test(navigator.vendor),d=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(t),p=/PhantomJS/.test(t),v=!o&&/AppleWebKit/.test(t)&&/Mobile\/\w+/.test(t),g=/Android/.test(t),m=v||g||/webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(t),y=v||/Mac/.test(e),b=/\bCrOS\b/.test(t),w=/win/i.test(e),x=f&&t.match(/Version\/(\d*\.\d*)/);x&&(x=Number(x[1])),x&&x>=15&&(f=!1,l=!0);var C=y&&(u||f&&(null==x||x<12.11)),_=r||a&&s>=9;function S(t){return new RegExp("(^|\\s)"+t+"(?:$|\\s)\\s*")}var k,L=function(t,e){var r=t.className,n=S(e).exec(r);if(n){var i=r.slice(n.index+n[0].length);t.className=r.slice(0,n.index)+(i?n[1]+i:"");}};function M(t){for(var e=t.childNodes.length;e>0;--e)t.removeChild(t.firstChild);return t}function T(t,e){return M(t).appendChild(e)}function O(t,e,r,n){var i=document.createElement(t);if(r&&(i.className=r),n&&(i.style.cssText=n),"string"==typeof e)i.appendChild(document.createTextNode(e));else if(e)for(var o=0;o=e)return a+(e-o);a+=s-o,a+=r-a%r,o=s+1;}}v?P=function(t){t.selectionStart=0,t.selectionEnd=t.value.length;}:a&&(P=function(t){try{t.select();}catch(t){}});var I=function(){this.id=null;};function z(t,e){for(var r=0;r=e)return n+Math.min(a,e-i);if(i+=o-n,n=o+1,(i+=r-i%r)>=e)return n}}var K=[""];function q(t){for(;K.length<=t;)K.push($(K)+" ");return K[t]}function $(t){return t[t.length-1]}function X(t,e){for(var r=[],n=0;n"€"&&(t.toUpperCase()!=t.toLowerCase()||J.test(t))}function tt(t,e){return e?!!(e.source.indexOf("\\w")>-1&&Q(t))||e.test(t):Q(t)}function et(t){for(var e in t)if(t.hasOwnProperty(e)&&t[e])return !1;return !0}var rt=/[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;function nt(t){return t.charCodeAt(0)>=768&&rt.test(t)}function it(t,e,r){for(;(r<0?e>0:er?-1:1;;){if(e==r)return e;var i=(e+r)/2,o=n<0?Math.ceil(i):Math.floor(i);if(o==e)return t(o)?e:r;t(o)?r=o:e=o+n;}}function at(t,e,n){var i=this;this.input=n,i.scrollbarFiller=O("div",null,"CodeMirror-scrollbar-filler"),i.scrollbarFiller.setAttribute("cm-not-content","true"),i.gutterFiller=O("div",null,"CodeMirror-gutter-filler"),i.gutterFiller.setAttribute("cm-not-content","true"),i.lineDiv=A("div",null,"CodeMirror-code"),i.selectionDiv=O("div",null,null,"position: relative; z-index: 1"),i.cursorDiv=O("div",null,"CodeMirror-cursors"),i.measure=O("div",null,"CodeMirror-measure"),i.lineMeasure=O("div",null,"CodeMirror-measure"),i.lineSpace=A("div",[i.measure,i.lineMeasure,i.selectionDiv,i.cursorDiv,i.lineDiv],null,"position: relative; outline: none");var o=A("div",[i.lineSpace],"CodeMirror-lines");i.mover=O("div",[o],null,"position: relative"),i.sizer=O("div",[i.mover],"CodeMirror-sizer"),i.sizerWidth=null,i.heightForcer=O("div",null,null,"position: absolute; height: 30px; width: 1px;"),i.gutters=O("div",null,"CodeMirror-gutters"),i.lineGutter=null,i.scroller=O("div",[i.sizer,i.heightForcer,i.gutters],"CodeMirror-scroll"),i.scroller.setAttribute("tabIndex","-1"),i.wrapper=O("div",[i.scrollbarFiller,i.gutterFiller,i.scroller],"CodeMirror"),a&&s<8&&(i.gutters.style.zIndex=-1,i.scroller.style.paddingRight=0),l||r&&m||(i.scroller.draggable=!0),t&&(t.appendChild?t.appendChild(i.wrapper):t(i.wrapper)),i.viewFrom=i.viewTo=e.first,i.reportedViewFrom=i.reportedViewTo=e.first,i.view=[],i.renderedView=null,i.externalMeasured=null,i.viewOffset=0,i.lastWrapHeight=i.lastWrapWidth=0,i.updateLineNumbers=null,i.nativeBarWidth=i.barHeight=i.barWidth=0,i.scrollbarsClipped=!1,i.lineNumWidth=i.lineNumInnerWidth=i.lineNumChars=null,i.alignWidgets=!1,i.cachedCharWidth=i.cachedTextHeight=i.cachedPaddingH=null,i.maxLine=null,i.maxLineLength=0,i.maxLineChanged=!1,i.wheelDX=i.wheelDY=i.wheelStartX=i.wheelStartY=null,i.shift=!1,i.selForContextMenu=null,i.activeTouch=null,n.init(i);}function st(t,e){if((e-=t.first)<0||e>=t.size)throw new Error("There is no line "+(e+t.first)+" in the document.");for(var r=t;!r.lines;)for(var n=0;;++n){var i=r.children[n],o=i.chunkSize();if(e=t.first&&er?vt(r,st(t,r).text.length):function(t,e){var r=t.ch;return null==r||r>e?vt(t.line,e):r<0?vt(t.line,0):t}(e,st(t,e.line).text.length)}function _t(t,e){for(var r=[],n=0;n=e:o.to>e);(n||(n=[])).push(new Lt(a,o.from,s?null:o.to));}}return n}(r,i,a),l=function(t,e,r){var n;if(t)for(var i=0;i=e:o.to>e)||o.from==e&&"bookmark"==a.type&&(!r||o.marker.insertLeft)){var s=null==o.from||(a.inclusiveLeft?o.from<=e:o.from0&&s)for(var b=0;be)&&(!r||Pt(r,o.marker)<0)&&(r=o.marker);}return r}function zt(t,e,r,n,i){var o=st(t,e),a=kt&&o.markedSpans;if(a)for(var s=0;s=0&&f<=0||c<=0&&f>=0)&&(c<=0&&(l.marker.inclusiveRight&&i.inclusiveLeft?gt(u.to,r)>=0:gt(u.to,r)>0)||c>=0&&(l.marker.inclusiveRight&&i.inclusiveLeft?gt(u.from,n)<=0:gt(u.from,n)<0)))return !0}}}function jt(t){for(var e;e=Ht(t);)t=e.find(-1,!0).line;return t}function Bt(t,e){var r=st(t,e),n=jt(r);return r==n?e:ft(n)}function Ut(t,e){if(e>t.lastLine())return e;var r,n=st(t,e);if(!Vt(t,n))return e;for(;r=Ft(n);)n=r.find(1,!0).line;return ft(n)+1}function Vt(t,e){var r=kt&&e.markedSpans;if(r)for(var n=void 0,i=0;ie.maxLineLength&&(e.maxLineLength=r,e.maxLine=t);}));}var Xt=null;function Yt(t,e,r){var n;Xt=null;for(var i=0;ie)return i;o.to==e&&(o.from!=o.to&&"before"==r?n=i:Xt=i),o.from==e&&(o.from!=o.to&&"before"!=r?n=i:Xt=i);}return null!=n?n:Xt}var Zt=function(){var t=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,e=/[stwN]/,r=/[LRr]/,n=/[Lb1n]/,i=/[1n]/;function o(t,e,r){this.level=t,this.from=e,this.to=r;}return function(a,s){var l="ltr"==s?"L":"R";if(0==a.length||"ltr"==s&&!t.test(a))return !1;for(var u,c=a.length,f=[],h=0;h-1&&(n[e]=i.slice(0,o).concat(i.slice(o+1)));}}}function ne(t,e){var r=ee(t,e);if(r.length)for(var n=Array.prototype.slice.call(arguments,2),i=0;i0}function se(t){t.prototype.on=function(t,e){te(this,t,e);},t.prototype.off=function(t,e){re(this,t,e);};}function le(t){t.preventDefault?t.preventDefault():t.returnValue=!1;}function ue(t){t.stopPropagation?t.stopPropagation():t.cancelBubble=!0;}function ce(t){return null!=t.defaultPrevented?t.defaultPrevented:0==t.returnValue}function fe(t){le(t),ue(t);}function he(t){return t.target||t.srcElement}function de(t){var e=t.which;return null==e&&(1&t.button?e=1:2&t.button?e=3:4&t.button&&(e=2)),y&&t.ctrlKey&&1==e&&(e=3),e}var pe,ve,ge=function(){if(a&&s<9)return !1;var t=O("div");return "draggable"in t||"dragDrop"in t}();function me(t){if(null==pe){var e=O("span","​");T(t,O("span",[e,document.createTextNode("x")])),0!=t.firstChild.offsetHeight&&(pe=e.offsetWidth<=1&&e.offsetHeight>2&&!(a&&s<8));}var r=pe?O("span","​"):O("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px");return r.setAttribute("cm-text",""),r}function ye(t){if(null!=ve)return ve;var e=T(t,document.createTextNode("AخA")),r=k(e,0,1).getBoundingClientRect(),n=k(e,1,2).getBoundingClientRect();return M(t),!(!r||r.left==r.right)&&(ve=n.right-r.right<3)}var be,we=3!="\n\nb".split(/\n/).length?function(t){for(var e=0,r=[],n=t.length;e<=n;){var i=t.indexOf("\n",e);-1==i&&(i=t.length);var o=t.slice(e,"\r"==t.charAt(i-1)?i-1:i),a=o.indexOf("\r");-1!=a?(r.push(o.slice(0,a)),e+=a+1):(r.push(o),e=i+1);}return r}:function(t){return t.split(/\r\n?|\n/)},xe=window.getSelection?function(t){try{return t.selectionStart!=t.selectionEnd}catch(t){return !1}}:function(t){var e;try{e=t.ownerDocument.selection.createRange();}catch(t){}return !(!e||e.parentElement()!=t)&&0!=e.compareEndPoints("StartToEnd",e)},Ce="oncopy"in(be=O("div"))||(be.setAttribute("oncopy","return;"),"function"==typeof be.oncopy),_e=null,Se={},ke={};function Le(t,e){arguments.length>2&&(e.dependencies=Array.prototype.slice.call(arguments,2)),Se[t]=e;}function Me(t){if("string"==typeof t&&ke.hasOwnProperty(t))t=ke[t];else if(t&&"string"==typeof t.name&&ke.hasOwnProperty(t.name)){var e=ke[t.name];"string"==typeof e&&(e={name:e}),(t=Z(e,t)).name=e.name;}else {if("string"==typeof t&&/^[\w\-]+\/[\w\-]+\+xml$/.test(t))return Me("application/xml");if("string"==typeof t&&/^[\w\-]+\/[\w\-]+\+json$/.test(t))return Me("application/json")}return "string"==typeof t?{name:t}:t||{name:"null"}}function Te(t,e){e=Me(e);var r=Se[e.name];if(!r)return Te(t,"text/plain");var n=r(t,e);if(Oe.hasOwnProperty(e.name)){var i=Oe[e.name];for(var o in i)i.hasOwnProperty(o)&&(n.hasOwnProperty(o)&&(n["_"+o]=n[o]),n[o]=i[o]);}if(n.name=e.name,e.helperType&&(n.helperType=e.helperType),e.modeProps)for(var a in e.modeProps)n[a]=e.modeProps[a];return n}var Oe={};function Ae(t,e){H(e,Oe.hasOwnProperty(t)?Oe[t]:Oe[t]={});}function Ne(t,e){if(!0===e)return e;if(t.copyState)return t.copyState(e);var r={};for(var n in e){var i=e[n];i instanceof Array&&(i=i.concat([])),r[n]=i;}return r}function De(t,e){for(var r;t.innerMode&&(r=t.innerMode(e))&&r.mode!=t;)e=r.state,t=r.mode;return r||{mode:t,state:e}}function We(t,e,r){return !t.startState||t.startState(e,r)}var Ee=function(t,e,r){this.pos=this.start=0,this.string=t,this.tabSize=e||8,this.lastColumnPos=this.lastColumnValue=0,this.lineStart=0,this.lineOracle=r;};Ee.prototype.eol=function(){return this.pos>=this.string.length},Ee.prototype.sol=function(){return this.pos==this.lineStart},Ee.prototype.peek=function(){return this.string.charAt(this.pos)||void 0},Ee.prototype.next=function(){if(this.pose},Ee.prototype.eatSpace=function(){for(var t=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>t},Ee.prototype.skipToEnd=function(){this.pos=this.string.length;},Ee.prototype.skipTo=function(t){var e=this.string.indexOf(t,this.pos);if(e>-1)return this.pos=e,!0},Ee.prototype.backUp=function(t){this.pos-=t;},Ee.prototype.column=function(){return this.lastColumnPos0?null:(n&&!1!==e&&(this.pos+=n[0].length),n)}var i=function(t){return r?t.toLowerCase():t};if(i(this.string.substr(this.pos,t.length))==i(t))return !1!==e&&(this.pos+=t.length),!0},Ee.prototype.current=function(){return this.string.slice(this.start,this.pos)},Ee.prototype.hideFirstChars=function(t,e){this.lineStart+=t;try{return e()}finally{this.lineStart-=t;}},Ee.prototype.lookAhead=function(t){var e=this.lineOracle;return e&&e.lookAhead(t)},Ee.prototype.baseToken=function(){var t=this.lineOracle;return t&&t.baseToken(this.pos)};var Pe=function(t,e){this.state=t,this.lookAhead=e;},Re=function(t,e,r,n){this.state=e,this.doc=t,this.line=r,this.maxLookAhead=n||0,this.baseTokens=null,this.baseTokenPos=1;};function He(t,e,r,n){var i=[t.state.modeGen],o={};Ke(t,e.text,t.doc.mode,r,(function(t,e){return i.push(t,e)}),o,n);for(var a=r.state,s=function(n){r.baseTokens=i;var s=t.state.overlays[n],l=1,u=0;r.state=!0,Ke(t,e.text,s.mode,r,(function(t,e){for(var r=l;ut&&i.splice(l,1,t,i[l+1],n),l+=2,u=Math.min(t,n);}if(e)if(s.opaque)i.splice(r,l-r,t,"overlay "+e),l=r+2;else for(;rt.options.maxHighlightLength&&Ne(t.doc.mode,n.state),o=He(t,e,n);i&&(n.state=i),e.stateAfter=n.save(!i),e.styles=o.styles,o.classes?e.styleClasses=o.classes:e.styleClasses&&(e.styleClasses=null),r===t.doc.highlightFrontier&&(t.doc.modeFrontier=Math.max(t.doc.modeFrontier,++t.doc.highlightFrontier));}return e.styles}function Ie(t,e,r){var n=t.doc,i=t.display;if(!n.mode.startState)return new Re(n,!0,e);var o=function(t,e,r){for(var n,i,o=t.doc,a=r?-1:e-(t.doc.mode.innerMode?1e3:100),s=e;s>a;--s){if(s<=o.first)return o.first;var l=st(o,s-1),u=l.stateAfter;if(u&&(!r||s+(u instanceof Pe?u.lookAhead:0)<=o.modeFrontier))return s;var c=F(l.text,null,t.options.tabSize);(null==i||n>c)&&(i=s-1,n=c);}return i}(t,e,r),a=o>n.first&&st(n,o-1).stateAfter,s=a?Re.fromSaved(n,a,o):new Re(n,We(n.mode),o);return n.iter(o,e,(function(r){ze(t,r.text,s);var n=s.line;r.stateAfter=n==e-1||n%5==0||n>=i.viewFrom&&ne.start)return o}throw new Error("Mode "+t.name+" failed to advance stream.")}Re.prototype.lookAhead=function(t){var e=this.doc.getLine(this.line+t);return null!=e&&t>this.maxLookAhead&&(this.maxLookAhead=t),e},Re.prototype.baseToken=function(t){if(!this.baseTokens)return null;for(;this.baseTokens[this.baseTokenPos]<=t;)this.baseTokenPos+=2;var e=this.baseTokens[this.baseTokenPos+1];return {type:e&&e.replace(/( |^)overlay .*/,""),size:this.baseTokens[this.baseTokenPos]-t}},Re.prototype.nextLine=function(){this.line++,this.maxLookAhead>0&&this.maxLookAhead--;},Re.fromSaved=function(t,e,r){return e instanceof Pe?new Re(t,Ne(t.mode,e.state),r,e.lookAhead):new Re(t,Ne(t.mode,e),r)},Re.prototype.save=function(t){var e=!1!==t?Ne(this.doc.mode,this.state):this.state;return this.maxLookAhead>0?new Pe(e,this.maxLookAhead):e};var Ue=function(t,e,r){this.start=t.start,this.end=t.pos,this.string=t.current(),this.type=e||null,this.state=r;};function Ve(t,e,r,n){var i,o,a=t.doc,s=a.mode,l=st(a,(e=Ct(a,e)).line),u=Ie(t,e.line,r),c=new Ee(l.text,t.options.tabSize,u);for(n&&(o=[]);(n||c.post.options.maxHighlightLength?(s=!1,a&&ze(t,e,n,f.pos),f.pos=e.length,l=null):l=Ge(Be(r,f,n.state,h),o),h){var d=h[0].name;d&&(l="m-"+(l?d+" "+l:d));}if(!s||c!=l){for(;u1&&!/ /.test(t))return t;for(var r=e,n="",i=0;iu&&f.from<=u);h++);if(f.to>=c)return t(r,n,i,o,a,s,l);t(r,n.slice(0,f.to-u),i,o,null,s,l),o=null,n=n.slice(f.to-u),u=f.to;}}}function rr(t,e,r,n){var i=!n&&r.widgetNode;i&&t.map.push(t.pos,t.pos+e,i),!n&&t.cm.display.input.needsContentAttribute&&(i||(i=t.content.appendChild(document.createElement("span"))),i.setAttribute("cm-marker",r.id)),i&&(t.cm.display.input.setUneditable(i),t.content.appendChild(i)),t.pos+=e,t.trailingSpace=!1;}function nr(t,e,r){var n=t.markedSpans,i=t.text,o=0;if(n)for(var a,s,l,u,c,f,h,d=i.length,p=0,v=1,g="",m=0;;){if(m==p){l=u=c=s="",h=null,f=null,m=1/0;for(var y=[],b=void 0,w=0;wp||C.collapsed&&x.to==p&&x.from==p)){if(null!=x.to&&x.to!=p&&m>x.to&&(m=x.to,u=""),C.className&&(l+=" "+C.className),C.css&&(s=(s?s+";":"")+C.css),C.startStyle&&x.from==p&&(c+=" "+C.startStyle),C.endStyle&&x.to==m&&(b||(b=[])).push(C.endStyle,x.to),C.title&&((h||(h={})).title=C.title),C.attributes)for(var _ in C.attributes)(h||(h={}))[_]=C.attributes[_];C.collapsed&&(!f||Pt(f.marker,C)<0)&&(f=x);}else x.from>p&&m>x.from&&(m=x.from);}if(b)for(var S=0;S=d)break;for(var L=Math.min(d,m);;){if(g){var M=p+g.length;if(!f){var T=M>L?g.slice(0,L-p):g;e.addToken(e,T,a?a+l:l,c,p+T.length==m?u:"",s,h);}if(M>=L){g=g.slice(L-p),p=L;break}p=M,c="";}g=i.slice(o,o=r[v++]),a=Ze(r[v++],e.cm.options);}}else for(var O=1;Or)return {map:t.measure.maps[i],cache:t.measure.caches[i],before:!0}}function Ar(t,e,r,n){return Wr(t,Dr(t,e),r,n)}function Nr(t,e){if(e>=t.display.viewFrom&&e=r.lineN&&e2&&o.push((l.bottom+u.top)/2-r.top);}}o.push(r.bottom-r.top);}}(t,e.view,e.rect),e.hasHeights=!0),(o=function(t,e,r,n){var i,o=Rr(e.map,r,n),l=o.node,u=o.start,c=o.end,f=o.collapse;if(3==l.nodeType){for(var h=0;h<4;h++){for(;u&&nt(e.line.text.charAt(o.coverStart+u));)--u;for(;o.coverStart+c1}(t))return e;var r=screen.logicalXDPI/screen.deviceXDPI,n=screen.logicalYDPI/screen.deviceYDPI;return {left:e.left*r,right:e.right*r,top:e.top*n,bottom:e.bottom*n}}(t.display.measure,i));}else {var d;u>0&&(f=n="right"),i=t.options.lineWrapping&&(d=l.getClientRects()).length>1?d["right"==n?d.length-1:0]:l.getBoundingClientRect();}if(a&&s<9&&!u&&(!i||!i.left&&!i.right)){var p=l.parentNode.getClientRects()[0];i=p?{left:p.left,right:p.left+on(t.display),top:p.top,bottom:p.bottom}:Pr;}for(var v=i.top-e.rect.top,g=i.bottom-e.rect.top,m=(v+g)/2,y=e.view.measure.heights,b=0;be)&&(i=(o=l-s)-1,e>=l&&(a="right")),null!=i){if(n=t[u+2],s==l&&r==(n.insertLeft?"left":"right")&&(a=r),"left"==r&&0==i)for(;u&&t[u-2]==t[u-3]&&t[u-1].insertLeft;)n=t[2+(u-=3)],a="left";if("right"==r&&i==l-s)for(;u=0&&(r=t[i]).left==r.right;i--);return r}function Fr(t){if(t.measure&&(t.measure.cache={},t.measure.heights=null,t.rest))for(var e=0;e=n.text.length?(l=n.text.length,u="before"):l<=0&&(l=0,u="after"),!s)return a("before"==u?l-1:l,"before"==u);function c(t,e,r){return a(r?t-1:t,1==s[e].level!=r)}var f=Yt(s,l,u),h=Xt,d=c(l,f,"before"==u);return null!=h&&(d.other=c(l,h,"before"!=u)),d}function $r(t,e){var r=0;e=Ct(t.doc,e),t.options.lineWrapping||(r=on(t.display)*e.ch);var n=st(t.doc,e.line),i=Kt(n)+_r(t.display);return {left:r,right:r,top:i,bottom:i+n.height}}function Xr(t,e,r,n,i){var o=vt(t,e,r);return o.xRel=i,n&&(o.outside=!0),o}function Yr(t,e,r){var n=t.doc;if((r+=t.display.viewOffset)<0)return Xr(n.first,0,null,!0,-1);var i=ht(n,r),o=n.first+n.size-1;if(i>o)return Xr(n.first+n.size-1,st(n,o).text.length,null,!0,1);e<0&&(e=0);for(var a=st(n,i);;){var s=tn(t,a,i,e,r),l=It(a,s.ch+(s.xRel>0?1:0));if(!l)return s;var u=l.find(1);if(u.line==i)return u;a=st(n,i=u.line);}}function Zr(t,e,r,n){n-=Ur(e);var i=e.text.length,o=ot((function(e){return Wr(t,r,e-1).bottom<=n}),i,0);return {begin:o,end:i=ot((function(e){return Wr(t,r,e).top>n}),o,i)}}function Jr(t,e,r,n){return r||(r=Dr(t,e)),Zr(t,e,r,Vr(t,e,Wr(t,r,n),"line").top)}function Qr(t,e,r,n){return !(t.bottom<=r)&&(t.top>r||(n?t.left:t.right)>e)}function tn(t,e,r,n,i){i-=Kt(e);var o=Dr(t,e),a=Ur(e),s=0,l=e.text.length,u=!0,c=Jt(e,t.doc.direction);if(c){var f=(t.options.lineWrapping?rn:en)(t,e,r,o,c,n,i);s=(u=1!=f.level)?f.from:f.to-1,l=u?f.to:f.from-1;}var h,d,p=null,v=null,g=ot((function(e){var r=Wr(t,o,e);return r.top+=a,r.bottom+=a,!!Qr(r,n,i,!1)&&(r.top<=i&&r.left<=n&&(p=e,v=r),!0)}),s,l),m=!1;if(v){var y=n-v.left=w.bottom;}return Xr(r,g=it(e.text,g,1),d,m,n-h)}function en(t,e,r,n,i,o,a){var s=ot((function(s){var l=i[s],u=1!=l.level;return Qr(qr(t,vt(r,u?l.to:l.from,u?"before":"after"),"line",e,n),o,a,!0)}),0,i.length-1),l=i[s];if(s>0){var u=1!=l.level,c=qr(t,vt(r,u?l.from:l.to,u?"after":"before"),"line",e,n);Qr(c,o,a,!0)&&c.top>a&&(l=i[s-1]);}return l}function rn(t,e,r,n,i,o,a){var s=Zr(t,e,n,a),l=s.begin,u=s.end;/\s/.test(e.text.charAt(u-1))&&u--;for(var c=null,f=null,h=0;h=u||d.to<=l)){var p=Wr(t,n,1!=d.level?Math.min(u,d.to)-1:Math.max(l,d.from)).right,v=pv)&&(c=d,f=v);}}return c||(c=i[i.length-1]),c.fromu&&(c={from:c.from,to:u,level:c.level}),c}function nn(t){if(null!=t.cachedTextHeight)return t.cachedTextHeight;if(null==Er){Er=O("pre");for(var e=0;e<49;++e)Er.appendChild(document.createTextNode("x")),Er.appendChild(O("br"));Er.appendChild(document.createTextNode("x"));}T(t.measure,Er);var r=Er.offsetHeight/50;return r>3&&(t.cachedTextHeight=r),M(t.measure),r||1}function on(t){if(null!=t.cachedCharWidth)return t.cachedCharWidth;var e=O("span","xxxxxxxxxx"),r=O("pre",[e]);T(t.measure,r);var n=e.getBoundingClientRect(),i=(n.right-n.left)/10;return i>2&&(t.cachedCharWidth=i),i||10}function an(t){for(var e=t.display,r={},n={},i=e.gutters.clientLeft,o=e.gutters.firstChild,a=0;o;o=o.nextSibling,++a)r[t.options.gutters[a]]=o.offsetLeft+o.clientLeft+i,n[t.options.gutters[a]]=o.clientWidth;return {fixedPos:sn(e),gutterTotalWidth:e.gutters.offsetWidth,gutterLeft:r,gutterWidth:n,wrapperWidth:e.wrapper.clientWidth}}function sn(t){return t.scroller.getBoundingClientRect().left-t.sizer.getBoundingClientRect().left}function ln(t){var e=nn(t.display),r=t.options.lineWrapping,n=r&&Math.max(5,t.display.scroller.clientWidth/on(t.display)-3);return function(i){if(Vt(t.doc,i))return 0;var o=0;if(i.widgets)for(var a=0;a=t.display.viewTo)return null;if((e-=t.display.viewFrom)<0)return null;for(var r=t.display.view,n=0;n=t.display.viewTo||s.to().linee||e==r&&a.to==e)&&(n(Math.max(a.from,e),Math.min(a.to,r),1==a.level?"rtl":"ltr",o),i=!0);}i||n(e,r,"ltr");}(v,r||0,null==n?h:n,(function(t,e,i,f){var g="ltr"==i,m=d(t,g?"left":"right"),y=d(e-1,g?"right":"left"),b=null==r&&0==t,w=null==n&&e==h,x=0==f,C=!v||f==v.length-1;if(y.top-m.top<=3){var _=(u?w:b)&&C,S=(u?b:w)&&x?s:(g?m:y).left,k=_?l:(g?y:m).right;c(S,m.top,k-S,m.bottom);}else {var L,M,T,O;g?(L=u&&b&&x?s:m.left,M=u?l:p(t,i,"before"),T=u?s:p(e,i,"after"),O=u&&w&&C?l:y.right):(L=u?p(t,i,"before"):s,M=!u&&b&&x?l:m.right,T=!u&&w&&C?s:y.left,O=u?p(e,i,"after"):l),c(L,m.top,M-L,m.bottom),m.bottom0?e.blinker=setInterval((function(){return e.cursorDiv.style.visibility=(r=!r)?"":"hidden"}),t.options.cursorBlinkRate):t.options.cursorBlinkRate<0&&(e.cursorDiv.style.visibility="hidden");}}function yn(t){t.state.focused||(t.display.input.focus(),wn(t));}function bn(t){t.state.delayingBlurEvent=!0,setTimeout((function(){t.state.delayingBlurEvent&&(t.state.delayingBlurEvent=!1,xn(t));}),100);}function wn(t,e){t.state.delayingBlurEvent&&(t.state.delayingBlurEvent=!1),"nocursor"!=t.options.readOnly&&(t.state.focused||(ne(t,"focus",t,e),t.state.focused=!0,W(t.display.wrapper,"CodeMirror-focused"),t.curOp||t.display.selForContextMenu==t.doc.sel||(t.display.input.reset(),l&&setTimeout((function(){return t.display.input.reset(!0)}),20)),t.display.input.receivedFocus()),mn(t));}function xn(t,e){t.state.delayingBlurEvent||(t.state.focused&&(ne(t,"blur",t,e),t.state.focused=!1,L(t.display.wrapper,"CodeMirror-focused")),clearInterval(t.display.blinker),setTimeout((function(){t.state.focused||(t.display.shift=!1);}),150));}function Cn(t){for(var e=t.display,r=e.lineDiv.offsetTop,n=0;n.005||h<-.005)&&(ct(i.line,l),_n(i.line),i.rest))for(var d=0;dt.display.sizerWidth){var p=Math.ceil(u/on(t.display));p>t.display.maxLineLength&&(t.display.maxLineLength=p,t.display.maxLine=i.line,t.display.maxLineChanged=!0);}}}}function _n(t){if(t.widgets)for(var e=0;e=a&&(o=ht(e,Kt(st(e,l))-t.wrapper.clientHeight),a=l);}return {from:o,to:Math.max(a,o+1)}}function kn(t){var e=t.display,r=e.view;if(e.alignWidgets||e.gutters.firstChild&&t.options.fixedGutter){for(var n=sn(e)-e.scroller.scrollLeft+t.doc.scrollLeft,i=e.gutters.offsetWidth,o=n+"px",a=0;ao&&(e.bottom=e.top+o);var s=t.doc.height+Sr(r),l=e.tops-n;if(e.topi+o){var c=Math.min(e.top,(u?s:e.bottom)-o);c!=i&&(a.scrollTop=c);}var f=t.curOp&&null!=t.curOp.scrollLeft?t.curOp.scrollLeft:r.scroller.scrollLeft,h=Mr(t)-(t.options.fixedGutter?r.gutters.offsetWidth:0),d=e.right-e.left>h;return d&&(e.right=e.left+h),e.left<10?a.scrollLeft=0:e.lefth+f-3&&(a.scrollLeft=e.right+(d?0:10)-h),a}function Tn(t,e){null!=e&&(Nn(t),t.curOp.scrollTop=(null==t.curOp.scrollTop?t.doc.scrollTop:t.curOp.scrollTop)+e);}function On(t){Nn(t);var e=t.getCursor();t.curOp.scrollToPos={from:e,to:e,margin:t.options.cursorScrollMargin};}function An(t,e,r){null==e&&null==r||Nn(t),null!=e&&(t.curOp.scrollLeft=e),null!=r&&(t.curOp.scrollTop=r);}function Nn(t){var e=t.curOp.scrollToPos;e&&(t.curOp.scrollToPos=null,Dn(t,$r(t,e.from),$r(t,e.to),e.margin));}function Dn(t,e,r,n){var i=Mn(t,{left:Math.min(e.left,r.left),top:Math.min(e.top,r.top)-n,right:Math.max(e.right,r.right),bottom:Math.max(e.bottom,r.bottom)+n});An(t,i.scrollLeft,i.scrollTop);}function Wn(t,e){Math.abs(t.doc.scrollTop-e)<2||(r||fi(t,{top:e}),En(t,e,!0),r&&fi(t),ai(t,100));}function En(t,e,r){e=Math.min(t.display.scroller.scrollHeight-t.display.scroller.clientHeight,e),(t.display.scroller.scrollTop!=e||r)&&(t.doc.scrollTop=e,t.display.scrollbars.setScrollTop(e),t.display.scroller.scrollTop!=e&&(t.display.scroller.scrollTop=e));}function Pn(t,e,r,n){e=Math.min(e,t.display.scroller.scrollWidth-t.display.scroller.clientWidth),(r?e==t.doc.scrollLeft:Math.abs(t.doc.scrollLeft-e)<2)&&!n||(t.doc.scrollLeft=e,kn(t),t.display.scroller.scrollLeft!=e&&(t.display.scroller.scrollLeft=e),t.display.scrollbars.setScrollLeft(e));}function Rn(t){var e=t.display,r=e.gutters.offsetWidth,n=Math.round(t.doc.height+Sr(t.display));return {clientHeight:e.scroller.clientHeight,viewHeight:e.wrapper.clientHeight,scrollWidth:e.scroller.scrollWidth,clientWidth:e.scroller.clientWidth,viewWidth:e.wrapper.clientWidth,barLeft:t.options.fixedGutter?r:0,docHeight:n,scrollHeight:n+Lr(t)+e.barHeight,nativeBarWidth:e.nativeBarWidth,gutterWidth:r}}var Hn=function(t,e,r){this.cm=r;var n=this.vert=O("div",[O("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),i=this.horiz=O("div",[O("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar");n.tabIndex=i.tabIndex=-1,t(n),t(i),te(n,"scroll",(function(){n.clientHeight&&e(n.scrollTop,"vertical");})),te(i,"scroll",(function(){i.clientWidth&&e(i.scrollLeft,"horizontal");})),this.checkedZeroWidth=!1,a&&s<8&&(this.horiz.style.minHeight=this.vert.style.minWidth="18px");};Hn.prototype.update=function(t){var e=t.scrollWidth>t.clientWidth+1,r=t.scrollHeight>t.clientHeight+1,n=t.nativeBarWidth;if(r){this.vert.style.display="block",this.vert.style.bottom=e?n+"px":"0";var i=t.viewHeight-(e?n:0);this.vert.firstChild.style.height=Math.max(0,t.scrollHeight-t.clientHeight+i)+"px";}else this.vert.style.display="",this.vert.firstChild.style.height="0";if(e){this.horiz.style.display="block",this.horiz.style.right=r?n+"px":"0",this.horiz.style.left=t.barLeft+"px";var o=t.viewWidth-t.barLeft-(r?n:0);this.horiz.firstChild.style.width=Math.max(0,t.scrollWidth-t.clientWidth+o)+"px";}else this.horiz.style.display="",this.horiz.firstChild.style.width="0";return !this.checkedZeroWidth&&t.clientHeight>0&&(0==n&&this.zeroWidthHack(),this.checkedZeroWidth=!0),{right:r?n:0,bottom:e?n:0}},Hn.prototype.setScrollLeft=function(t){this.horiz.scrollLeft!=t&&(this.horiz.scrollLeft=t),this.disableHoriz&&this.enableZeroWidthBar(this.horiz,this.disableHoriz,"horiz");},Hn.prototype.setScrollTop=function(t){this.vert.scrollTop!=t&&(this.vert.scrollTop=t),this.disableVert&&this.enableZeroWidthBar(this.vert,this.disableVert,"vert");},Hn.prototype.zeroWidthHack=function(){var t=y&&!d?"12px":"18px";this.horiz.style.height=this.vert.style.width=t,this.horiz.style.pointerEvents=this.vert.style.pointerEvents="none",this.disableHoriz=new I,this.disableVert=new I;},Hn.prototype.enableZeroWidthBar=function(t,e,r){t.style.pointerEvents="auto",e.set(1e3,(function n(){var i=t.getBoundingClientRect();("vert"==r?document.elementFromPoint(i.right-1,(i.top+i.bottom)/2):document.elementFromPoint((i.right+i.left)/2,i.bottom-1))!=t?t.style.pointerEvents="none":e.set(1e3,n);}));},Hn.prototype.clear=function(){var t=this.horiz.parentNode;t.removeChild(this.horiz),t.removeChild(this.vert);};var Fn=function(){};function In(t,e){e||(e=Rn(t));var r=t.display.barWidth,n=t.display.barHeight;zn(t,e);for(var i=0;i<4&&r!=t.display.barWidth||n!=t.display.barHeight;i++)r!=t.display.barWidth&&t.options.lineWrapping&&Cn(t),zn(t,Rn(t)),r=t.display.barWidth,n=t.display.barHeight;}function zn(t,e){var r=t.display,n=r.scrollbars.update(e);r.sizer.style.paddingRight=(r.barWidth=n.right)+"px",r.sizer.style.paddingBottom=(r.barHeight=n.bottom)+"px",r.heightForcer.style.borderBottom=n.bottom+"px solid transparent",n.right&&n.bottom?(r.scrollbarFiller.style.display="block",r.scrollbarFiller.style.height=n.bottom+"px",r.scrollbarFiller.style.width=n.right+"px"):r.scrollbarFiller.style.display="",n.bottom&&t.options.coverGutterNextToScrollbar&&t.options.fixedGutter?(r.gutterFiller.style.display="block",r.gutterFiller.style.height=n.bottom+"px",r.gutterFiller.style.width=e.gutterWidth+"px"):r.gutterFiller.style.display="";}Fn.prototype.update=function(){return {bottom:0,right:0}},Fn.prototype.setScrollLeft=function(){},Fn.prototype.setScrollTop=function(){},Fn.prototype.clear=function(){};var jn={native:Hn,null:Fn};function Bn(t){t.display.scrollbars&&(t.display.scrollbars.clear(),t.display.scrollbars.addClass&&L(t.display.wrapper,t.display.scrollbars.addClass)),t.display.scrollbars=new jn[t.options.scrollbarStyle]((function(e){t.display.wrapper.insertBefore(e,t.display.scrollbarFiller),te(e,"mousedown",(function(){t.state.focused&&setTimeout((function(){return t.display.input.focus()}),0);})),e.setAttribute("cm-not-content","true");}),(function(e,r){"horizontal"==r?Pn(t,e):Wn(t,e);}),t),t.display.scrollbars.addClass&&W(t.display.wrapper,t.display.scrollbars.addClass);}var Un=0;function Vn(t){var e;t.curOp={cm:t,viewChanged:!1,startHeight:t.doc.height,forceUpdate:!1,updateInput:null,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,focus:!1,id:++Un},e=t.curOp,ar?ar.ops.push(e):e.ownsGroup=ar={ops:[e],delayedCallbacks:[]};}function Gn(t){var e=t.curOp;e&&function(t,e){var r=t.ownsGroup;if(r)try{!function(t){var e=t.delayedCallbacks,r=0;do{for(;r=r.viewTo)||r.maxLineChanged&&e.options.lineWrapping,t.update=t.mustUpdate&&new li(e,t.mustUpdate&&{top:t.scrollTop,ensure:t.scrollToPos},t.forceUpdate);}function qn(t){t.updatedDisplay=t.mustUpdate&&ui(t.cm,t.update);}function $n(t){var e=t.cm,r=e.display;t.updatedDisplay&&Cn(e),t.barMeasure=Rn(e),r.maxLineChanged&&!e.options.lineWrapping&&(t.adjustWidthTo=Ar(e,r.maxLine,r.maxLine.text.length).left+3,e.display.sizerWidth=t.adjustWidthTo,t.barMeasure.scrollWidth=Math.max(r.scroller.clientWidth,r.sizer.offsetLeft+t.adjustWidthTo+Lr(e)+e.display.barWidth),t.maxScrollLeft=Math.max(0,r.sizer.offsetLeft+t.adjustWidthTo-Mr(e))),(t.updatedDisplay||t.selectionChanged)&&(t.preparedSelection=r.input.prepareSelection());}function Xn(t){var e=t.cm;null!=t.adjustWidthTo&&(e.display.sizer.style.minWidth=t.adjustWidthTo+"px",t.maxScrollLeft(window.innerHeight||document.documentElement.clientHeight)&&(i=!1),null!=i&&!p){var o=O("div","​",null,"position: absolute;\n top: "+(e.top-r.viewOffset-_r(t.display))+"px;\n height: "+(e.bottom-e.top+Lr(t)+r.barHeight)+"px;\n left: "+e.left+"px; width: "+Math.max(2,e.right-e.left)+"px;");t.display.lineSpace.appendChild(o),o.scrollIntoView(i),t.display.lineSpace.removeChild(o);}}}(e,function(t,e,r,n){var i;null==n&&(n=0),t.options.lineWrapping||e!=r||(r="before"==(e=e.ch?vt(e.line,"before"==e.sticky?e.ch-1:e.ch,"after"):e).sticky?vt(e.line,e.ch+1,"before"):e);for(var o=0;o<5;o++){var a=!1,s=qr(t,e),l=r&&r!=e?qr(t,r):s,u=Mn(t,i={left:Math.min(s.left,l.left),top:Math.min(s.top,l.top)-n,right:Math.max(s.left,l.left),bottom:Math.max(s.bottom,l.bottom)+n}),c=t.doc.scrollTop,f=t.doc.scrollLeft;if(null!=u.scrollTop&&(Wn(t,u.scrollTop),Math.abs(t.doc.scrollTop-c)>1&&(a=!0)),null!=u.scrollLeft&&(Pn(t,u.scrollLeft),Math.abs(t.doc.scrollLeft-f)>1&&(a=!0)),!a)break}return i}(e,Ct(n,t.scrollToPos.from),Ct(n,t.scrollToPos.to),t.scrollToPos.margin));var i=t.maybeHiddenMarkers,o=t.maybeUnhiddenMarkers;if(i)for(var a=0;ae)&&(i.updateLineNumbers=e),t.curOp.viewChanged=!0,e>=i.viewTo)kt&&Bt(t.doc,e)i.viewFrom?ni(t):(i.viewFrom+=n,i.viewTo+=n);else if(e<=i.viewFrom&&r>=i.viewTo)ni(t);else if(e<=i.viewFrom){var o=ii(t,r,r+n,1);o?(i.view=i.view.slice(o.index),i.viewFrom=o.lineN,i.viewTo+=n):ni(t);}else if(r>=i.viewTo){var a=ii(t,e,e,-1);a?(i.view=i.view.slice(0,a.index),i.viewTo=a.lineN):ni(t);}else {var s=ii(t,e,e,-1),l=ii(t,r,r+n,1);s&&l?(i.view=i.view.slice(0,s.index).concat(or(t,s.lineN,l.lineN)).concat(i.view.slice(l.index)),i.viewTo+=n):ni(t);}var u=i.externalMeasured;u&&(r=i.lineN&&e=n.viewTo)){var o=n.view[fn(t,e)];if(null!=o.node){var a=o.changes||(o.changes=[]);-1==z(a,r)&&a.push(r);}}}function ni(t){t.display.viewFrom=t.display.viewTo=t.doc.first,t.display.view=[],t.display.viewOffset=0;}function ii(t,e,r,n){var i,o=fn(t,e),a=t.display.view;if(!kt||r==t.doc.first+t.doc.size)return {index:o,lineN:r};for(var s=t.display.viewFrom,l=0;l0){if(o==a.length-1)return null;i=s+a[o].size-e,o++;}else i=s-e;e+=i,r+=i;}for(;Bt(t.doc,r)!=r;){if(o==(n<0?0:a.length-1))return null;r+=n*a[o-(n<0?1:0)].size,o+=n;}return {index:o,lineN:r}}function oi(t){for(var e=t.display.view,r=0,n=0;n=t.display.viewTo)){var r=+new Date+t.options.workTime,n=Ie(t,e.highlightFrontier),i=[];e.iter(n.line,Math.min(e.first+e.size,t.display.viewTo+500),(function(o){if(n.line>=t.display.viewFrom){var a=o.styles,s=o.text.length>t.options.maxHighlightLength?Ne(e.mode,n.state):null,l=He(t,o,n,!0);s&&(n.state=s),o.styles=l.styles;var u=o.styleClasses,c=l.classes;c?o.styleClasses=c:u&&(o.styleClasses=null);for(var f=!a||a.length!=o.styles.length||u!=c&&(!u||!c||u.bgClass!=c.bgClass||u.textClass!=c.textClass),h=0;!f&&hr)return ai(t,t.options.workDelay),!0})),e.highlightFrontier=n.line,e.modeFrontier=Math.max(e.modeFrontier,n.line),i.length&&Zn(t,(function(){for(var e=0;e=r.viewFrom&&e.visible.to<=r.viewTo&&(null==r.updateLineNumbers||r.updateLineNumbers>=r.viewTo)&&r.renderedView==r.view&&0==oi(t))return !1;Ln(t)&&(ni(t),e.dims=an(t));var i=n.first+n.size,o=Math.max(e.visible.from-t.options.viewportMargin,n.first),a=Math.min(i,e.visible.to+t.options.viewportMargin);r.viewFroma&&r.viewTo-a<20&&(a=Math.min(i,r.viewTo)),kt&&(o=Bt(t.doc,o),a=Ut(t.doc,a));var s=o!=r.viewFrom||a!=r.viewTo||r.lastWrapHeight!=e.wrapperHeight||r.lastWrapWidth!=e.wrapperWidth;!function(t,e,r){var n=t.display;0==n.view.length||e>=n.viewTo||r<=n.viewFrom?(n.view=or(t,e,r),n.viewFrom=e):(n.viewFrom>e?n.view=or(t,e,n.viewFrom).concat(n.view):n.viewFromr&&(n.view=n.view.slice(0,fn(t,r)))),n.viewTo=r;}(t,o,a),r.viewOffset=Kt(st(t.doc,r.viewFrom)),t.display.mover.style.top=r.viewOffset+"px";var u=oi(t);if(!s&&0==u&&!e.force&&r.renderedView==r.view&&(null==r.updateLineNumbers||r.updateLineNumbers>=r.viewTo))return !1;var c=function(t){if(t.hasFocus())return null;var e=D();if(!e||!N(t.display.lineDiv,e))return null;var r={activeElt:e};if(window.getSelection){var n=window.getSelection();n.anchorNode&&n.extend&&N(t.display.lineDiv,n.anchorNode)&&(r.anchorNode=n.anchorNode,r.anchorOffset=n.anchorOffset,r.focusNode=n.focusNode,r.focusOffset=n.focusOffset);}return r}(t);return u>4&&(r.lineDiv.style.display="none"),function(t,e,r){var n=t.display,i=t.options.lineNumbers,o=n.lineDiv,a=o.firstChild;function s(e){var r=e.nextSibling;return l&&y&&t.display.currentWheelTarget==e?e.style.display="none":e.parentNode.removeChild(e),r}for(var u=n.view,c=n.viewFrom,f=0;f-1&&(d=!1),cr(t,h,c,r)),d&&(M(h.lineNumber),h.lineNumber.appendChild(document.createTextNode(pt(t.options,c)))),a=h.node.nextSibling;}else {var p=mr(t,h,c,r);o.insertBefore(p,a);}c+=h.size;}for(;a;)a=s(a);}(t,r.updateLineNumbers,e.dims),u>4&&(r.lineDiv.style.display=""),r.renderedView=r.view,function(t){if(t&&t.activeElt&&t.activeElt!=D()&&(t.activeElt.focus(),t.anchorNode&&N(document.body,t.anchorNode)&&N(document.body,t.focusNode))){var e=window.getSelection(),r=document.createRange();r.setEnd(t.anchorNode,t.anchorOffset),r.collapse(!1),e.removeAllRanges(),e.addRange(r),e.extend(t.focusNode,t.focusOffset);}}(c),M(r.cursorDiv),M(r.selectionDiv),r.gutters.style.height=r.sizer.style.minHeight=0,s&&(r.lastWrapHeight=e.wrapperHeight,r.lastWrapWidth=e.wrapperWidth,ai(t,400)),r.updateLineNumbers=null,!0}function ci(t,e){for(var r=e.viewport,n=!0;(n&&t.options.lineWrapping&&e.oldDisplayWidth!=Mr(t)||(r&&null!=r.top&&(r={top:Math.min(t.doc.height+Sr(t.display)-Tr(t),r.top)}),e.visible=Sn(t.display,t.doc,r),!(e.visible.from>=t.display.viewFrom&&e.visible.to<=t.display.viewTo)))&&ui(t,e);n=!1){Cn(t);var i=Rn(t);hn(t),In(t,i),di(t,i),e.force=!1;}e.signal(t,"update",t),t.display.viewFrom==t.display.reportedViewFrom&&t.display.viewTo==t.display.reportedViewTo||(e.signal(t,"viewportChange",t,t.display.viewFrom,t.display.viewTo),t.display.reportedViewFrom=t.display.viewFrom,t.display.reportedViewTo=t.display.viewTo);}function fi(t,e){var r=new li(t,e);if(ui(t,r)){Cn(t),ci(t,r);var n=Rn(t);hn(t),In(t,n),di(t,n),r.finish();}}function hi(t){var e=t.display.gutters.offsetWidth;t.display.sizer.style.marginLeft=e+"px";}function di(t,e){t.display.sizer.style.minHeight=e.docHeight+"px",t.display.heightForcer.style.top=e.docHeight+"px",t.display.gutters.style.height=e.docHeight+t.display.barHeight+Lr(t)+"px";}function pi(t){var e=t.display.gutters,r=t.options.gutters;M(e);for(var n=0;n-1&&!t.lineNumbers&&(t.gutters=t.gutters.slice(0),t.gutters.splice(e,1));}li.prototype.signal=function(t,e){ae(t,e)&&this.events.push(arguments);},li.prototype.finish=function(){for(var t=0;ts.clientWidth,c=s.scrollHeight>s.clientHeight;if(i&&u||o&&c){if(o&&y&&l)t:for(var h=e.target,d=a.view;h!=s;h=h.parentNode)for(var p=0;p=0&>(t,n.to())<=0)return r}return -1};var Ci=function(t,e){this.anchor=t,this.head=e;};function _i(t,e,r){var n=t&&t.options.selectionsMayTouch,i=e[r];e.sort((function(t,e){return gt(t.from(),e.from())})),r=z(e,i);for(var o=1;o0:l>=0){var u=wt(s.from(),a.from()),c=bt(s.to(),a.to()),f=s.empty()?a.from()==a.head:s.from()==s.head;o<=r&&--r,e.splice(--o,2,new Ci(f?c:u,f?u:c));}}return new xi(e,r)}function Si(t,e){return new xi([new Ci(t,e||t)],0)}function ki(t){return t.text?vt(t.from.line+t.text.length-1,$(t.text).length+(1==t.text.length?t.from.ch:0)):t.to}function Li(t,e){if(gt(t,e.from)<0)return t;if(gt(t,e.to)<=0)return ki(e);var r=t.line+e.text.length-(e.to.line-e.from.line)-1,n=t.ch;return t.line==e.to.line&&(n+=ki(e).ch-e.to.ch),vt(r,n)}function Mi(t,e){for(var r=[],n=0;n1&&t.remove(s.line+1,p-1),t.insert(s.line+1,m);}lr(t,"change",t,e);}function Wi(t,e,r){!function t(n,i,o){if(n.linked)for(var a=0;as-(t.cm?t.cm.options.historyEventDelay:500)||"*"==e.origin.charAt(0)))&&(o=function(t,e){return e?(Fi(t.done),$(t.done)):t.done.length&&!$(t.done).ranges?$(t.done):t.done.length>1&&!t.done[t.done.length-2].ranges?(t.done.pop(),$(t.done)):void 0}(i,i.lastOp==n)))a=$(o.changes),0==gt(e.from,e.to)&&0==gt(e.from,a.to)?a.to=ki(e):o.changes.push(Hi(t,e));else {var l=$(i.done);for(l&&l.ranges||ji(t.sel,i.done),o={changes:[Hi(t,e)],generation:i.generation},i.done.push(o);i.done.length>i.undoDepth;)i.done.shift(),i.done[0].ranges||i.done.shift();}i.done.push(r),i.generation=++i.maxGeneration,i.lastModTime=i.lastSelTime=s,i.lastOp=i.lastSelOp=n,i.lastOrigin=i.lastSelOrigin=e.origin,a||ne(t,"historyAdded");}function zi(t,e,r,n){var i=t.history,o=n&&n.origin;r==i.lastSelOp||o&&i.lastSelOrigin==o&&(i.lastModTime==i.lastSelTime&&i.lastOrigin==o||function(t,e,r,n){var i=e.charAt(0);return "*"==i||"+"==i&&r.ranges.length==n.ranges.length&&r.somethingSelected()==n.somethingSelected()&&new Date-t.history.lastSelTime<=(t.cm?t.cm.options.historyEventDelay:500)}(t,o,$(i.done),e))?i.done[i.done.length-1]=e:ji(e,i.done),i.lastSelTime=+new Date,i.lastSelOrigin=o,i.lastSelOp=r,n&&!1!==n.clearRedo&&Fi(i.undone);}function ji(t,e){var r=$(e);r&&r.ranges&&r.equals(t)||e.push(t);}function Bi(t,e,r,n){var i=e["spans_"+t.id],o=0;t.iter(Math.max(t.first,r),Math.min(t.first+t.size,n),(function(r){r.markedSpans&&((i||(i=e["spans_"+t.id]={}))[o]=r.markedSpans),++o;}));}function Ui(t){if(!t)return null;for(var e,r=0;r-1&&($(s)[f]=u[f],delete u[f]);}}}return n}function Ki(t,e,r,n){if(n){var i=t.anchor;if(r){var o=gt(e,i)<0;o!=gt(r,i)<0?(i=e,e=r):o!=gt(e,r)<0&&(e=r);}return new Ci(i,e)}return new Ci(r||e,e)}function qi(t,e,r,n,i){null==i&&(i=t.cm&&(t.cm.display.shift||t.extend)),Ji(t,new xi([Ki(t.sel.primary(),e,r,i)],0),n);}function $i(t,e,r){for(var n=[],i=t.cm&&(t.cm.display.shift||t.extend),o=0;o=e.ch:s.to>e.ch))){if(i&&(ne(l,"beforeCursorEnter"),l.explicitlyCleared)){if(o.markedSpans){--a;continue}break}if(!l.atomic)continue;if(r){var u=l.find(n<0?1:-1),c=void 0;if((n<0?l.inclusiveRight:l.inclusiveLeft)&&(u=oo(t,u,-n,u&&u.line==e.line?o:null)),u&&u.line==e.line&&(c=gt(u,r))&&(n<0?c<0:c>0))return no(t,u,e,n,i)}var f=l.find(n<0?-1:1);return (n<0?l.inclusiveLeft:l.inclusiveRight)&&(f=oo(t,f,n,f.line==e.line?o:null)),f?no(t,f,e,n,i):null}}return e}function io(t,e,r,n,i){var o=n||1,a=no(t,e,r,o,i)||!i&&no(t,e,r,o,!0)||no(t,e,r,-o,i)||!i&&no(t,e,r,-o,!0);return a||(t.cantEdit=!0,vt(t.first,0))}function oo(t,e,r,n){return r<0&&0==e.ch?e.line>t.first?Ct(t,vt(e.line-1)):null:r>0&&e.ch==(n||st(t,e.line)).text.length?e.line0)){var c=[l,1],f=gt(u.from,s.from),h=gt(u.to,s.to);(f<0||!a.inclusiveLeft&&!f)&&c.push({from:u.from,to:s.from}),(h>0||!a.inclusiveRight&&!h)&&c.push({from:s.to,to:u.to}),i.splice.apply(i,c),l+=c.length-3;}}return i}(t,e.from,e.to);if(n)for(var i=n.length-1;i>=0;--i)uo(t,{from:n[i].from,to:n[i].to,text:i?[""]:e.text,origin:e.origin});else uo(t,e);}}function uo(t,e){if(1!=e.text.length||""!=e.text[0]||0!=gt(e.from,e.to)){var r=Mi(t,e);Ii(t,e,r,t.cm?t.cm.curOp.id:NaN),ho(t,e,r,Ot(t,e));var n=[];Wi(t,(function(t,r){r||-1!=z(n,t.history)||(mo(t.history,e),n.push(t.history)),ho(t,e,null,Ot(t,e));}));}}function co(t,e,r){var n=t.cm&&t.cm.state.suppressEdits;if(!n||r){for(var i,o=t.history,a=t.sel,s="undo"==e?o.done:o.undone,l="undo"==e?o.undone:o.done,u=0;u=0;--d){var p=h(d);if(p)return p.v}}}}function fo(t,e){if(0!=e&&(t.first+=e,t.sel=new xi(X(t.sel.ranges,(function(t){return new Ci(vt(t.anchor.line+e,t.anchor.ch),vt(t.head.line+e,t.head.ch))})),t.sel.primIndex),t.cm)){ei(t.cm,t.first,t.first-e,e);for(var r=t.cm.display,n=r.viewFrom;nt.lastLine())){if(e.from.lineo&&(e={from:e.from,to:vt(o,st(t,o).text.length),text:[e.text[0]],origin:e.origin}),e.removed=lt(t,e.from,e.to),r||(r=Mi(t,e)),t.cm?function(t,e,r){var n=t.doc,i=t.display,o=e.from,a=e.to,s=!1,l=o.line;t.options.lineWrapping||(l=ft(jt(st(n,o.line))),n.iter(l,a.line+1,(function(t){if(t==i.maxLine)return s=!0,!0}))),n.sel.contains(e.from,e.to)>-1&&oe(t),Di(n,e,r,ln(t)),t.options.lineWrapping||(n.iter(l,o.line+e.text.length,(function(t){var e=qt(t);e>i.maxLineLength&&(i.maxLine=t,i.maxLineLength=e,i.maxLineChanged=!0,s=!1);})),s&&(t.curOp.updateMaxLine=!0)),function(t,e){if(t.modeFrontier=Math.min(t.modeFrontier,e),!(t.highlightFrontierr;n--){var i=st(t,n).stateAfter;if(i&&(!(i instanceof Pe)||n+i.lookAhead1||!(this.children[0]instanceof bo))){var s=[];this.collapse(s),this.children=[new bo(s)],this.children[0].parent=this;}},collapse:function(t){for(var e=0;e50){for(var a=i.lines.length%25+25,s=a;s10);t.parent.maybeSpill();}},iterN:function(t,e,r){for(var n=0;n0||0==a&&!1!==o.clearWhenEmpty)return o;if(o.replacedWith&&(o.collapsed=!0,o.widgetNode=A("span",[o.replacedWith],"CodeMirror-widget"),n.handleMouseEvents||o.widgetNode.setAttribute("cm-ignore-events","true"),n.insertLeft&&(o.widgetNode.insertLeft=!0)),o.collapsed){if(zt(t,e.line,e,r,o)||e.line!=r.line&&zt(t,r.line,e,r,o))throw new Error("Inserting collapsed marker partially overlapping an existing one");kt=!0;}o.addToHistory&&Ii(t,{from:e,to:r,origin:"markText"},t.sel,NaN);var s,l=e.line,u=t.cm;if(t.iter(l,r.line+1,(function(t){u&&o.collapsed&&!u.options.lineWrapping&&jt(t)==u.display.maxLine&&(s=!0),o.collapsed&&l!=e.line&&ct(t,0),function(t,e){t.markedSpans=t.markedSpans?t.markedSpans.concat([e]):[e],e.marker.attachLine(t);}(t,new Lt(o,l==e.line?e.ch:null,l==r.line?r.ch:null)),++l;})),o.collapsed&&t.iter(e.line,r.line+1,(function(e){Vt(t,e)&&ct(e,0);})),o.clearOnEnter&&te(o,"beforeCursorEnter",(function(){return o.clear()})),o.readOnly&&(St=!0,(t.history.done.length||t.history.undone.length)&&t.clearHistory()),o.collapsed&&(o.id=++_o,o.atomic=!0),u){if(s&&(u.curOp.updateMaxLine=!0),o.collapsed)ei(u,e.line,r.line+1);else if(o.className||o.startStyle||o.endStyle||o.css||o.attributes||o.title)for(var c=e.line;c<=r.line;c++)ri(u,c,"text");o.atomic&&eo(u.doc),lr(u,"markerAdded",u,o);}return o}So.prototype.clear=function(){if(!this.explicitlyCleared){var t=this.doc.cm,e=t&&!t.curOp;if(e&&Vn(t),ae(this,"clear")){var r=this.find();r&&lr(this,"clear",r.from,r.to);}for(var n=null,i=null,o=0;ot.display.maxLineLength&&(t.display.maxLine=u,t.display.maxLineLength=c,t.display.maxLineChanged=!0);}null!=n&&t&&this.collapsed&&ei(t,n,i+1),this.lines.length=0,this.explicitlyCleared=!0,this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,t&&eo(t.doc)),t&&lr(t,"markerCleared",t,this,n,i),e&&Gn(t),this.parent&&this.parent.clear();}},So.prototype.find=function(t,e){var r,n;null==t&&"bookmark"==this.type&&(t=1);for(var i=0;i=0;l--)lo(this,n[l]);s?Zi(this,s):this.cm&&On(this.cm);})),undo:ti((function(){co(this,"undo");})),redo:ti((function(){co(this,"redo");})),undoSelection:ti((function(){co(this,"undo",!0);})),redoSelection:ti((function(){co(this,"redo",!0);})),setExtending:function(t){this.extend=t;},getExtending:function(){return this.extend},historySize:function(){for(var t=this.history,e=0,r=0,n=0;n=t.ch)&&e.push(i.marker.parent||i.marker);}return e},findMarks:function(t,e,r){t=Ct(this,t),e=Ct(this,e);var n=[],i=t.line;return this.iter(t.line,e.line+1,(function(o){var a=o.markedSpans;if(a)for(var s=0;s=l.to||null==l.from&&i!=t.line||null!=l.from&&i==e.line&&l.from>=e.ch||r&&!r(l.marker)||n.push(l.marker.parent||l.marker);}++i;})),n},getAllMarks:function(){var t=[];return this.iter((function(e){var r=e.markedSpans;if(r)for(var n=0;nt)return e=t,!0;t-=o,++r;})),Ct(this,vt(r,e))},indexFromPos:function(t){var e=(t=Ct(this,t)).ch;if(t.linee&&(e=t.from),null!=t.to&&t.to-1)return e.state.draggingText(t),void setTimeout((function(){return e.display.input.focus()}),20);try{var c=t.dataTransfer.getData("Text");if(c){var f;if(e.state.draggingText&&!e.state.draggingText.copy&&(f=e.listSelections()),Qi(e.doc,Si(r,r)),f)for(var h=0;h=0;e--)po(t.doc,"",n[e].from,n[e].to,"+delete");On(t);}));}function Zo(t,e,r){var n=it(t.text,e+r,r);return n<0||n>t.text.length?null:n}function Jo(t,e,r){var n=Zo(t,e.ch,r);return null==n?null:new vt(e.line,n,r<0?"after":"before")}function Qo(t,e,r,n,i){if(t){var o=Jt(r,e.doc.direction);if(o){var a,s=i<0?$(o):o[0],l=i<0==(1==s.level)?"after":"before";if(s.level>0||"rtl"==e.doc.direction){var u=Dr(e,r);a=i<0?r.text.length-1:0;var c=Wr(e,u,a).top;a=ot((function(t){return Wr(e,u,t).top==c}),i<0==(1==s.level)?s.from:s.to-1,a),"before"==l&&(a=Zo(r,a,1));}else a=i<0?s.to:s.from;return new vt(n,a,l)}}return new vt(n,i<0?r.text.length:0,i<0?"before":"after")}Bo.basic={Left:"goCharLeft",Right:"goCharRight",Up:"goLineUp",Down:"goLineDown",End:"goLineEnd",Home:"goLineStartSmart",PageUp:"goPageUp",PageDown:"goPageDown",Delete:"delCharAfter",Backspace:"delCharBefore","Shift-Backspace":"delCharBefore",Tab:"defaultTab","Shift-Tab":"indentAuto",Enter:"newlineAndIndent",Insert:"toggleOverwrite",Esc:"singleSelection"},Bo.pcDefault={"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Up":"goLineUp","Ctrl-Down":"goLineDown","Ctrl-Left":"goGroupLeft","Ctrl-Right":"goGroupRight","Alt-Left":"goLineStart","Alt-Right":"goLineEnd","Ctrl-Backspace":"delGroupBefore","Ctrl-Delete":"delGroupAfter","Ctrl-S":"save","Ctrl-F":"find","Ctrl-G":"findNext","Shift-Ctrl-G":"findPrev","Shift-Ctrl-F":"replace","Shift-Ctrl-R":"replaceAll","Ctrl-[":"indentLess","Ctrl-]":"indentMore","Ctrl-U":"undoSelection","Shift-Ctrl-U":"redoSelection","Alt-U":"redoSelection",fallthrough:"basic"},Bo.emacsy={"Ctrl-F":"goCharRight","Ctrl-B":"goCharLeft","Ctrl-P":"goLineUp","Ctrl-N":"goLineDown","Alt-F":"goWordRight","Alt-B":"goWordLeft","Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd","Ctrl-V":"goPageDown","Shift-Ctrl-V":"goPageUp","Ctrl-D":"delCharAfter","Ctrl-H":"delCharBefore","Alt-D":"delWordAfter","Alt-Backspace":"delWordBefore","Ctrl-K":"killLine","Ctrl-T":"transposeChars","Ctrl-O":"openLine"},Bo.macDefault={"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Home":"goDocStart","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineLeft","Cmd-Right":"goLineRight","Alt-Backspace":"delGroupBefore","Ctrl-Alt-Backspace":"delGroupAfter","Alt-Delete":"delGroupAfter","Cmd-S":"save","Cmd-F":"find","Cmd-G":"findNext","Shift-Cmd-G":"findPrev","Cmd-Alt-F":"replace","Shift-Cmd-Alt-F":"replaceAll","Cmd-[":"indentLess","Cmd-]":"indentMore","Cmd-Backspace":"delWrappedLineLeft","Cmd-Delete":"delWrappedLineRight","Cmd-U":"undoSelection","Shift-Cmd-U":"redoSelection","Ctrl-Up":"goDocStart","Ctrl-Down":"goDocEnd",fallthrough:["basic","emacsy"]},Bo.default=y?Bo.macDefault:Bo.pcDefault;var ta={selectAll:ao,singleSelection:function(t){return t.setSelection(t.getCursor("anchor"),t.getCursor("head"),B)},killLine:function(t){return Yo(t,(function(e){if(e.empty()){var r=st(t.doc,e.head.line).text.length;return e.head.ch==r&&e.head.line0)i=new vt(i.line,i.ch+1),t.replaceRange(o.charAt(i.ch-1)+o.charAt(i.ch-2),vt(i.line,i.ch-2),i,"+transpose");else if(i.line>t.doc.first){var a=st(t.doc,i.line-1).text;a&&(i=new vt(i.line,1),t.replaceRange(o.charAt(0)+t.doc.lineSeparator()+a.charAt(a.length-1),vt(i.line-1,a.length-1),i,"+transpose"));}r.push(new Ci(i,i));}t.setSelections(r);}))},newlineAndIndent:function(t){return Zn(t,(function(){for(var e=t.listSelections(),r=e.length-1;r>=0;r--)t.replaceRange(t.doc.lineSeparator(),e[r].anchor,e[r].head,"+input");e=t.listSelections();for(var n=0;n-1&&(gt((i=u.ranges[i]).from(),e)<0||e.xRel>0)&&(gt(i.to(),e)>0||e.xRel<0)?function(t,e,r,n){var i=t.display,o=!1,u=Jn(t,(function(e){l&&(i.scroller.draggable=!1),t.state.draggingText=!1,re(i.wrapper.ownerDocument,"mouseup",u),re(i.wrapper.ownerDocument,"mousemove",c),re(i.scroller,"dragstart",f),re(i.scroller,"drop",u),o||(le(e),n.addNew||qi(t.doc,r,null,null,n.extend),l||a&&9==s?setTimeout((function(){i.wrapper.ownerDocument.body.focus(),i.input.focus();}),20):i.input.focus());})),c=function(t){o=o||Math.abs(e.clientX-t.clientX)+Math.abs(e.clientY-t.clientY)>=10;},f=function(){return o=!0};l&&(i.scroller.draggable=!0),t.state.draggingText=u,u.copy=!n.moveOnDrag,i.scroller.dragDrop&&i.scroller.dragDrop(),te(i.wrapper.ownerDocument,"mouseup",u),te(i.wrapper.ownerDocument,"mousemove",c),te(i.scroller,"dragstart",f),te(i.scroller,"drop",u),bn(t),setTimeout((function(){return i.input.focus()}),20);}(t,n,e,o):function(t,e,r,n){var i=t.display,o=t.doc;le(e);var a,s,l=o.sel,u=l.ranges;if(n.addNew&&!n.extend?(s=o.sel.contains(r),a=s>-1?u[s]:new Ci(r,r)):(a=o.sel.primary(),s=o.sel.primIndex),"rectangle"==n.unit)n.addNew||(a=new Ci(r,r)),r=cn(t,e,!0,!0),s=-1;else {var c=ga(t,r,n.unit);a=n.extend?Ki(a,c.anchor,c.head,n.extend):c;}n.addNew?-1==s?(s=u.length,Ji(o,_i(t,u.concat([a]),s),{scroll:!1,origin:"*mouse"})):u.length>1&&u[s].empty()&&"char"==n.unit&&!n.extend?(Ji(o,_i(t,u.slice(0,s).concat(u.slice(s+1)),0),{scroll:!1,origin:"*mouse"}),l=o.sel):Xi(o,s,a,U):(s=0,Ji(o,new xi([a],0),U),l=o.sel);var f=r;function h(e){if(0!=gt(f,e))if(f=e,"rectangle"==n.unit){for(var i=[],u=t.options.tabSize,c=F(st(o,r.line).text,r.ch,u),h=F(st(o,e.line).text,e.ch,u),d=Math.min(c,h),p=Math.max(c,h),v=Math.min(r.line,e.line),g=Math.min(t.lastLine(),Math.max(r.line,e.line));v<=g;v++){var m=st(o,v).text,y=G(m,d,u);d==p?i.push(new Ci(vt(v,y),vt(v,y))):m.length>y&&i.push(new Ci(vt(v,y),vt(v,G(m,p,u))));}i.length||i.push(new Ci(r,r)),Ji(o,_i(t,l.ranges.slice(0,s).concat(i),s),{origin:"*mouse",scroll:!1}),t.scrollIntoView(e);}else {var b,w=a,x=ga(t,e,n.unit),C=w.anchor;gt(x.anchor,C)>0?(b=x.head,C=wt(w.from(),x.anchor)):(b=x.anchor,C=bt(w.to(),x.head));var _=l.ranges.slice(0);_[s]=function(t,e){var r=e.anchor,n=e.head,i=st(t.doc,r.line);if(0==gt(r,n)&&r.sticky==n.sticky)return e;var o=Jt(i);if(!o)return e;var a=Yt(o,r.ch,r.sticky),s=o[a];if(s.from!=r.ch&&s.to!=r.ch)return e;var l,u=a+(s.from==r.ch==(1!=s.level)?0:1);if(0==u||u==o.length)return e;if(n.line!=r.line)l=(n.line-r.line)*("ltr"==t.doc.direction?1:-1)>0;else {var c=Yt(o,n.ch,n.sticky),f=c-a||(n.ch-r.ch)*(1==s.level?-1:1);l=c==u-1||c==u?f<0:f>0;}var h=o[u+(l?-1:0)],d=l==(1==h.level),p=d?h.from:h.to,v=d?"after":"before";return r.ch==p&&r.sticky==v?e:new Ci(new vt(r.line,p,v),n)}(t,new Ci(Ct(o,C),b)),Ji(o,_i(t,_,s),U);}}var d=i.wrapper.getBoundingClientRect(),p=0;function v(e){t.state.selectingText=!1,p=1/0,le(e),i.input.focus(),re(i.wrapper.ownerDocument,"mousemove",g),re(i.wrapper.ownerDocument,"mouseup",m),o.history.lastSelOrigin=null;}var g=Jn(t,(function(e){0!==e.buttons&&de(e)?function e(r){var a=++p,s=cn(t,r,!0,"rectangle"==n.unit);if(s)if(0!=gt(s,f)){t.curOp.focus=D(),h(s);var l=Sn(i,o);(s.line>=l.to||s.lined.bottom?20:0;u&&setTimeout(Jn(t,(function(){p==a&&(i.scroller.scrollTop+=u,e(r));})),50);}}(e):v(e);})),m=Jn(t,v);t.state.selectingText=m,te(i.wrapper.ownerDocument,"mousemove",g),te(i.wrapper.ownerDocument,"mouseup",m);}(t,n,e,o);}(e,n,o,t):he(t)==r.scroller&&le(t):2==i?(n&&qi(e.doc,n),setTimeout((function(){return r.input.focus()}),20)):3==i&&(_?e.display.input.onContextMenu(t):bn(e)));}}function ga(t,e,r){if("char"==r)return new Ci(e,e);if("word"==r)return t.findWordAt(e);if("line"==r)return new Ci(vt(e.line,0),Ct(t.doc,vt(e.line+1,0)));var n=r(t,e);return new Ci(n.from,n.to)}function ma(t,e,r,n){var i,o;if(e.touches)i=e.touches[0].clientX,o=e.touches[0].clientY;else try{i=e.clientX,o=e.clientY;}catch(e){return !1}if(i>=Math.floor(t.display.gutters.getBoundingClientRect().right))return !1;n&&le(e);var a=t.display,s=a.lineDiv.getBoundingClientRect();if(o>s.bottom||!ae(t,r))return ce(e);o-=s.top-a.viewOffset;for(var l=0;l=i)return ne(t,r,t,ht(t.doc,o),t.options.gutters[l],e),ce(e)}}function ya(t,e){return ma(t,e,"gutterClick",!0)}function ba(t,e){Cr(t.display,e)||function(t,e){return !!ae(t,"gutterContextMenu")&&ma(t,e,"gutterContextMenu",!1)}(t,e)||ie(t,e,"contextmenu")||_||t.display.input.onContextMenu(e);}function wa(t){t.display.wrapper.className=t.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+t.options.theme.replace(/(^|\s)\s*/g," cm-s-"),zr(t);}pa.prototype.compare=function(t,e,r){return this.time+400>t&&0==gt(e,this.pos)&&r==this.button};var xa={toString:function(){return "CodeMirror.Init"}},Ca={},_a={};function Sa(t){pi(t),ei(t),kn(t);}function ka(t,e,r){if(!e!=!(r&&r!=xa)){var n=t.display.dragFunctions,i=e?te:re;i(t.display.scroller,"dragstart",n.start),i(t.display.scroller,"dragenter",n.enter),i(t.display.scroller,"dragover",n.over),i(t.display.scroller,"dragleave",n.leave),i(t.display.scroller,"drop",n.drop);}}function La(t){t.options.lineWrapping?(W(t.display.wrapper,"CodeMirror-wrap"),t.display.sizer.style.minWidth="",t.display.sizerWidth=null):(L(t.display.wrapper,"CodeMirror-wrap"),$t(t)),un(t),ei(t),zr(t),setTimeout((function(){return In(t)}),100);}function Ma(t,e){var r=this;if(!(this instanceof Ma))return new Ma(t,e);this.options=e=e?H(e):{},H(Ca,e,!1),vi(e);var n=e.value;"string"==typeof n?n=new Ao(n,e.mode,null,e.lineSeparator,e.direction):e.mode&&(n.modeOption=e.mode),this.doc=n;var i=new Ma.inputStyles[e.inputStyle](this),o=this.display=new at(t,n,i);for(var u in o.wrapper.CodeMirror=this,pi(this),wa(this),e.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap"),Bn(this),this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,delayingBlurEvent:!1,focused:!1,suppressEdits:!1,pasteIncoming:!1,cutIncoming:!1,selectingText:!1,draggingText:!1,highlight:new I,keySeq:null,specialChars:null},e.autofocus&&!m&&o.input.focus(),a&&s<11&&setTimeout((function(){return r.display.input.reset(!0)}),20),function(t){var e=t.display;te(e.scroller,"mousedown",Jn(t,va)),te(e.scroller,"dblclick",a&&s<11?Jn(t,(function(e){if(!ie(t,e)){var r=cn(t,e);if(r&&!ya(t,e)&&!Cr(t.display,e)){le(e);var n=t.findWordAt(r);qi(t.doc,n.anchor,n.head);}}})):function(e){return ie(t,e)||le(e)}),te(e.scroller,"contextmenu",(function(e){return ba(t,e)}));var r,n={end:0};function i(){e.activeTouch&&(r=setTimeout((function(){return e.activeTouch=null}),1e3),(n=e.activeTouch).end=+new Date);}function o(t,e){if(null==e.left)return !0;var r=e.left-t.left,n=e.top-t.top;return r*r+n*n>400}te(e.scroller,"touchstart",(function(i){if(!ie(t,i)&&!function(t){if(1!=t.touches.length)return !1;var e=t.touches[0];return e.radiusX<=1&&e.radiusY<=1}(i)&&!ya(t,i)){e.input.ensurePolled(),clearTimeout(r);var o=+new Date;e.activeTouch={start:o,moved:!1,prev:o-n.end<=300?n:null},1==i.touches.length&&(e.activeTouch.left=i.touches[0].pageX,e.activeTouch.top=i.touches[0].pageY);}})),te(e.scroller,"touchmove",(function(){e.activeTouch&&(e.activeTouch.moved=!0);})),te(e.scroller,"touchend",(function(r){var n=e.activeTouch;if(n&&!Cr(e,r)&&null!=n.left&&!n.moved&&new Date-n.start<300){var a,s=t.coordsChar(e.activeTouch,"page");a=!n.prev||o(n,n.prev)?new Ci(s,s):!n.prev.prev||o(n,n.prev.prev)?t.findWordAt(s):new Ci(vt(s.line,0),Ct(t.doc,vt(s.line+1,0))),t.setSelection(a.anchor,a.head),t.focus(),le(r);}i();})),te(e.scroller,"touchcancel",i),te(e.scroller,"scroll",(function(){e.scroller.clientHeight&&(Wn(t,e.scroller.scrollTop),Pn(t,e.scroller.scrollLeft,!0),ne(t,"scroll",t));})),te(e.scroller,"mousewheel",(function(e){return wi(t,e)})),te(e.scroller,"DOMMouseScroll",(function(e){return wi(t,e)})),te(e.wrapper,"scroll",(function(){return e.wrapper.scrollTop=e.wrapper.scrollLeft=0})),e.dragFunctions={enter:function(e){ie(t,e)||fe(e);},over:function(e){ie(t,e)||(function(t,e){var r=cn(t,e);if(r){var n=document.createDocumentFragment();pn(t,r,n),t.display.dragCursor||(t.display.dragCursor=O("div",null,"CodeMirror-cursors CodeMirror-dragcursors"),t.display.lineSpace.insertBefore(t.display.dragCursor,t.display.cursorDiv)),T(t.display.dragCursor,n);}}(t,e),fe(e));},start:function(e){return function(t,e){if(a&&(!t.state.draggingText||+new Date-No<100))fe(e);else if(!ie(t,e)&&!Cr(t.display,e)&&(e.dataTransfer.setData("Text",t.getSelection()),e.dataTransfer.effectAllowed="copyMove",e.dataTransfer.setDragImage&&!h)){var r=O("img",null,null,"position: fixed; left: 0; top: 0;");r.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",f&&(r.width=r.height=1,t.display.wrapper.appendChild(r),r._top=r.offsetTop),e.dataTransfer.setDragImage(r,0,0),f&&r.parentNode.removeChild(r);}}(t,e)},drop:Jn(t,Do),leave:function(e){ie(t,e)||Wo(t);}};var l=e.input.getField();te(l,"keyup",(function(e){return ca.call(t,e)})),te(l,"keydown",Jn(t,ua)),te(l,"keypress",Jn(t,fa)),te(l,"focus",(function(e){return wn(t,e)})),te(l,"blur",(function(e){return xn(t,e)}));}(this),Ro(),Vn(this),this.curOp.forceUpdate=!0,Ei(this,n),e.autofocus&&!m||this.hasFocus()?setTimeout(R(wn,this),20):xn(this),_a)_a.hasOwnProperty(u)&&_a[u](r,e[u],xa);Ln(this),e.finishInit&&e.finishInit(this);for(var c=0;c150)){if(!n)return;r="prev";}}else u=0,r="not";"prev"==r?u=e>o.first?F(st(o,e-1).text,null,a):0:"add"==r?u=l+t.options.indentUnit:"subtract"==r?u=l-t.options.indentUnit:"number"==typeof r&&(u=l+r),u=Math.max(0,u);var f="",h=0;if(t.options.indentWithTabs)for(var d=Math.floor(u/a);d;--d)h+=a,f+="\t";if(h1)if(Aa&&Aa.text.join("\n")==e){if(n.ranges.length%Aa.text.length==0){u=[];for(var c=0;c=0;f--){var h=n.ranges[f],d=h.from(),p=h.to();h.empty()&&(r&&r>0?d=vt(d.line,d.ch-r):t.state.overwrite&&!s?p=vt(p.line,Math.min(st(o,p.line).text.length,p.ch+$(l).length)):s&&Aa&&Aa.lineWise&&Aa.text.join("\n")==e&&(d=p=vt(d.line,0))),a=t.curOp.updateInput;var v={from:d,to:p,text:u?u[f%u.length]:l,origin:i||(s?"paste":t.state.cutIncoming?"cut":"+input")};lo(t.doc,v),lr(t,"inputRead",t,v);}e&&!s&&Ea(t,e),On(t),t.curOp.updateInput=a,t.curOp.typing=!0,t.state.pasteIncoming=t.state.cutIncoming=!1;}function Wa(t,e){var r=t.clipboardData&&t.clipboardData.getData("Text");if(r)return t.preventDefault(),e.isReadOnly()||e.options.disableInput||Zn(e,(function(){return Da(e,r,0,null,"paste")})),!0}function Ea(t,e){if(t.options.electricChars&&t.options.smartIndent)for(var r=t.doc.sel,n=r.ranges.length-1;n>=0;n--){var i=r.ranges[n];if(!(i.head.ch>100||n&&r.ranges[n-1].head.line==i.head.line)){var o=t.getModeAt(i.head),a=!1;if(o.electricChars){for(var s=0;s-1){a=Oa(t,i.head.line,"smart");break}}else o.electricInput&&o.electricInput.test(st(t.doc,i.head.line).text.slice(0,i.head.ch))&&(a=Oa(t,i.head.line,"smart"));a&&lr(t,"electricInput",t,i.head.line);}}}function Pa(t){for(var e=[],r=[],n=0;n=e.text.length?(r.ch=e.text.length,r.sticky="before"):r.ch<=0&&(r.ch=0,r.sticky="after");var o=Yt(i,r.ch,r.sticky),a=i[o];if("ltr"==t.doc.direction&&a.level%2==0&&(n>0?a.to>r.ch:a.from=a.from&&h>=c.begin)){var d=f?"before":"after";return new vt(r.line,h,d)}}var p=function(t,e,n){for(var o=function(t,e){return e?new vt(r.line,l(t,1),"before"):new vt(r.line,t,"after")};t>=0&&t0==(1!=a.level),u=s?n.begin:l(n.end,-1);if(a.from<=u&&u0?c.end:l(c.begin,-1);return null==g||n>0&&g==e.text.length||!(v=p(n>0?0:i.length-1,n,u(g)))?null:v}(t.cm,s,e,r):Jo(s,e,r))){if(n||(a=e.line+r)=t.first+t.size||(e=new vt(a,e.ch,e.sticky),!(s=st(t,a))))return !1;e=Qo(i,t.cm,s,e.line,r);}else e=o;return !0}if("char"==n)l();else if("column"==n)l(!0);else if("word"==n||"group"==n)for(var u=null,c="group"==n,f=t.cm&&t.cm.getHelper(e,"wordChars"),h=!0;!(r<0)||l(!h);h=!1){var d=s.text.charAt(e.ch)||"\n",p=tt(d,f)?"w":c&&"\n"==d?"n":!c||/\s/.test(d)?null:"p";if(!c||h||p||(p="s"),u&&u!=p){r<0&&(r=1,l(),e.sticky="after");break}if(p&&(u=p),r>0&&!l(!h))break}var v=io(t,e,o,a,!0);return mt(o,v)&&(v.hitSide=!0),v}function Ia(t,e,r,n){var i,o,a=t.doc,s=e.left;if("page"==n){var l=Math.min(t.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight),u=Math.max(l-.5*nn(t.display),3);i=(r>0?e.bottom:e.top)+r*u;}else "line"==n&&(i=r>0?e.bottom+3:e.top-3);for(;(o=Yr(t,s,i)).outside;){if(r<0?i<=0:i>=a.height){o.hitSide=!0;break}i+=5*r;}return o}var za=function(t){this.cm=t,this.lastAnchorNode=this.lastAnchorOffset=this.lastFocusNode=this.lastFocusOffset=null,this.polling=new I,this.composing=null,this.gracePeriod=!1,this.readDOMTimeout=null;};function ja(t,e){var r=Nr(t,e.line);if(!r||r.hidden)return null;var n=st(t.doc,e.line),i=Or(r,n,e.line),o=Jt(n,t.doc.direction),a="left";o&&(a=Yt(o,e.ch)%2?"right":"left");var s=Rr(i.map,e.ch,a);return s.offset="right"==s.collapse?s.end:s.start,s}function Ba(t,e){return e&&(t.bad=!0),t}function Ua(t,e,r){var n;if(e==t.display.lineDiv){if(!(n=t.display.lineDiv.childNodes[r]))return Ba(t.clipPos(vt(t.display.viewTo-1)),!0);e=null,r=0;}else for(n=e;;n=n.parentNode){if(!n||n==t.display.lineDiv)return null;if(n.parentNode&&n.parentNode==t.display.lineDiv)break}for(var i=0;i=e.display.viewTo||o.line=e.display.viewFrom&&ja(e,i)||{node:l[0].measure.map[2],offset:0},c=o.linen.firstLine()&&(a=vt(a.line-1,st(n.doc,a.line-1).length)),s.ch==st(n.doc,s.line).text.length&&s.linei.viewTo-1)return !1;a.line==i.viewFrom||0==(t=fn(n,a.line))?(e=ft(i.view[0].line),r=i.view[0].node):(e=ft(i.view[t].line),r=i.view[t-1].node.nextSibling);var l,u,c=fn(n,s.line);if(c==i.view.length-1?(l=i.viewTo-1,u=i.lineDiv.lastChild):(l=ft(i.view[c+1].line)-1,u=i.view[c+1].node.previousSibling),!r)return !1;for(var f=n.doc.splitLines(function(t,e,r,n,i){var o="",a=!1,s=t.doc.lineSeparator(),l=!1;function u(){a&&(o+=s,l&&(o+=s),a=l=!1);}function c(t){t&&(u(),o+=t);}function f(e){if(1==e.nodeType){var r=e.getAttribute("cm-text");if(r)return void c(r);var o,h=e.getAttribute("cm-marker");if(h){var d=t.findMarks(vt(n,0),vt(i+1,0),(g=+h,function(t){return t.id==g}));return void(d.length&&(o=d[0].find(0))&&c(lt(t.doc,o.from,o.to).join(s)))}if("false"==e.getAttribute("contenteditable"))return;var p=/^(pre|div|p|li|table|br)$/i.test(e.nodeName);if(!/^br$/i.test(e.nodeName)&&0==e.textContent.length)return;p&&u();for(var v=0;v1&&h.length>1;)if($(f)==$(h))f.pop(),h.pop(),l--;else {if(f[0]!=h[0])break;f.shift(),h.shift(),e++;}for(var d=0,p=0,v=f[0],g=h[0],m=Math.min(v.length,g.length);da.ch&&y.charCodeAt(y.length-p-1)==b.charCodeAt(b.length-p-1);)d--,p++;f[f.length-1]=y.slice(0,y.length-p).replace(/^\u200b+/,""),f[0]=f[0].slice(d).replace(/\u200b+$/,"");var x=vt(e,d),C=vt(l,h.length?$(h).length-p:0);return f.length>1||f[0]||gt(x,C)?(po(n.doc,f,x,C,"+input"),!0):void 0},za.prototype.ensurePolled=function(){this.forceCompositionEnd();},za.prototype.reset=function(){this.forceCompositionEnd();},za.prototype.forceCompositionEnd=function(){this.composing&&(clearTimeout(this.readDOMTimeout),this.composing=null,this.updateFromDOM(),this.div.blur(),this.div.focus());},za.prototype.readFromDOMSoon=function(){var t=this;null==this.readDOMTimeout&&(this.readDOMTimeout=setTimeout((function(){if(t.readDOMTimeout=null,t.composing){if(!t.composing.done)return;t.composing=null;}t.updateFromDOM();}),80));},za.prototype.updateFromDOM=function(){var t=this;!this.cm.isReadOnly()&&this.pollContent()||Zn(this.cm,(function(){return ei(t.cm)}));},za.prototype.setUneditable=function(t){t.contentEditable="false";},za.prototype.onKeyPress=function(t){0==t.charCode||this.composing||(t.preventDefault(),this.cm.isReadOnly()||Jn(this.cm,Da)(this.cm,String.fromCharCode(null==t.charCode?t.keyCode:t.charCode),0));},za.prototype.readOnlyChanged=function(t){this.div.contentEditable=String("nocursor"!=t);},za.prototype.onContextMenu=function(){},za.prototype.resetPosition=function(){},za.prototype.needsContentAttribute=!0;var Ga=function(t){this.cm=t,this.prevInput="",this.pollingFast=!1,this.polling=new I,this.hasSelection=!1,this.composing=null;};Ga.prototype.init=function(t){var e=this,r=this,n=this.cm;this.createField(t);var i=this.textarea;function o(t){if(!ie(n,t)){if(n.somethingSelected())Na({lineWise:!1,text:n.getSelections()});else {if(!n.options.lineWiseCopyCut)return;var e=Pa(n);Na({lineWise:!0,text:e.text}),"cut"==t.type?n.setSelections(e.ranges,null,B):(r.prevInput="",i.value=e.text.join("\n"),P(i));}"cut"==t.type&&(n.state.cutIncoming=!0);}}t.wrapper.insertBefore(this.wrapper,t.wrapper.firstChild),v&&(i.style.width="0px"),te(i,"input",(function(){a&&s>=9&&e.hasSelection&&(e.hasSelection=null),r.poll();})),te(i,"paste",(function(t){ie(n,t)||Wa(t,n)||(n.state.pasteIncoming=!0,r.fastPoll());})),te(i,"cut",o),te(i,"copy",o),te(t.scroller,"paste",(function(e){Cr(t,e)||ie(n,e)||(n.state.pasteIncoming=!0,r.focus());})),te(t.lineSpace,"selectstart",(function(e){Cr(t,e)||le(e);})),te(i,"compositionstart",(function(){var t=n.getCursor("from");r.composing&&r.composing.range.clear(),r.composing={start:t,range:n.markText(t,n.getCursor("to"),{className:"CodeMirror-composing"})};})),te(i,"compositionend",(function(){r.composing&&(r.poll(),r.composing.range.clear(),r.composing=null);}));},Ga.prototype.createField=function(t){this.wrapper=Ha(),this.textarea=this.wrapper.firstChild;},Ga.prototype.prepareSelection=function(){var t=this.cm,e=t.display,r=t.doc,n=dn(t);if(t.options.moveInputWithCursor){var i=qr(t,r.sel.primary().head,"div"),o=e.wrapper.getBoundingClientRect(),a=e.lineDiv.getBoundingClientRect();n.teTop=Math.max(0,Math.min(e.wrapper.clientHeight-10,i.top+a.top-o.top)),n.teLeft=Math.max(0,Math.min(e.wrapper.clientWidth-10,i.left+a.left-o.left));}return n},Ga.prototype.showSelection=function(t){var e=this.cm.display;T(e.cursorDiv,t.cursors),T(e.selectionDiv,t.selection),null!=t.teTop&&(this.wrapper.style.top=t.teTop+"px",this.wrapper.style.left=t.teLeft+"px");},Ga.prototype.reset=function(t){if(!this.contextMenuPending&&!this.composing){var e=this.cm;if(e.somethingSelected()){this.prevInput="";var r=e.getSelection();this.textarea.value=r,e.state.focused&&P(this.textarea),a&&s>=9&&(this.hasSelection=r);}else t||(this.prevInput=this.textarea.value="",a&&s>=9&&(this.hasSelection=null));}},Ga.prototype.getField=function(){return this.textarea},Ga.prototype.supportsTouch=function(){return !1},Ga.prototype.focus=function(){if("nocursor"!=this.cm.options.readOnly&&(!m||D()!=this.textarea))try{this.textarea.focus();}catch(t){}},Ga.prototype.blur=function(){this.textarea.blur();},Ga.prototype.resetPosition=function(){this.wrapper.style.top=this.wrapper.style.left=0;},Ga.prototype.receivedFocus=function(){this.slowPoll();},Ga.prototype.slowPoll=function(){var t=this;this.pollingFast||this.polling.set(this.cm.options.pollInterval,(function(){t.poll(),t.cm.state.focused&&t.slowPoll();}));},Ga.prototype.fastPoll=function(){var t=!1,e=this;e.pollingFast=!0,e.polling.set(20,(function r(){e.poll()||t?(e.pollingFast=!1,e.slowPoll()):(t=!0,e.polling.set(60,r));}));},Ga.prototype.poll=function(){var t=this,e=this.cm,r=this.textarea,n=this.prevInput;if(this.contextMenuPending||!e.state.focused||xe(r)&&!n&&!this.composing||e.isReadOnly()||e.options.disableInput||e.state.keySeq)return !1;var i=r.value;if(i==n&&!e.somethingSelected())return !1;if(a&&s>=9&&this.hasSelection===i||y&&/[\uf700-\uf7ff]/.test(i))return e.display.input.reset(),!1;if(e.doc.sel==e.display.selForContextMenu){var o=i.charCodeAt(0);if(8203!=o||n||(n="​"),8666==o)return this.reset(),this.cm.execCommand("undo")}for(var l=0,u=Math.min(n.length,i.length);l1e3||i.indexOf("\n")>-1?r.value=t.prevInput="":t.prevInput=i,t.composing&&(t.composing.range.clear(),t.composing.range=e.markText(t.composing.start,e.getCursor("to"),{className:"CodeMirror-composing"}));})),!0},Ga.prototype.ensurePolled=function(){this.pollingFast&&this.poll()&&(this.pollingFast=!1);},Ga.prototype.onKeyPress=function(){a&&s>=9&&(this.hasSelection=null),this.fastPoll();},Ga.prototype.onContextMenu=function(t){var e=this,r=e.cm,n=r.display,i=e.textarea,o=cn(r,t),u=n.scroller.scrollTop;if(o&&!f){r.options.resetSelectionOnContextMenu&&-1==r.doc.sel.contains(o)&&Jn(r,Ji)(r.doc,Si(o),B);var c=i.style.cssText,h=e.wrapper.style.cssText;e.wrapper.style.cssText="position: absolute";var d,p=e.wrapper.getBoundingClientRect();if(i.style.cssText="position: absolute; width: 30px; height: 30px;\n top: "+(t.clientY-p.top-5)+"px; left: "+(t.clientX-p.left-5)+"px;\n z-index: 1000; background: "+(a?"rgba(255, 255, 255, .05)":"transparent")+";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);",l&&(d=window.scrollY),n.input.focus(),l&&window.scrollTo(null,d),n.input.reset(),r.somethingSelected()||(i.value=e.prevInput=" "),e.contextMenuPending=!0,n.selForContextMenu=r.doc.sel,clearTimeout(n.detectingSelectAll),a&&s>=9&&g(),_){fe(t);var v=function(){re(window,"mouseup",v),setTimeout(m,20);};te(window,"mouseup",v);}else setTimeout(m,50);}function g(){if(null!=i.selectionStart){var t=r.somethingSelected(),o="​"+(t?i.value:"");i.value="⇚",i.value=o,e.prevInput=t?"":"​",i.selectionStart=1,i.selectionEnd=o.length,n.selForContextMenu=r.doc.sel;}}function m(){if(e.contextMenuPending=!1,e.wrapper.style.cssText=h,i.style.cssText=c,a&&s<9&&n.scrollbars.setScrollTop(n.scroller.scrollTop=u),null!=i.selectionStart){(!a||a&&s<9)&&g();var t=0,o=function(){n.selForContextMenu==r.doc.sel&&0==i.selectionStart&&i.selectionEnd>0&&"​"==e.prevInput?Jn(r,ao)(r):t++<10?n.detectingSelectAll=setTimeout(o,500):(n.selForContextMenu=null,n.input.reset());};n.detectingSelectAll=setTimeout(o,200);}}},Ga.prototype.readOnlyChanged=function(t){t||this.reset(),this.textarea.disabled="nocursor"==t;},Ga.prototype.setUneditable=function(){},Ga.prototype.needsContentAttribute=!1,function(t){var e=t.optionHandlers;function r(r,n,i,o){t.defaults[r]=n,i&&(e[r]=o?function(t,e,r){r!=xa&&i(t,e,r);}:i);}t.defineOption=r,t.Init=xa,r("value","",(function(t,e){return t.setValue(e)}),!0),r("mode",null,(function(t,e){t.doc.modeOption=e,Oi(t);}),!0),r("indentUnit",2,Oi,!0),r("indentWithTabs",!1),r("smartIndent",!0),r("tabSize",4,(function(t){Ai(t),zr(t),ei(t);}),!0),r("lineSeparator",null,(function(t,e){if(t.doc.lineSep=e,e){var r=[],n=t.doc.first;t.doc.iter((function(t){for(var i=0;;){var o=t.text.indexOf(e,i);if(-1==o)break;i=o+e.length,r.push(vt(n,o));}n++;}));for(var i=r.length-1;i>=0;i--)po(t.doc,e,r[i],vt(r[i].line,r[i].ch+e.length));}})),r("specialChars",/[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g,(function(t,e,r){t.state.specialChars=new RegExp(e.source+(e.test("\t")?"":"|\t"),"g"),r!=xa&&t.refresh();})),r("specialCharPlaceholder",Qe,(function(t){return t.refresh()}),!0),r("electricChars",!0),r("inputStyle",m?"contenteditable":"textarea",(function(){throw new Error("inputStyle can not (yet) be changed in a running editor")}),!0),r("spellcheck",!1,(function(t,e){return t.getInputField().spellcheck=e}),!0),r("rtlMoveVisually",!w),r("wholeLineUpdateBefore",!0),r("theme","default",(function(t){wa(t),Sa(t);}),!0),r("keyMap","default",(function(t,e,r){var n=Xo(e),i=r!=xa&&Xo(r);i&&i.detach&&i.detach(t,n),n.attach&&n.attach(t,i||null);})),r("extraKeys",null),r("configureMouse",null),r("lineWrapping",!1,La,!0),r("gutters",[],(function(t){vi(t.options),Sa(t);}),!0),r("fixedGutter",!0,(function(t,e){t.display.gutters.style.left=e?sn(t.display)+"px":"0",t.refresh();}),!0),r("coverGutterNextToScrollbar",!1,(function(t){return In(t)}),!0),r("scrollbarStyle","native",(function(t){Bn(t),In(t),t.display.scrollbars.setScrollTop(t.doc.scrollTop),t.display.scrollbars.setScrollLeft(t.doc.scrollLeft);}),!0),r("lineNumbers",!1,(function(t){vi(t.options),Sa(t);}),!0),r("firstLineNumber",1,Sa,!0),r("lineNumberFormatter",(function(t){return t}),Sa,!0),r("showCursorWhenSelecting",!1,hn,!0),r("resetSelectionOnContextMenu",!0),r("lineWiseCopyCut",!0),r("pasteLinesPerSelection",!0),r("selectionsMayTouch",!1),r("readOnly",!1,(function(t,e){"nocursor"==e&&(xn(t),t.display.input.blur()),t.display.input.readOnlyChanged(e);})),r("disableInput",!1,(function(t,e){e||t.display.input.reset();}),!0),r("dragDrop",!0,ka),r("allowDropFileTypes",null),r("cursorBlinkRate",530),r("cursorScrollMargin",0),r("cursorHeight",1,hn,!0),r("singleCursorHeightPerLine",!0,hn,!0),r("workTime",100),r("workDelay",100),r("flattenSpans",!0,Ai,!0),r("addModeClass",!1,Ai,!0),r("pollInterval",100),r("undoDepth",200,(function(t,e){return t.doc.history.undoDepth=e})),r("historyEventDelay",1250),r("viewportMargin",10,(function(t){return t.refresh()}),!0),r("maxHighlightLength",1e4,Ai,!0),r("moveInputWithCursor",!0,(function(t,e){e||t.display.input.resetPosition();})),r("tabindex",null,(function(t,e){return t.display.input.getField().tabIndex=e||""})),r("autofocus",null),r("direction","ltr",(function(t,e){return t.doc.setDirection(e)}),!0),r("phrases",null);}(Ma),function(t){var e=t.optionHandlers,r=t.helpers={};t.prototype={constructor:t,focus:function(){window.focus(),this.display.input.focus();},setOption:function(t,r){var n=this.options,i=n[t];n[t]==r&&"mode"!=t||(n[t]=r,e.hasOwnProperty(t)&&Jn(this,e[t])(this,r,i),ne(this,"optionChange",this,t));},getOption:function(t){return this.options[t]},getDoc:function(){return this.doc},addKeyMap:function(t,e){this.state.keyMaps[e?"push":"unshift"](Xo(t));},removeKeyMap:function(t){for(var e=this.state.keyMaps,r=0;rr&&(Oa(this,i.head.line,t,!0),r=i.head.line,n==this.doc.sel.primIndex&&On(this));else {var o=i.from(),a=i.to(),s=Math.max(r,o.line);r=Math.min(this.lastLine(),a.line-(a.ch?0:1))+1;for(var l=s;l0&&Xi(this.doc,n,new Ci(o,u[n].to()),B);}}})),getTokenAt:function(t,e){return Ve(this,t,e)},getLineTokens:function(t,e){return Ve(this,vt(t),e,!0)},getTokenTypeAt:function(t){t=Ct(this.doc,t);var e,r=Fe(this,st(this.doc,t.line)),n=0,i=(r.length-1)/2,o=t.ch;if(0==o)e=r[2];else for(;;){var a=n+i>>1;if((a?r[2*a-1]:0)>=o)i=a;else {if(!(r[2*a+1]o&&(t=o,i=!0),n=st(this.doc,t);}else n=t;return Vr(this,n,{top:0,left:0},e||"page",r||i).top+(i?this.doc.height-Kt(n):0)},defaultTextHeight:function(){return nn(this.display)},defaultCharWidth:function(){return on(this.display)},getViewport:function(){return {from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(t,e,r,n,i){var o,a,s,l=this.display,u=(t=qr(this,Ct(this.doc,t))).bottom,c=t.left;if(e.style.position="absolute",e.setAttribute("cm-ignore-events","true"),this.display.input.setUneditable(e),l.sizer.appendChild(e),"over"==n)u=t.top;else if("above"==n||"near"==n){var f=Math.max(l.wrapper.clientHeight,this.doc.height),h=Math.max(l.sizer.clientWidth,l.lineSpace.clientWidth);("above"==n||t.bottom+e.offsetHeight>f)&&t.top>e.offsetHeight?u=t.top-e.offsetHeight:t.bottom+e.offsetHeight<=f&&(u=t.bottom),c+e.offsetWidth>h&&(c=h-e.offsetWidth);}e.style.top=u+"px",e.style.left=e.style.right="","right"==i?(c=l.sizer.clientWidth-e.offsetWidth,e.style.right="0px"):("left"==i?c=0:"middle"==i&&(c=(l.sizer.clientWidth-e.offsetWidth)/2),e.style.left=c+"px"),r&&(o=this,a={left:c,top:u,right:c+e.offsetWidth,bottom:u+e.offsetHeight},null!=(s=Mn(o,a)).scrollTop&&Wn(o,s.scrollTop),null!=s.scrollLeft&&Pn(o,s.scrollLeft));},triggerOnKeyDown:Qn(ua),triggerOnKeyPress:Qn(fa),triggerOnKeyUp:ca,triggerOnMouseDown:Qn(va),execCommand:function(t){if(ta.hasOwnProperty(t))return ta[t].call(null,this)},triggerElectric:Qn((function(t){Ea(this,t);})),findPosH:function(t,e,r,n){var i=1;e<0&&(i=-1,e=-e);for(var o=Ct(this.doc,t),a=0;a0&&a(e.charAt(r-1));)--r;for(;n.5)&&un(this),ne(this,"refresh",this);})),swapDoc:Qn((function(t){var e=this.doc;return e.cm=null,Ei(this,t),zr(this),this.display.input.reset(),An(this,t.scrollLeft,t.scrollTop),this.curOp.forceScroll=!0,lr(this,"swapDoc",this,e),e})),phrase:function(t){var e=this.options.phrases;return e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:t},getInputField:function(){return this.display.input.getField()},getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}},se(t),t.registerHelper=function(e,n,i){r.hasOwnProperty(e)||(r[e]=t[e]={_global:[]}),r[e][n]=i;},t.registerGlobalHelper=function(e,n,i,o){t.registerHelper(e,n,o),r[e]._global.push({pred:i,val:o});};}(Ma);var Ka="iter insert remove copy getEditor constructor".split(" ");for(var qa in Ao.prototype)Ao.prototype.hasOwnProperty(qa)&&z(Ka,qa)<0&&(Ma.prototype[qa]=function(t){return function(){return t.apply(this.doc,arguments)}}(Ao.prototype[qa]));return se(Ao),Ma.inputStyles={textarea:Ga,contenteditable:za},Ma.defineMode=function(t){Ma.defaults.mode||"null"==t||(Ma.defaults.mode=t),Le.apply(this,arguments);},Ma.defineMIME=function(t,e){ke[t]=e;},Ma.defineMode("null",(function(){return {token:function(t){return t.skipToEnd()}}})),Ma.defineMIME("text/plain","null"),Ma.defineExtension=function(t,e){Ma.prototype[t]=e;},Ma.defineDocExtension=function(t,e){Ao.prototype[t]=e;},Ma.fromTextArea=function(t,e){if((e=e?H(e):{}).value=t.value,!e.tabindex&&t.tabIndex&&(e.tabindex=t.tabIndex),!e.placeholder&&t.placeholder&&(e.placeholder=t.placeholder),null==e.autofocus){var r=D();e.autofocus=r==t||null!=t.getAttribute("autofocus")&&r==document.body;}function n(){t.value=s.getValue();}var i;if(t.form&&(te(t.form,"submit",n),!e.leaveSubmitMethodAlone)){var o=t.form;i=o.submit;try{var a=o.submit=function(){n(),o.submit=i,o.submit(),o.submit=a;};}catch(t){}}e.finishInit=function(e){e.save=n,e.getTextArea=function(){return t},e.toTextArea=function(){e.toTextArea=isNaN,n(),t.parentNode.removeChild(e.getWrapperElement()),t.style.display="",t.form&&(re(t.form,"submit",n),"function"==typeof t.form.submit&&(t.form.submit=i));};},t.style.display="none";var s=Ma((function(e){return t.parentNode.insertBefore(e,t.nextSibling)}),e);return s},function(t){t.off=re,t.on=te,t.wheelEventPixels=bi,t.Doc=Ao,t.splitLines=we,t.countColumn=F,t.findColumn=G,t.isWordChar=Q,t.Pass=j,t.signal=ne,t.Line=qe,t.changeEnd=ki,t.scrollbarModel=jn,t.Pos=vt,t.cmpPos=gt,t.modes=Se,t.mimeModes=ke,t.resolveMode=Me,t.getMode=Te,t.modeExtensions=Oe,t.extendMode=Ae,t.copyState=Ne,t.startState=We,t.innerMode=De,t.commands=ta,t.keyMap=Bo,t.keyName=$o,t.isModifierKey=Ko,t.lookupKey=Go,t.normalizeKeyMap=Vo,t.StringStream=Ee,t.SharedTextMarker=Lo,t.TextMarker=So,t.LineWidget=xo,t.e_preventDefault=le,t.e_stopPropagation=ue,t.e_stop=fe,t.addClass=W,t.contains=N,t.rmClass=L,t.keyNames=Fo;}(Ma),Ma.version="5.42.0",Ma}();},function(t,e,r){Object.defineProperty(e,"__esModule",{value:!0});var n=r(0),i=function(){function t(){}return t.prototype.isSeparator=function(t){return " "==t||"\r"==t||"\n"==t||"\t"==t||"("==t||")"==t},t.prototype.isWhiteSpace=function(t){return " "==t||"\r"==t||"\n"==t||"\t"==t},t.prototype.findLastSeparatorIndex=function(t){var e=this;return n.findLastIndex(t,(function(t){return e.isSeparator(t)}))},t.prototype.needSpaceAfter=function(t){return !("("==t)},t.prototype.isLastCharacterWhiteSpace=function(t){return !!t&&this.isWhiteSpace(t[t.length-1])},t.prototype.stripEndWithNonSeparatorCharacters=function(t){if(!t)return t;if(this.isSeparator(t[t.length-1]))return t;var e=this.findLastSeparatorIndex(t);return e<0?"":t.substr(0,e+1)},t.prototype.getEndNotSeparatorCharacers=function(t){if(!t)return t;if(this.isSeparator(t[t.length-1]))return "";var e=this.findLastSeparatorIndex(t);return e<0?t:t.substr(e+1)},t}();e.default=new i;},function(t,e,r){Object.defineProperty(e,"__esModule",{value:!0});var n=r(0),i=function(){function t(){}return t.prototype.quote=function(t){return /\s/g.test(t)?'"'+t+'"':t},t.prototype.buildDefaultObjOrGetOriginal=function(t,e){return n.isString(t)?{value:this.quote(t),type:e}:{value:t,type:e}},t.prototype.handleParseError=function(t,e,r){var i=this,o=e;return n.flatMap(r.expected,(function(t){var e=[];if("literal"==t.type&&(e=n.map([t.text||t.value],(function(t){return {value:t,type:"literal"}}))),"other"==t.type){var r=o.getLastTokenType()||"value";"value"==r&&(e=n.map(i.needCategories(),(function(t){return i.buildDefaultObjOrGetOriginal(t,"category")}))),"category"==r&&(e=n.map(i.needOperators(o.getLastCategory()),(function(t){return i.buildDefaultObjOrGetOriginal(t,"operator")}))),"operator"==r&&(e=n.map(i.needValues(o.getLastCategory(),o.getLastOperator()),(function(t){return i.buildDefaultObjOrGetOriginal(t,"value")})));}return e}))},t.prototype.hasCategory=function(t){return !1},t.prototype.hasOperator=function(t,e){return !1},t.prototype.needCategories=function(){return []},t.prototype.needOperators=function(t){return []},t.prototype.needValues=function(t,e){return []},t}();e.default=i;},function(t,e){t.exports=function(t){var e=[];return e.toString=function(){return this.map((function(e){var r=function(t,e){var r=t[1]||"",n=t[3];if(!n)return r;if(e&&"function"==typeof btoa){var i=(a=n,"/*# sourceMappingURL=data:application/json;charset=utf-8;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(a))))+" */"),o=n.sources.map((function(t){return "/*# sourceURL="+n.sourceRoot+t+" */"}));return [r].concat(o).concat([i]).join("\n")}var a;return [r].join("\n")}(e,t);return e[2]?"@media "+e[2]+"{"+r+"}":r})).join("")},e.i=function(t,r){"string"==typeof t&&(t=[[null,t,""]]);for(var n={},i=0;i=0&&f.splice(e,1);}function m(t){var e=document.createElement("style");if(void 0===t.attrs.type&&(t.attrs.type="text/css"),void 0===t.attrs.nonce){var n=function(){return r.nc}();n&&(t.attrs.nonce=n);}return y(e,t.attrs),v(t,e),e}function y(t,e){Object.keys(e).forEach((function(r){t.setAttribute(r,e[r]);}));}function b(t,e){var r,n,i,o;if(e.transform&&t.css){if(!(o="function"==typeof e.transform?e.transform(t.css):e.transform.default(t.css)))return function(){};t.css=o;}if(e.singleton){var a=c++;r=u||(u=m(e)),n=C.bind(null,r,a,!1),i=C.bind(null,r,a,!0);}else t.sourceMap&&"function"==typeof URL&&"function"==typeof URL.createObjectURL&&"function"==typeof URL.revokeObjectURL&&"function"==typeof Blob&&"function"==typeof btoa?(r=function(t){var e=document.createElement("link");return void 0===t.attrs.type&&(t.attrs.type="text/css"),t.attrs.rel="stylesheet",y(e,t.attrs),v(t,e),e}(e),n=S.bind(null,r,e),i=function(){g(r),r.href&&URL.revokeObjectURL(r.href);}):(r=m(e),n=_.bind(null,r),i=function(){g(r);});return n(t),function(e){if(e){if(e.css===t.css&&e.media===t.media&&e.sourceMap===t.sourceMap)return;n(t=e);}else i();}}t.exports=function(t,e){if("undefined"!=typeof DEBUG&&DEBUG&&"object"!=typeof document)throw new Error("The style-loader cannot be used in a non-browser environment");(e=e||{}).attrs="object"==typeof e.attrs?e.attrs:{},e.singleton||"boolean"==typeof e.singleton||(e.singleton=a()),e.insertInto||(e.insertInto="head"),e.insertAt||(e.insertAt="bottom");var r=p(t,e);return d(r,e),function(t){for(var n=[],i=0;i1)){if(this.somethingSelected()){if(!r.hint.supportsSelection)return;for(var i=0;iu.clientHeight+1,k=a.getScrollInfo();if(_>0){var L=C.bottom-C.top;if(g.top-(g.bottom-C.top)-L>0)u.style.top=(y=g.top-L)+"px",b=!1;else if(L>x){u.style.height=x-5+"px",u.style.top=(y=g.bottom-C.top)+"px";var M=a.getCursor();r.from.ch!=M.ch&&(g=a.cursorCoords(M),u.style.left=(m=g.left)+"px",C=u.getBoundingClientRect());}}var T,O=C.right-w;if(O>0&&(C.right-C.left>w&&(u.style.width=w-5+"px",O-=C.right-C.left-w),u.style.left=(m=g.left-O)+"px"),S)for(var A=u.firstChild;A;A=A.nextSibling)A.style.paddingRight=a.display.nativeBarWidth+"px";return a.addKeyMap(this.keyMap=function(t,e){var r={Up:function(){e.moveFocus(-1);},Down:function(){e.moveFocus(1);},PageUp:function(){e.moveFocus(1-e.menuSize(),!0);},PageDown:function(){e.moveFocus(e.menuSize()-1,!0);},Home:function(){e.setFocus(0);},End:function(){e.setFocus(e.length-1);},Enter:e.pick,Tab:e.pick,Esc:e.close},n=t.options.customKeys,i=n?{}:r;function o(t,n){var o;o="string"!=typeof n?function(t){return n(t,e)}:r.hasOwnProperty(n)?r[n]:n,i[t]=o;}if(n)for(var a in n)n.hasOwnProperty(a)&&o(a,n[a]);var s=t.options.extraKeys;if(s)for(var a in s)s.hasOwnProperty(a)&&o(a,s[a]);return i}(e,{moveFocus:function(t,e){n.changeActive(n.selectedHint+t,e);},setFocus:function(t){n.changeActive(t);},menuSize:function(){return n.screenAmount()},length:f.length,close:function(){e.close();},pick:function(){n.pick();},data:r})),e.options.closeOnUnfocus&&(a.on("blur",this.onBlur=function(){T=setTimeout((function(){e.close();}),100);}),a.on("focus",this.onFocus=function(){clearTimeout(T);})),a.on("scroll",this.onScroll=function(){var t=a.getScrollInfo(),r=a.getWrapperElement().getBoundingClientRect(),n=y+k.top-t.top,i=n-(l.pageYOffset||(s.documentElement||s.body).scrollTop);if(b||(i+=u.offsetHeight),i<=r.top||i>=r.bottom)return e.close();u.style.top=n+"px",u.style.left=m+k.left-t.left+"px";}),t.on(u,"dblclick",(function(t){var e=o(u,t.target||t.srcElement);e&&null!=e.hintId&&(n.changeActive(e.hintId),n.pick());})),t.on(u,"click",(function(t){var r=o(u,t.target||t.srcElement);r&&null!=r.hintId&&(n.changeActive(r.hintId),e.options.completeOnSingleClick&&n.pick());})),t.on(u,"mousedown",(function(){setTimeout((function(){a.focus();}),20);})),t.signal(r,"select",f[this.selectedHint],u.childNodes[this.selectedHint]),!0}function s(t,e,r,n){if(t.async)t(e,n,r);else {var i=t(e,r);i&&i.then?i.then(n):n(i);}}e.prototype={close:function(){this.active()&&(this.cm.state.completionActive=null,this.tick=null,this.cm.off("cursorActivity",this.activityFunc),this.widget&&this.data&&t.signal(this.data,"close"),this.widget&&this.widget.close(),t.signal(this.cm,"endCompletion",this.cm));},active:function(){return this.cm.state.completionActive==this},pick:function(e,r){var n=e.list[r];n.hint?n.hint(this.cm,e,n):this.cm.replaceRange(i(n),n.from||e.from,n.to||e.to,"complete"),t.signal(e,"pick",n),this.close();},cursorActivity:function(){this.debounce&&(n(this.debounce),this.debounce=0);var t=this.cm.getCursor(),e=this.cm.getLine(t.line);if(t.line!=this.startPos.line||e.length-t.ch!=this.startLen-this.startPos.ch||t.ch=this.data.list.length?e=r?this.data.list.length-1:0:e<0&&(e=r?0:this.data.list.length-1),this.selectedHint!=e){var n=this.hints.childNodes[this.selectedHint];n&&(n.className=n.className.replace(" CodeMirror-hint-active","")),(n=this.hints.childNodes[this.selectedHint=e]).className+=" CodeMirror-hint-active",n.offsetTopthis.hints.scrollTop+this.hints.clientHeight&&(this.hints.scrollTop=n.offsetTop+n.offsetHeight-this.hints.clientHeight+3),t.signal(this.data,"select",this.data.list[this.selectedHint],n);}},screenAmount:function(){return Math.floor(this.hints.clientHeight/this.hints.firstChild.offsetHeight)||1}},t.registerHelper("hint","auto",{resolve:function(e,r){var n,i=e.getHelpers(r,"hint");if(i.length){var o=function(t,e,r){var n=function(t,e){if(!t.somethingSelected())return e;for(var r=[],n=0;n0?e(t):i(o+1);}));}(0);};return o.async=!0,o.supportsSelection=!0,o}return (n=e.getHelper(e.getCursor(),"hintWords"))?function(e){return t.hint.fromList(e,{words:n})}:t.hint.anyword?function(e,r){return t.hint.anyword(e,r)}:function(){}}}),t.registerHelper("hint","fromList",(function(e,r){var n,i=e.getCursor(),o=e.getTokenAt(i),a=t.Pos(i.line,o.start),s=i;o.start,]/,closeOnUnfocus:!0,completeOnSingleClick:!0,container:null,customKeys:null,extraKeys:null};t.defineOption("hintOptions",null);}(r(2));},function(t,e,r){!function(t){function e(t){t.state.placeholder&&(t.state.placeholder.parentNode.removeChild(t.state.placeholder),t.state.placeholder=null);}function r(t){e(t);var r=t.state.placeholder=document.createElement("pre");r.style.cssText="height: 0; overflow: visible",r.style.direction=t.getOption("direction"),r.className="CodeMirror-placeholder";var n=t.getOption("placeholder");"string"==typeof n&&(n=document.createTextNode(n)),r.appendChild(n),t.display.lineSpace.insertBefore(r,t.display.lineSpace.firstChild);}function n(t){o(t)&&r(t);}function i(t){var n=t.getWrapperElement(),i=o(t);n.className=n.className.replace(" CodeMirror-empty","")+(i?" CodeMirror-empty":""),i?r(t):e(t);}function o(t){return 1===t.lineCount()&&""===t.getLine(0)}t.defineOption("placeholder","",(function(r,o,a){var s=a&&a!=t.Init;if(o&&!s)r.on("blur",n),r.on("change",i),r.on("swapDoc",i),i(r);else if(!o&&s){r.off("blur",n),r.off("change",i),r.off("swapDoc",i),e(r);var l=r.getWrapperElement();l.className=l.className.replace(" CodeMirror-empty","");}o&&!r.hasFocus()&&n(r);}));}(r(2));},function(t,e,r){Object.defineProperty(e,"__esModule",{value:!0}),r(2).defineMode("filter-mode",(function(t,e){function r(t){var e,r=(e=t.fieldState)==n.category?n.operator:e==n.operator?n.value:e==n.value?n.category:void 0,i=t.fieldState;return t.fieldState=r,i.toString()}return {startState:function(){return {inString:!1,fieldState:n.category}},token:function(t,e){return " "==(n=t.peek())||"\r"==n||"\n"==n||"\t"==n?(t.eatSpace(),null):"("==t.peek()||")"==t.peek()?(t.next(),"bracket"):t.match("AND",!0,!0)||t.match("OR",!0,!0)?"condition":(e.inString||'"'!=t.peek()||(t.next(),e.inString=!0),e.inString?(t.skipTo('"')?(t.next(),e.inString=!1):t.skipToEnd(),r(e)):(t.eatWhile(/[^\r\n\t\s\(\)]+/),r(e)));var n;}}}));var n=function(){function t(){}return t.none="none",t.category="category",t.operator="operator",t.value="value",t}();},function(t,e,r){var n=r(16);"string"==typeof n&&(n=[[t.i,n,""]]);var i={hmr:!0,transform:void 0,insertInto:void 0};r(6)(n,i);n.locals&&(t.exports=n.locals);},function(t,e,r){(t.exports=r(5)(!1)).push([t.i,".CodeMirror{font-family:monospace;height:300px;color:black;direction:ltr}.CodeMirror-lines{padding:4px 0}.CodeMirror pre{padding:0 4px}.CodeMirror-scrollbar-filler,.CodeMirror-gutter-filler{background-color:white}.CodeMirror-gutters{border-right:1px solid #ddd;background-color:#f7f7f7;white-space:nowrap}.CodeMirror-linenumber{padding:0 3px 0 5px;min-width:20px;text-align:right;color:#999;white-space:nowrap}.CodeMirror-guttermarker{color:black}.CodeMirror-guttermarker-subtle{color:#999}.CodeMirror-cursor{border-left:1px solid black;border-right:none;width:0}.CodeMirror div.CodeMirror-secondarycursor{border-left:1px solid silver}.cm-fat-cursor .CodeMirror-cursor{width:auto;border:0 !important;background:#7e7}.cm-fat-cursor div.CodeMirror-cursors{z-index:1}.cm-fat-cursor-mark{background-color:rgba(20,255,20,0.5);-webkit-animation:blink 1.06s steps(1) infinite;-moz-animation:blink 1.06s steps(1) infinite;animation:blink 1.06s steps(1) infinite}.cm-animate-fat-cursor{width:auto;border:0;-webkit-animation:blink 1.06s steps(1) infinite;-moz-animation:blink 1.06s steps(1) infinite;animation:blink 1.06s steps(1) infinite;background-color:#7e7}@-moz-keyframes blink{50%{background-color:transparent}}@-webkit-keyframes blink{50%{background-color:transparent}}@keyframes blink{50%{background-color:transparent}}.cm-tab{display:inline-block;text-decoration:inherit}.CodeMirror-rulers{position:absolute;left:0;right:0;top:-50px;bottom:-20px;overflow:hidden}.CodeMirror-ruler{border-left:1px solid #ccc;top:0;bottom:0;position:absolute}.cm-s-default .cm-header{color:blue}.cm-s-default .cm-quote{color:#090}.cm-negative{color:#d44}.cm-positive{color:#292}.cm-header,.cm-strong{font-weight:bold}.cm-em{font-style:italic}.cm-link{text-decoration:underline}.cm-strikethrough{text-decoration:line-through}.cm-s-default .cm-keyword{color:#708}.cm-s-default .cm-atom{color:#219}.cm-s-default .cm-number{color:#164}.cm-s-default .cm-def{color:#00f}.cm-s-default .cm-variable-2{color:#05a}.cm-s-default .cm-variable-3,.cm-s-default .cm-type{color:#085}.cm-s-default .cm-comment{color:#a50}.cm-s-default .cm-string{color:#a11}.cm-s-default .cm-string-2{color:#f50}.cm-s-default .cm-meta{color:#555}.cm-s-default .cm-qualifier{color:#555}.cm-s-default .cm-builtin{color:#30a}.cm-s-default .cm-bracket{color:#997}.cm-s-default .cm-tag{color:#170}.cm-s-default .cm-attribute{color:#00c}.cm-s-default .cm-hr{color:#999}.cm-s-default .cm-link{color:#00c}.cm-s-default .cm-error{color:#f00}.cm-invalidchar{color:#f00}.CodeMirror-composing{border-bottom:2px solid}div.CodeMirror span.CodeMirror-matchingbracket{color:#0b0}div.CodeMirror span.CodeMirror-nonmatchingbracket{color:#a22}.CodeMirror-matchingtag{background:rgba(255,150,0,0.3)}.CodeMirror-activeline-background{background:#e8f2ff}.CodeMirror{position:relative;overflow:hidden;background:white}.CodeMirror-scroll{overflow:scroll !important;margin-bottom:-30px;margin-right:-30px;padding-bottom:30px;height:100%;outline:none;position:relative}.CodeMirror-sizer{position:relative;border-right:30px solid transparent}.CodeMirror-vscrollbar,.CodeMirror-hscrollbar,.CodeMirror-scrollbar-filler,.CodeMirror-gutter-filler{position:absolute;z-index:6;display:none}.CodeMirror-vscrollbar{right:0;top:0;overflow-x:hidden;overflow-y:scroll}.CodeMirror-hscrollbar{bottom:0;left:0;overflow-y:hidden;overflow-x:scroll}.CodeMirror-scrollbar-filler{right:0;bottom:0}.CodeMirror-gutter-filler{left:0;bottom:0}.CodeMirror-gutters{position:absolute;left:0;top:0;min-height:100%;z-index:3}.CodeMirror-gutter{white-space:normal;height:100%;display:inline-block;vertical-align:top;margin-bottom:-30px}.CodeMirror-gutter-wrapper{position:absolute;z-index:4;background:none !important;border:none !important}.CodeMirror-gutter-background{position:absolute;top:0;bottom:0;z-index:4}.CodeMirror-gutter-elt{position:absolute;cursor:default;z-index:4}.CodeMirror-gutter-wrapper ::selection{background-color:transparent}.CodeMirror-gutter-wrapper ::-moz-selection{background-color:transparent}.CodeMirror-lines{cursor:text;min-height:1px}.CodeMirror pre{-moz-border-radius:0;-webkit-border-radius:0;border-radius:0;border-width:0;background:transparent;font-family:inherit;font-size:inherit;margin:0;white-space:pre;word-wrap:normal;line-height:inherit;color:inherit;z-index:2;position:relative;overflow:visible;-webkit-tap-highlight-color:transparent;-webkit-font-variant-ligatures:contextual;font-variant-ligatures:contextual}.CodeMirror-wrap pre{word-wrap:break-word;white-space:pre-wrap;word-break:normal}.CodeMirror-linebackground{position:absolute;left:0;right:0;top:0;bottom:0;z-index:0}.CodeMirror-linewidget{position:relative;z-index:2;padding:.1px}.CodeMirror-rtl pre{direction:rtl}.CodeMirror-code{outline:none}.CodeMirror-scroll,.CodeMirror-sizer,.CodeMirror-gutter,.CodeMirror-gutters,.CodeMirror-linenumber{-moz-box-sizing:content-box;box-sizing:content-box}.CodeMirror-measure{position:absolute;width:100%;height:0;overflow:hidden;visibility:hidden}.CodeMirror-cursor{position:absolute;pointer-events:none}.CodeMirror-measure pre{position:static}div.CodeMirror-cursors{visibility:hidden;position:relative;z-index:3}div.CodeMirror-dragcursors{visibility:visible}.CodeMirror-focused div.CodeMirror-cursors{visibility:visible}.CodeMirror-selected{background:#d9d9d9}.CodeMirror-focused .CodeMirror-selected{background:#d7d4f0}.CodeMirror-crosshair{cursor:crosshair}.CodeMirror-line::selection,.CodeMirror-line>span::selection,.CodeMirror-line>span>span::selection{background:#d7d4f0}.CodeMirror-line::-moz-selection,.CodeMirror-line>span::-moz-selection,.CodeMirror-line>span>span::-moz-selection{background:#d7d4f0}.cm-searching{background-color:#ffa;background-color:rgba(255,255,0,0.4)}.cm-force-border{padding-right:.1px}@media print{.CodeMirror div.CodeMirror-cursors{visibility:hidden}}.cm-tab-wrap-hack:after{content:''}span.CodeMirror-selectedtext{background:none}",""]);},function(t,e){t.exports=function(t){var e="undefined"!=typeof window&&window.location;if(!e)throw new Error("fixUrls requires window.location");if(!t||"string"!=typeof t)return t;var r=e.protocol+"//"+e.host,n=r+e.pathname.replace(/\/[^\/]*$/,"/");return t.replace(/url\s*\(((?:[^)(]|\((?:[^)(]+|\([^)(]*\))*\))*)\)/gi,(function(t,e){var i,o=e.trim().replace(/^"(.*)"$/,(function(t,e){return e})).replace(/^'(.*)'$/,(function(t,e){return e}));return /^(#|data:|http:\/\/|https:\/\/|file:\/\/\/|\s*$)/i.test(o)?t:(i=0===o.indexOf("//")?o:0===o.indexOf("/")?r+o:n+o.replace(/^\.\//,""),"url("+JSON.stringify(i)+")")}))};},function(t,e,r){var n=r(19);"string"==typeof n&&(n=[[t.i,n,""]]);var i={hmr:!0,transform:void 0,insertInto:void 0};r(6)(n,i);n.locals&&(t.exports=n.locals);},function(t,e,r){(t.exports=r(5)(!1)).push([t.i,".CodeMirror-hints{position:absolute;z-index:10;overflow:hidden;list-style:none;margin:0;padding:2px;-webkit-box-shadow:2px 3px 5px rgba(0,0,0,0.2);-moz-box-shadow:2px 3px 5px rgba(0,0,0,0.2);box-shadow:2px 3px 5px rgba(0,0,0,0.2);border-radius:3px;border:1px solid silver;background:white;font-size:90%;font-family:monospace;max-height:20em;overflow-y:auto}.CodeMirror-hint{margin:0;padding:0 4px;border-radius:2px;white-space:pre;color:black;cursor:pointer}li.CodeMirror-hint-active{background:#08f;color:white}",""]);},function(t,e,r){(function(t){var n,i=Object.assign||function(t){for(var e=1;e=0;case"!contains":return t[i].toLowerCase().indexOf(n.toLowerCase())<0}return !1},e}(r(8).default);e.default=a;},function(t,e,r){var n,i=this&&this.__extends||(n=function(t,e){return (n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e;}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r]);})(t,e)},function(t,e){function r(){this.constructor=t;}n(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r);});Object.defineProperty(e,"__esModule",{value:!0});var o=r(4),a=r(0),s=function(t){function e(e,r){var n=t.call(this)||this;return n.data=e,n.options=r,n.cache={},n.parseResult=null,n.categories=a.map(n.options,(function(t){return t.columnText?t.columnText:t.columnField})),n}return i(e,t),e.prototype.hasCategory=function(t){return void 0!==a.find(this.options,(function(e){return t===e.columnField||t===e.columnText}))},e.prototype.hasOperator=function(t,e){return this.needOperators(t).indexOf(e)>=0},e.prototype.needCategories=function(){return this.categories},e.prototype.needOperators=function(t){var e=a.find(this.options,(function(e){return null!=e.customOperatorFunc&&(e.columnText==t||e.columnField==t)}));return e?e.customOperatorFunc(t):["==","!=","contains","!contains"]},e.prototype.needValues=function(t,e){var r=a.find(this.options,(function(e){return e.columnField==t||e.columnText==t}));return null!=r&&"selection"==r.type&&null!=this.data?(this.cache[t]||(this.cache[t]=a.chain(this.data).map((function(e){return e[t]})).uniq().value()),this.cache[t]):null!=r&&r.customValuesFunc?r.customValuesFunc(t,e):[]},e}(o.default);e.default=s;},function(t,e,r){Object.defineProperty(e,"__esModule",{value:!0});var n=r(28),i=r(0),o=r(4),a=r(29),s=r(3),l=function(){function t(){this.autoCompleteHandler=new o.default,this.lastError=null,this.parseTrace=new a.default;}return t.prototype.parse=function(t){if(t=i.trim(t),i.isEmpty(t))return [];try{return this.parseQuery(t)}catch(t){return t.isError=!0,t}},t.prototype.parseQuery=function(t){return this.parseTrace.clear(),n.parse(t,{parseTrace:this.parseTrace})},t.prototype.getSuggestions=function(t){t=s.default.stripEndWithNonSeparatorCharacters(t);try{return this.parseQuery(t),!t||s.default.isLastCharacterWhiteSpace(t)?i.map(["AND","OR"],(function(t){return {value:t,type:"literal"}})):[]}catch(t){return this.autoCompleteHandler.handleParseError(n,this.parseTrace,t)}},t.prototype.setAutoCompleteHandler=function(t){this.autoCompleteHandler=t;},t}();e.default=l;},function(t,e,r){function n(t,e,r,i){this.message=t,this.expected=e,this.found=r,this.location=i,this.name="SyntaxError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,n);}!function(t,e){function r(){this.constructor=t;}r.prototype=e.prototype,t.prototype=new r;}(n,Error),n.buildMessage=function(t,e){var r={literal:function(t){return '"'+i(t.text)+'"'},class:function(t){var e,r="";for(e=0;e0){for(e=1,n=1;ek&&(k=C,L=[]),L.push(t));}function P(t,e,r){return new n(n.buildMessage(t,e),t,e,r)}function R(){var e,r,n,o,a,u,c,f;if(e=C,z()!==i)if((r=H())!==i){for(n=[],o=C,(a=I())!==i?("and"===t.substr(C,3).toLowerCase()?(u=t.substr(C,3),C+=3):(u=i,0===M&&E(s)),u===i&&("or"===t.substr(C,2).toLowerCase()?(u=t.substr(C,2),C+=2):(u=i,0===M&&E(l))),u!==i&&(c=I())!==i&&(f=H())!==i?o=a=[a,u,c,f]:(C=o,o=i)):(C=o,o=i);o!==i;)n.push(o),o=C,(a=I())!==i?("and"===t.substr(C,3).toLowerCase()?(u=t.substr(C,3),C+=3):(u=i,0===M&&E(s)),u===i&&("or"===t.substr(C,2).toLowerCase()?(u=t.substr(C,2),C+=2):(u=i,0===M&&E(l))),u!==i&&(c=I())!==i&&(f=H())!==i?o=a=[a,u,c,f]:(C=o,o=i)):(C=o,o=i);n!==i&&(o=z())!==i?(_=e,e=function(t,e){for(var r=[t],n=0;n 1 ? 's' : '') + ' required, but only ' + args.length + ' present'); + } +} + +/** + * @name isDate + * @category Common Helpers + * @summary Is the given value a date? + * + * @description + * Returns true if the given value is an instance of Date. The function works for dates transferred across iframes. + * + * @param {*} value - the value to check + * @returns {boolean} true if the given value is a date + * @throws {TypeError} 1 arguments required + * + * @example + * // For a valid date: + * const result = isDate(new Date()) + * //=> true + * + * @example + * // For an invalid date: + * const result = isDate(new Date(NaN)) + * //=> true + * + * @example + * // For some value: + * const result = isDate('2014-02-31') + * //=> false + * + * @example + * // For an object: + * const result = isDate({}) + * //=> false + */ +function isDate(value) { + requiredArgs(1, arguments); + return value instanceof Date || _typeof$1(value) === 'object' && Object.prototype.toString.call(value) === '[object Date]'; +} + +/** + * @name toDate + * @category Common Helpers + * @summary Convert the given argument to an instance of Date. + * + * @description + * Convert the given argument to an instance of Date. + * + * If the argument is an instance of Date, the function returns its clone. + * + * If the argument is a number, it is treated as a timestamp. + * + * If the argument is none of the above, the function returns Invalid Date. + * + * **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`. + * + * @param {Date|Number} argument - the value to convert + * @returns {Date} the parsed date in the local time zone + * @throws {TypeError} 1 argument required + * + * @example + * // Clone the date: + * const result = toDate(new Date(2014, 1, 11, 11, 30, 30)) + * //=> Tue Feb 11 2014 11:30:30 + * + * @example + * // Convert the timestamp to date: + * const result = toDate(1392098430000) + * //=> Tue Feb 11 2014 11:30:30 + */ +function toDate(argument) { + requiredArgs(1, arguments); + var argStr = Object.prototype.toString.call(argument); + + // Clone the date + if (argument instanceof Date || _typeof$1(argument) === 'object' && argStr === '[object Date]') { + // Prevent the date to lose the milliseconds when passed to new Date() in IE10 + return new Date(argument.getTime()); + } else if (typeof argument === 'number' || argStr === '[object Number]') { + return new Date(argument); + } else { + if ((typeof argument === 'string' || argStr === '[object String]') && typeof console !== 'undefined') { + // eslint-disable-next-line no-console + console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"); + // eslint-disable-next-line no-console + console.warn(new Error().stack); + } + return new Date(NaN); + } +} + +/** + * @name isValid + * @category Common Helpers + * @summary Is the given date valid? + * + * @description + * Returns false if argument is Invalid Date and true otherwise. + * Argument is converted to Date using `toDate`. See [toDate]{@link https://date-fns.org/docs/toDate} + * Invalid Date is a Date, whose time value is NaN. + * + * Time value of Date: http://es5.github.io/#x15.9.1.1 + * + * @param {*} date - the date to check + * @returns {Boolean} the date is valid + * @throws {TypeError} 1 argument required + * + * @example + * // For the valid date: + * const result = isValid(new Date(2014, 1, 31)) + * //=> true + * + * @example + * // For the value, convertable into a date: + * const result = isValid(1393804800000) + * //=> true + * + * @example + * // For the invalid date: + * const result = isValid(new Date('')) + * //=> false + */ +function isValid(dirtyDate) { + requiredArgs(1, arguments); + if (!isDate(dirtyDate) && typeof dirtyDate !== 'number') { + return false; + } + var date = toDate(dirtyDate); + return !isNaN(Number(date)); +} + +function toInteger(dirtyNumber) { + if (dirtyNumber === null || dirtyNumber === true || dirtyNumber === false) { + return NaN; + } + var number = Number(dirtyNumber); + if (isNaN(number)) { + return number; + } + return number < 0 ? Math.ceil(number) : Math.floor(number); +} + +/** + * @name addMilliseconds + * @category Millisecond Helpers + * @summary Add the specified number of milliseconds to the given date. + * + * @description + * Add the specified number of milliseconds to the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of milliseconds to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the milliseconds added + * @throws {TypeError} 2 arguments required + * + * @example + * // Add 750 milliseconds to 10 July 2014 12:45:30.000: + * const result = addMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750) + * //=> Thu Jul 10 2014 12:45:30.750 + */ +function addMilliseconds(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var timestamp = toDate(dirtyDate).getTime(); + var amount = toInteger(dirtyAmount); + return new Date(timestamp + amount); +} + +/** + * @name subMilliseconds + * @category Millisecond Helpers + * @summary Subtract the specified number of milliseconds from the given date. + * + * @description + * Subtract the specified number of milliseconds from the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of milliseconds to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the milliseconds subtracted + * @throws {TypeError} 2 arguments required + * + * @example + * // Subtract 750 milliseconds from 10 July 2014 12:45:30.000: + * const result = subMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750) + * //=> Thu Jul 10 2014 12:45:29.250 + */ +function subMilliseconds(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var amount = toInteger(dirtyAmount); + return addMilliseconds(dirtyDate, -amount); +} + +var MILLISECONDS_IN_DAY$1 = 86400000; +function getUTCDayOfYear(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var timestamp = date.getTime(); + date.setUTCMonth(0, 1); + date.setUTCHours(0, 0, 0, 0); + var startOfYearTimestamp = date.getTime(); + var difference = timestamp - startOfYearTimestamp; + return Math.floor(difference / MILLISECONDS_IN_DAY$1) + 1; +} + +function startOfUTCISOWeek(dirtyDate) { + requiredArgs(1, arguments); + var weekStartsOn = 1; + var date = toDate(dirtyDate); + var day = date.getUTCDay(); + var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; + date.setUTCDate(date.getUTCDate() - diff); + date.setUTCHours(0, 0, 0, 0); + return date; +} + +function getUTCISOWeekYear(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var year = date.getUTCFullYear(); + var fourthOfJanuaryOfNextYear = new Date(0); + fourthOfJanuaryOfNextYear.setUTCFullYear(year + 1, 0, 4); + fourthOfJanuaryOfNextYear.setUTCHours(0, 0, 0, 0); + var startOfNextYear = startOfUTCISOWeek(fourthOfJanuaryOfNextYear); + var fourthOfJanuaryOfThisYear = new Date(0); + fourthOfJanuaryOfThisYear.setUTCFullYear(year, 0, 4); + fourthOfJanuaryOfThisYear.setUTCHours(0, 0, 0, 0); + var startOfThisYear = startOfUTCISOWeek(fourthOfJanuaryOfThisYear); + if (date.getTime() >= startOfNextYear.getTime()) { + return year + 1; + } else if (date.getTime() >= startOfThisYear.getTime()) { + return year; + } else { + return year - 1; + } +} + +function startOfUTCISOWeekYear(dirtyDate) { + requiredArgs(1, arguments); + var year = getUTCISOWeekYear(dirtyDate); + var fourthOfJanuary = new Date(0); + fourthOfJanuary.setUTCFullYear(year, 0, 4); + fourthOfJanuary.setUTCHours(0, 0, 0, 0); + var date = startOfUTCISOWeek(fourthOfJanuary); + return date; +} + +var MILLISECONDS_IN_WEEK$2 = 604800000; +function getUTCISOWeek(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var diff = startOfUTCISOWeek(date).getTime() - startOfUTCISOWeekYear(date).getTime(); + + // Round the number of days to the nearest integer + // because the number of milliseconds in a week is not constant + // (e.g. it's different in the week of the daylight saving time clock shift) + return Math.round(diff / MILLISECONDS_IN_WEEK$2) + 1; +} + +var defaultOptions = {}; +function getDefaultOptions() { + return defaultOptions; +} + +function startOfUTCWeek(dirtyDate, options) { + var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; + requiredArgs(1, arguments); + var defaultOptions = getDefaultOptions(); + var weekStartsOn = toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0); + + // Test if weekStartsOn is between 0 and 6 _and_ is not NaN + if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { + throw new RangeError('weekStartsOn must be between 0 and 6 inclusively'); + } + var date = toDate(dirtyDate); + var day = date.getUTCDay(); + var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; + date.setUTCDate(date.getUTCDate() - diff); + date.setUTCHours(0, 0, 0, 0); + return date; +} + +function getUTCWeekYear(dirtyDate, options) { + var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var year = date.getUTCFullYear(); + var defaultOptions = getDefaultOptions(); + var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1); + + // Test if weekStartsOn is between 1 and 7 _and_ is not NaN + if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) { + throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively'); + } + var firstWeekOfNextYear = new Date(0); + firstWeekOfNextYear.setUTCFullYear(year + 1, 0, firstWeekContainsDate); + firstWeekOfNextYear.setUTCHours(0, 0, 0, 0); + var startOfNextYear = startOfUTCWeek(firstWeekOfNextYear, options); + var firstWeekOfThisYear = new Date(0); + firstWeekOfThisYear.setUTCFullYear(year, 0, firstWeekContainsDate); + firstWeekOfThisYear.setUTCHours(0, 0, 0, 0); + var startOfThisYear = startOfUTCWeek(firstWeekOfThisYear, options); + if (date.getTime() >= startOfNextYear.getTime()) { + return year + 1; + } else if (date.getTime() >= startOfThisYear.getTime()) { + return year; + } else { + return year - 1; + } +} + +function startOfUTCWeekYear(dirtyDate, options) { + var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; + requiredArgs(1, arguments); + var defaultOptions = getDefaultOptions(); + var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1); + var year = getUTCWeekYear(dirtyDate, options); + var firstWeek = new Date(0); + firstWeek.setUTCFullYear(year, 0, firstWeekContainsDate); + firstWeek.setUTCHours(0, 0, 0, 0); + var date = startOfUTCWeek(firstWeek, options); + return date; +} + +var MILLISECONDS_IN_WEEK$1 = 604800000; +function getUTCWeek(dirtyDate, options) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var diff = startOfUTCWeek(date, options).getTime() - startOfUTCWeekYear(date, options).getTime(); + + // Round the number of days to the nearest integer + // because the number of milliseconds in a week is not constant + // (e.g. it's different in the week of the daylight saving time clock shift) + return Math.round(diff / MILLISECONDS_IN_WEEK$1) + 1; +} + +function addLeadingZeros(number, targetLength) { + var sign = number < 0 ? '-' : ''; + var output = Math.abs(number).toString(); + while (output.length < targetLength) { + output = '0' + output; + } + return sign + output; +} + +/* + * | | Unit | | Unit | + * |-----|--------------------------------|-----|--------------------------------| + * | a | AM, PM | A* | | + * | d | Day of month | D | | + * | h | Hour [1-12] | H | Hour [0-23] | + * | m | Minute | M | Month | + * | s | Second | S | Fraction of second | + * | y | Year (abs) | Y | | + * + * Letters marked by * are not implemented but reserved by Unicode standard. + */ +var formatters$2 = { + // Year + y: function y(date, token) { + // From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_tokens + // | Year | y | yy | yyy | yyyy | yyyyy | + // |----------|-------|----|-------|-------|-------| + // | AD 1 | 1 | 01 | 001 | 0001 | 00001 | + // | AD 12 | 12 | 12 | 012 | 0012 | 00012 | + // | AD 123 | 123 | 23 | 123 | 0123 | 00123 | + // | AD 1234 | 1234 | 34 | 1234 | 1234 | 01234 | + // | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 | + + var signedYear = date.getUTCFullYear(); + // Returns 1 for 1 BC (which is year 0 in JavaScript) + var year = signedYear > 0 ? signedYear : 1 - signedYear; + return addLeadingZeros(token === 'yy' ? year % 100 : year, token.length); + }, + // Month + M: function M(date, token) { + var month = date.getUTCMonth(); + return token === 'M' ? String(month + 1) : addLeadingZeros(month + 1, 2); + }, + // Day of the month + d: function d(date, token) { + return addLeadingZeros(date.getUTCDate(), token.length); + }, + // AM or PM + a: function a(date, token) { + var dayPeriodEnumValue = date.getUTCHours() / 12 >= 1 ? 'pm' : 'am'; + switch (token) { + case 'a': + case 'aa': + return dayPeriodEnumValue.toUpperCase(); + case 'aaa': + return dayPeriodEnumValue; + case 'aaaaa': + return dayPeriodEnumValue[0]; + case 'aaaa': + default: + return dayPeriodEnumValue === 'am' ? 'a.m.' : 'p.m.'; + } + }, + // Hour [1-12] + h: function h(date, token) { + return addLeadingZeros(date.getUTCHours() % 12 || 12, token.length); + }, + // Hour [0-23] + H: function H(date, token) { + return addLeadingZeros(date.getUTCHours(), token.length); + }, + // Minute + m: function m(date, token) { + return addLeadingZeros(date.getUTCMinutes(), token.length); + }, + // Second + s: function s(date, token) { + return addLeadingZeros(date.getUTCSeconds(), token.length); + }, + // Fraction of second + S: function S(date, token) { + var numberOfDigits = token.length; + var milliseconds = date.getUTCMilliseconds(); + var fractionalSeconds = Math.floor(milliseconds * Math.pow(10, numberOfDigits - 3)); + return addLeadingZeros(fractionalSeconds, token.length); + } +}; +var lightFormatters = formatters$2; + +var dayPeriodEnum = { + am: 'am', + pm: 'pm', + midnight: 'midnight', + noon: 'noon', + morning: 'morning', + afternoon: 'afternoon', + evening: 'evening', + night: 'night' +}; +/* + * | | Unit | | Unit | + * |-----|--------------------------------|-----|--------------------------------| + * | a | AM, PM | A* | Milliseconds in day | + * | b | AM, PM, noon, midnight | B | Flexible day period | + * | c | Stand-alone local day of week | C* | Localized hour w/ day period | + * | d | Day of month | D | Day of year | + * | e | Local day of week | E | Day of week | + * | f | | F* | Day of week in month | + * | g* | Modified Julian day | G | Era | + * | h | Hour [1-12] | H | Hour [0-23] | + * | i! | ISO day of week | I! | ISO week of year | + * | j* | Localized hour w/ day period | J* | Localized hour w/o day period | + * | k | Hour [1-24] | K | Hour [0-11] | + * | l* | (deprecated) | L | Stand-alone month | + * | m | Minute | M | Month | + * | n | | N | | + * | o! | Ordinal number modifier | O | Timezone (GMT) | + * | p! | Long localized time | P! | Long localized date | + * | q | Stand-alone quarter | Q | Quarter | + * | r* | Related Gregorian year | R! | ISO week-numbering year | + * | s | Second | S | Fraction of second | + * | t! | Seconds timestamp | T! | Milliseconds timestamp | + * | u | Extended year | U* | Cyclic year | + * | v* | Timezone (generic non-locat.) | V* | Timezone (location) | + * | w | Local week of year | W* | Week of month | + * | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) | + * | y | Year (abs) | Y | Local week-numbering year | + * | z | Timezone (specific non-locat.) | Z* | Timezone (aliases) | + * + * Letters marked by * are not implemented but reserved by Unicode standard. + * + * Letters marked by ! are non-standard, but implemented by date-fns: + * - `o` modifies the previous token to turn it into an ordinal (see `format` docs) + * - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days, + * i.e. 7 for Sunday, 1 for Monday, etc. + * - `I` is ISO week of year, as opposed to `w` which is local week of year. + * - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year. + * `R` is supposed to be used in conjunction with `I` and `i` + * for universal ISO week-numbering date, whereas + * `Y` is supposed to be used in conjunction with `w` and `e` + * for week-numbering date specific to the locale. + * - `P` is long localized date format + * - `p` is long localized time format + */ + +var formatters = { + // Era + G: function G(date, token, localize) { + var era = date.getUTCFullYear() > 0 ? 1 : 0; + switch (token) { + // AD, BC + case 'G': + case 'GG': + case 'GGG': + return localize.era(era, { + width: 'abbreviated' + }); + // A, B + case 'GGGGG': + return localize.era(era, { + width: 'narrow' + }); + // Anno Domini, Before Christ + case 'GGGG': + default: + return localize.era(era, { + width: 'wide' + }); + } + }, + // Year + y: function y(date, token, localize) { + // Ordinal number + if (token === 'yo') { + var signedYear = date.getUTCFullYear(); + // Returns 1 for 1 BC (which is year 0 in JavaScript) + var year = signedYear > 0 ? signedYear : 1 - signedYear; + return localize.ordinalNumber(year, { + unit: 'year' + }); + } + return lightFormatters.y(date, token); + }, + // Local week-numbering year + Y: function Y(date, token, localize, options) { + var signedWeekYear = getUTCWeekYear(date, options); + // Returns 1 for 1 BC (which is year 0 in JavaScript) + var weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear; + + // Two digit year + if (token === 'YY') { + var twoDigitYear = weekYear % 100; + return addLeadingZeros(twoDigitYear, 2); + } + + // Ordinal number + if (token === 'Yo') { + return localize.ordinalNumber(weekYear, { + unit: 'year' + }); + } + + // Padding + return addLeadingZeros(weekYear, token.length); + }, + // ISO week-numbering year + R: function R(date, token) { + var isoWeekYear = getUTCISOWeekYear(date); + + // Padding + return addLeadingZeros(isoWeekYear, token.length); + }, + // Extended year. This is a single number designating the year of this calendar system. + // The main difference between `y` and `u` localizers are B.C. years: + // | Year | `y` | `u` | + // |------|-----|-----| + // | AC 1 | 1 | 1 | + // | BC 1 | 1 | 0 | + // | BC 2 | 2 | -1 | + // Also `yy` always returns the last two digits of a year, + // while `uu` pads single digit years to 2 characters and returns other years unchanged. + u: function u(date, token) { + var year = date.getUTCFullYear(); + return addLeadingZeros(year, token.length); + }, + // Quarter + Q: function Q(date, token, localize) { + var quarter = Math.ceil((date.getUTCMonth() + 1) / 3); + switch (token) { + // 1, 2, 3, 4 + case 'Q': + return String(quarter); + // 01, 02, 03, 04 + case 'QQ': + return addLeadingZeros(quarter, 2); + // 1st, 2nd, 3rd, 4th + case 'Qo': + return localize.ordinalNumber(quarter, { + unit: 'quarter' + }); + // Q1, Q2, Q3, Q4 + case 'QQQ': + return localize.quarter(quarter, { + width: 'abbreviated', + context: 'formatting' + }); + // 1, 2, 3, 4 (narrow quarter; could be not numerical) + case 'QQQQQ': + return localize.quarter(quarter, { + width: 'narrow', + context: 'formatting' + }); + // 1st quarter, 2nd quarter, ... + case 'QQQQ': + default: + return localize.quarter(quarter, { + width: 'wide', + context: 'formatting' + }); + } + }, + // Stand-alone quarter + q: function q(date, token, localize) { + var quarter = Math.ceil((date.getUTCMonth() + 1) / 3); + switch (token) { + // 1, 2, 3, 4 + case 'q': + return String(quarter); + // 01, 02, 03, 04 + case 'qq': + return addLeadingZeros(quarter, 2); + // 1st, 2nd, 3rd, 4th + case 'qo': + return localize.ordinalNumber(quarter, { + unit: 'quarter' + }); + // Q1, Q2, Q3, Q4 + case 'qqq': + return localize.quarter(quarter, { + width: 'abbreviated', + context: 'standalone' + }); + // 1, 2, 3, 4 (narrow quarter; could be not numerical) + case 'qqqqq': + return localize.quarter(quarter, { + width: 'narrow', + context: 'standalone' + }); + // 1st quarter, 2nd quarter, ... + case 'qqqq': + default: + return localize.quarter(quarter, { + width: 'wide', + context: 'standalone' + }); + } + }, + // Month + M: function M(date, token, localize) { + var month = date.getUTCMonth(); + switch (token) { + case 'M': + case 'MM': + return lightFormatters.M(date, token); + // 1st, 2nd, ..., 12th + case 'Mo': + return localize.ordinalNumber(month + 1, { + unit: 'month' + }); + // Jan, Feb, ..., Dec + case 'MMM': + return localize.month(month, { + width: 'abbreviated', + context: 'formatting' + }); + // J, F, ..., D + case 'MMMMM': + return localize.month(month, { + width: 'narrow', + context: 'formatting' + }); + // January, February, ..., December + case 'MMMM': + default: + return localize.month(month, { + width: 'wide', + context: 'formatting' + }); + } + }, + // Stand-alone month + L: function L(date, token, localize) { + var month = date.getUTCMonth(); + switch (token) { + // 1, 2, ..., 12 + case 'L': + return String(month + 1); + // 01, 02, ..., 12 + case 'LL': + return addLeadingZeros(month + 1, 2); + // 1st, 2nd, ..., 12th + case 'Lo': + return localize.ordinalNumber(month + 1, { + unit: 'month' + }); + // Jan, Feb, ..., Dec + case 'LLL': + return localize.month(month, { + width: 'abbreviated', + context: 'standalone' + }); + // J, F, ..., D + case 'LLLLL': + return localize.month(month, { + width: 'narrow', + context: 'standalone' + }); + // January, February, ..., December + case 'LLLL': + default: + return localize.month(month, { + width: 'wide', + context: 'standalone' + }); + } + }, + // Local week of year + w: function w(date, token, localize, options) { + var week = getUTCWeek(date, options); + if (token === 'wo') { + return localize.ordinalNumber(week, { + unit: 'week' + }); + } + return addLeadingZeros(week, token.length); + }, + // ISO week of year + I: function I(date, token, localize) { + var isoWeek = getUTCISOWeek(date); + if (token === 'Io') { + return localize.ordinalNumber(isoWeek, { + unit: 'week' + }); + } + return addLeadingZeros(isoWeek, token.length); + }, + // Day of the month + d: function d(date, token, localize) { + if (token === 'do') { + return localize.ordinalNumber(date.getUTCDate(), { + unit: 'date' + }); + } + return lightFormatters.d(date, token); + }, + // Day of year + D: function D(date, token, localize) { + var dayOfYear = getUTCDayOfYear(date); + if (token === 'Do') { + return localize.ordinalNumber(dayOfYear, { + unit: 'dayOfYear' + }); + } + return addLeadingZeros(dayOfYear, token.length); + }, + // Day of week + E: function E(date, token, localize) { + var dayOfWeek = date.getUTCDay(); + switch (token) { + // Tue + case 'E': + case 'EE': + case 'EEE': + return localize.day(dayOfWeek, { + width: 'abbreviated', + context: 'formatting' + }); + // T + case 'EEEEE': + return localize.day(dayOfWeek, { + width: 'narrow', + context: 'formatting' + }); + // Tu + case 'EEEEEE': + return localize.day(dayOfWeek, { + width: 'short', + context: 'formatting' + }); + // Tuesday + case 'EEEE': + default: + return localize.day(dayOfWeek, { + width: 'wide', + context: 'formatting' + }); + } + }, + // Local day of week + e: function e(date, token, localize, options) { + var dayOfWeek = date.getUTCDay(); + var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7; + switch (token) { + // Numerical value (Nth day of week with current locale or weekStartsOn) + case 'e': + return String(localDayOfWeek); + // Padded numerical value + case 'ee': + return addLeadingZeros(localDayOfWeek, 2); + // 1st, 2nd, ..., 7th + case 'eo': + return localize.ordinalNumber(localDayOfWeek, { + unit: 'day' + }); + case 'eee': + return localize.day(dayOfWeek, { + width: 'abbreviated', + context: 'formatting' + }); + // T + case 'eeeee': + return localize.day(dayOfWeek, { + width: 'narrow', + context: 'formatting' + }); + // Tu + case 'eeeeee': + return localize.day(dayOfWeek, { + width: 'short', + context: 'formatting' + }); + // Tuesday + case 'eeee': + default: + return localize.day(dayOfWeek, { + width: 'wide', + context: 'formatting' + }); + } + }, + // Stand-alone local day of week + c: function c(date, token, localize, options) { + var dayOfWeek = date.getUTCDay(); + var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7; + switch (token) { + // Numerical value (same as in `e`) + case 'c': + return String(localDayOfWeek); + // Padded numerical value + case 'cc': + return addLeadingZeros(localDayOfWeek, token.length); + // 1st, 2nd, ..., 7th + case 'co': + return localize.ordinalNumber(localDayOfWeek, { + unit: 'day' + }); + case 'ccc': + return localize.day(dayOfWeek, { + width: 'abbreviated', + context: 'standalone' + }); + // T + case 'ccccc': + return localize.day(dayOfWeek, { + width: 'narrow', + context: 'standalone' + }); + // Tu + case 'cccccc': + return localize.day(dayOfWeek, { + width: 'short', + context: 'standalone' + }); + // Tuesday + case 'cccc': + default: + return localize.day(dayOfWeek, { + width: 'wide', + context: 'standalone' + }); + } + }, + // ISO day of week + i: function i(date, token, localize) { + var dayOfWeek = date.getUTCDay(); + var isoDayOfWeek = dayOfWeek === 0 ? 7 : dayOfWeek; + switch (token) { + // 2 + case 'i': + return String(isoDayOfWeek); + // 02 + case 'ii': + return addLeadingZeros(isoDayOfWeek, token.length); + // 2nd + case 'io': + return localize.ordinalNumber(isoDayOfWeek, { + unit: 'day' + }); + // Tue + case 'iii': + return localize.day(dayOfWeek, { + width: 'abbreviated', + context: 'formatting' + }); + // T + case 'iiiii': + return localize.day(dayOfWeek, { + width: 'narrow', + context: 'formatting' + }); + // Tu + case 'iiiiii': + return localize.day(dayOfWeek, { + width: 'short', + context: 'formatting' + }); + // Tuesday + case 'iiii': + default: + return localize.day(dayOfWeek, { + width: 'wide', + context: 'formatting' + }); + } + }, + // AM or PM + a: function a(date, token, localize) { + var hours = date.getUTCHours(); + var dayPeriodEnumValue = hours / 12 >= 1 ? 'pm' : 'am'; + switch (token) { + case 'a': + case 'aa': + return localize.dayPeriod(dayPeriodEnumValue, { + width: 'abbreviated', + context: 'formatting' + }); + case 'aaa': + return localize.dayPeriod(dayPeriodEnumValue, { + width: 'abbreviated', + context: 'formatting' + }).toLowerCase(); + case 'aaaaa': + return localize.dayPeriod(dayPeriodEnumValue, { + width: 'narrow', + context: 'formatting' + }); + case 'aaaa': + default: + return localize.dayPeriod(dayPeriodEnumValue, { + width: 'wide', + context: 'formatting' + }); + } + }, + // AM, PM, midnight, noon + b: function b(date, token, localize) { + var hours = date.getUTCHours(); + var dayPeriodEnumValue; + if (hours === 12) { + dayPeriodEnumValue = dayPeriodEnum.noon; + } else if (hours === 0) { + dayPeriodEnumValue = dayPeriodEnum.midnight; + } else { + dayPeriodEnumValue = hours / 12 >= 1 ? 'pm' : 'am'; + } + switch (token) { + case 'b': + case 'bb': + return localize.dayPeriod(dayPeriodEnumValue, { + width: 'abbreviated', + context: 'formatting' + }); + case 'bbb': + return localize.dayPeriod(dayPeriodEnumValue, { + width: 'abbreviated', + context: 'formatting' + }).toLowerCase(); + case 'bbbbb': + return localize.dayPeriod(dayPeriodEnumValue, { + width: 'narrow', + context: 'formatting' + }); + case 'bbbb': + default: + return localize.dayPeriod(dayPeriodEnumValue, { + width: 'wide', + context: 'formatting' + }); + } + }, + // in the morning, in the afternoon, in the evening, at night + B: function B(date, token, localize) { + var hours = date.getUTCHours(); + var dayPeriodEnumValue; + if (hours >= 17) { + dayPeriodEnumValue = dayPeriodEnum.evening; + } else if (hours >= 12) { + dayPeriodEnumValue = dayPeriodEnum.afternoon; + } else if (hours >= 4) { + dayPeriodEnumValue = dayPeriodEnum.morning; + } else { + dayPeriodEnumValue = dayPeriodEnum.night; + } + switch (token) { + case 'B': + case 'BB': + case 'BBB': + return localize.dayPeriod(dayPeriodEnumValue, { + width: 'abbreviated', + context: 'formatting' + }); + case 'BBBBB': + return localize.dayPeriod(dayPeriodEnumValue, { + width: 'narrow', + context: 'formatting' + }); + case 'BBBB': + default: + return localize.dayPeriod(dayPeriodEnumValue, { + width: 'wide', + context: 'formatting' + }); + } + }, + // Hour [1-12] + h: function h(date, token, localize) { + if (token === 'ho') { + var hours = date.getUTCHours() % 12; + if (hours === 0) hours = 12; + return localize.ordinalNumber(hours, { + unit: 'hour' + }); + } + return lightFormatters.h(date, token); + }, + // Hour [0-23] + H: function H(date, token, localize) { + if (token === 'Ho') { + return localize.ordinalNumber(date.getUTCHours(), { + unit: 'hour' + }); + } + return lightFormatters.H(date, token); + }, + // Hour [0-11] + K: function K(date, token, localize) { + var hours = date.getUTCHours() % 12; + if (token === 'Ko') { + return localize.ordinalNumber(hours, { + unit: 'hour' + }); + } + return addLeadingZeros(hours, token.length); + }, + // Hour [1-24] + k: function k(date, token, localize) { + var hours = date.getUTCHours(); + if (hours === 0) hours = 24; + if (token === 'ko') { + return localize.ordinalNumber(hours, { + unit: 'hour' + }); + } + return addLeadingZeros(hours, token.length); + }, + // Minute + m: function m(date, token, localize) { + if (token === 'mo') { + return localize.ordinalNumber(date.getUTCMinutes(), { + unit: 'minute' + }); + } + return lightFormatters.m(date, token); + }, + // Second + s: function s(date, token, localize) { + if (token === 'so') { + return localize.ordinalNumber(date.getUTCSeconds(), { + unit: 'second' + }); + } + return lightFormatters.s(date, token); + }, + // Fraction of second + S: function S(date, token) { + return lightFormatters.S(date, token); + }, + // Timezone (ISO-8601. If offset is 0, output is always `'Z'`) + X: function X(date, token, _localize, options) { + var originalDate = options._originalDate || date; + var timezoneOffset = originalDate.getTimezoneOffset(); + if (timezoneOffset === 0) { + return 'Z'; + } + switch (token) { + // Hours and optional minutes + case 'X': + return formatTimezoneWithOptionalMinutes(timezoneOffset); + + // Hours, minutes and optional seconds without `:` delimiter + // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets + // so this token always has the same output as `XX` + case 'XXXX': + case 'XX': + // Hours and minutes without `:` delimiter + return formatTimezone(timezoneOffset); + + // Hours, minutes and optional seconds with `:` delimiter + // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets + // so this token always has the same output as `XXX` + case 'XXXXX': + case 'XXX': // Hours and minutes with `:` delimiter + default: + return formatTimezone(timezoneOffset, ':'); + } + }, + // Timezone (ISO-8601. If offset is 0, output is `'+00:00'` or equivalent) + x: function x(date, token, _localize, options) { + var originalDate = options._originalDate || date; + var timezoneOffset = originalDate.getTimezoneOffset(); + switch (token) { + // Hours and optional minutes + case 'x': + return formatTimezoneWithOptionalMinutes(timezoneOffset); + + // Hours, minutes and optional seconds without `:` delimiter + // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets + // so this token always has the same output as `xx` + case 'xxxx': + case 'xx': + // Hours and minutes without `:` delimiter + return formatTimezone(timezoneOffset); + + // Hours, minutes and optional seconds with `:` delimiter + // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets + // so this token always has the same output as `xxx` + case 'xxxxx': + case 'xxx': // Hours and minutes with `:` delimiter + default: + return formatTimezone(timezoneOffset, ':'); + } + }, + // Timezone (GMT) + O: function O(date, token, _localize, options) { + var originalDate = options._originalDate || date; + var timezoneOffset = originalDate.getTimezoneOffset(); + switch (token) { + // Short + case 'O': + case 'OO': + case 'OOO': + return 'GMT' + formatTimezoneShort(timezoneOffset, ':'); + // Long + case 'OOOO': + default: + return 'GMT' + formatTimezone(timezoneOffset, ':'); + } + }, + // Timezone (specific non-location) + z: function z(date, token, _localize, options) { + var originalDate = options._originalDate || date; + var timezoneOffset = originalDate.getTimezoneOffset(); + switch (token) { + // Short + case 'z': + case 'zz': + case 'zzz': + return 'GMT' + formatTimezoneShort(timezoneOffset, ':'); + // Long + case 'zzzz': + default: + return 'GMT' + formatTimezone(timezoneOffset, ':'); + } + }, + // Seconds timestamp + t: function t(date, token, _localize, options) { + var originalDate = options._originalDate || date; + var timestamp = Math.floor(originalDate.getTime() / 1000); + return addLeadingZeros(timestamp, token.length); + }, + // Milliseconds timestamp + T: function T(date, token, _localize, options) { + var originalDate = options._originalDate || date; + var timestamp = originalDate.getTime(); + return addLeadingZeros(timestamp, token.length); + } +}; +function formatTimezoneShort(offset, dirtyDelimiter) { + var sign = offset > 0 ? '-' : '+'; + var absOffset = Math.abs(offset); + var hours = Math.floor(absOffset / 60); + var minutes = absOffset % 60; + if (minutes === 0) { + return sign + String(hours); + } + var delimiter = dirtyDelimiter || ''; + return sign + String(hours) + delimiter + addLeadingZeros(minutes, 2); +} +function formatTimezoneWithOptionalMinutes(offset, dirtyDelimiter) { + if (offset % 60 === 0) { + var sign = offset > 0 ? '-' : '+'; + return sign + addLeadingZeros(Math.abs(offset) / 60, 2); + } + return formatTimezone(offset, dirtyDelimiter); +} +function formatTimezone(offset, dirtyDelimiter) { + var delimiter = dirtyDelimiter || ''; + var sign = offset > 0 ? '-' : '+'; + var absOffset = Math.abs(offset); + var hours = addLeadingZeros(Math.floor(absOffset / 60), 2); + var minutes = addLeadingZeros(absOffset % 60, 2); + return sign + hours + delimiter + minutes; +} +var formatters$1 = formatters; + +var dateLongFormatter = function dateLongFormatter(pattern, formatLong) { + switch (pattern) { + case 'P': + return formatLong.date({ + width: 'short' + }); + case 'PP': + return formatLong.date({ + width: 'medium' + }); + case 'PPP': + return formatLong.date({ + width: 'long' + }); + case 'PPPP': + default: + return formatLong.date({ + width: 'full' + }); + } +}; +var timeLongFormatter = function timeLongFormatter(pattern, formatLong) { + switch (pattern) { + case 'p': + return formatLong.time({ + width: 'short' + }); + case 'pp': + return formatLong.time({ + width: 'medium' + }); + case 'ppp': + return formatLong.time({ + width: 'long' + }); + case 'pppp': + default: + return formatLong.time({ + width: 'full' + }); + } +}; +var dateTimeLongFormatter = function dateTimeLongFormatter(pattern, formatLong) { + var matchResult = pattern.match(/(P+)(p+)?/) || []; + var datePattern = matchResult[1]; + var timePattern = matchResult[2]; + if (!timePattern) { + return dateLongFormatter(pattern, formatLong); + } + var dateTimeFormat; + switch (datePattern) { + case 'P': + dateTimeFormat = formatLong.dateTime({ + width: 'short' + }); + break; + case 'PP': + dateTimeFormat = formatLong.dateTime({ + width: 'medium' + }); + break; + case 'PPP': + dateTimeFormat = formatLong.dateTime({ + width: 'long' + }); + break; + case 'PPPP': + default: + dateTimeFormat = formatLong.dateTime({ + width: 'full' + }); + break; + } + return dateTimeFormat.replace('{{date}}', dateLongFormatter(datePattern, formatLong)).replace('{{time}}', timeLongFormatter(timePattern, formatLong)); +}; +var longFormatters = { + p: timeLongFormatter, + P: dateTimeLongFormatter +}; +var longFormatters$1 = longFormatters; + +/** + * Google Chrome as of 67.0.3396.87 introduced timezones with offset that includes seconds. + * They usually appear for dates that denote time before the timezones were introduced + * (e.g. for 'Europe/Prague' timezone the offset is GMT+00:57:44 before 1 October 1891 + * and GMT+01:00:00 after that date) + * + * Date#getTimezoneOffset returns the offset in minutes and would return 57 for the example above, + * which would lead to incorrect calculations. + * + * This function returns the timezone offset in milliseconds that takes seconds in account. + */ +function getTimezoneOffsetInMilliseconds(date) { + var utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds())); + utcDate.setUTCFullYear(date.getFullYear()); + return date.getTime() - utcDate.getTime(); +} + +var protectedDayOfYearTokens = ['D', 'DD']; +var protectedWeekYearTokens = ['YY', 'YYYY']; +function isProtectedDayOfYearToken(token) { + return protectedDayOfYearTokens.indexOf(token) !== -1; +} +function isProtectedWeekYearToken(token) { + return protectedWeekYearTokens.indexOf(token) !== -1; +} +function throwProtectedError(token, format, input) { + if (token === 'YYYY') { + throw new RangeError("Use `yyyy` instead of `YYYY` (in `".concat(format, "`) for formatting years to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md")); + } else if (token === 'YY') { + throw new RangeError("Use `yy` instead of `YY` (in `".concat(format, "`) for formatting years to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md")); + } else if (token === 'D') { + throw new RangeError("Use `d` instead of `D` (in `".concat(format, "`) for formatting days of the month to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md")); + } else if (token === 'DD') { + throw new RangeError("Use `dd` instead of `DD` (in `".concat(format, "`) for formatting days of the month to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md")); + } +} + +var formatDistanceLocale = { + lessThanXSeconds: { + one: 'less than a second', + other: 'less than {{count}} seconds' + }, + xSeconds: { + one: '1 second', + other: '{{count}} seconds' + }, + halfAMinute: 'half a minute', + lessThanXMinutes: { + one: 'less than a minute', + other: 'less than {{count}} minutes' + }, + xMinutes: { + one: '1 minute', + other: '{{count}} minutes' + }, + aboutXHours: { + one: 'about 1 hour', + other: 'about {{count}} hours' + }, + xHours: { + one: '1 hour', + other: '{{count}} hours' + }, + xDays: { + one: '1 day', + other: '{{count}} days' + }, + aboutXWeeks: { + one: 'about 1 week', + other: 'about {{count}} weeks' + }, + xWeeks: { + one: '1 week', + other: '{{count}} weeks' + }, + aboutXMonths: { + one: 'about 1 month', + other: 'about {{count}} months' + }, + xMonths: { + one: '1 month', + other: '{{count}} months' + }, + aboutXYears: { + one: 'about 1 year', + other: 'about {{count}} years' + }, + xYears: { + one: '1 year', + other: '{{count}} years' + }, + overXYears: { + one: 'over 1 year', + other: 'over {{count}} years' + }, + almostXYears: { + one: 'almost 1 year', + other: 'almost {{count}} years' + } +}; +var formatDistance = function formatDistance(token, count, options) { + var result; + var tokenValue = formatDistanceLocale[token]; + if (typeof tokenValue === 'string') { + result = tokenValue; + } else if (count === 1) { + result = tokenValue.one; + } else { + result = tokenValue.other.replace('{{count}}', count.toString()); + } + if (options !== null && options !== void 0 && options.addSuffix) { + if (options.comparison && options.comparison > 0) { + return 'in ' + result; + } else { + return result + ' ago'; + } + } + return result; +}; +var formatDistance$1 = formatDistance; + +function buildFormatLongFn(args) { + return function () { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + // TODO: Remove String() + var width = options.width ? String(options.width) : args.defaultWidth; + var format = args.formats[width] || args.formats[args.defaultWidth]; + return format; + }; +} + +var dateFormats = { + full: 'EEEE, MMMM do, y', + long: 'MMMM do, y', + medium: 'MMM d, y', + short: 'MM/dd/yyyy' +}; +var timeFormats = { + full: 'h:mm:ss a zzzz', + long: 'h:mm:ss a z', + medium: 'h:mm:ss a', + short: 'h:mm a' +}; +var dateTimeFormats = { + full: "{{date}} 'at' {{time}}", + long: "{{date}} 'at' {{time}}", + medium: '{{date}}, {{time}}', + short: '{{date}}, {{time}}' +}; +var formatLong = { + date: buildFormatLongFn({ + formats: dateFormats, + defaultWidth: 'full' + }), + time: buildFormatLongFn({ + formats: timeFormats, + defaultWidth: 'full' + }), + dateTime: buildFormatLongFn({ + formats: dateTimeFormats, + defaultWidth: 'full' + }) +}; +var formatLong$1 = formatLong; + +var formatRelativeLocale = { + lastWeek: "'last' eeee 'at' p", + yesterday: "'yesterday at' p", + today: "'today at' p", + tomorrow: "'tomorrow at' p", + nextWeek: "eeee 'at' p", + other: 'P' +}; +var formatRelative = function formatRelative(token, _date, _baseDate, _options) { + return formatRelativeLocale[token]; +}; +var formatRelative$1 = formatRelative; + +function buildLocalizeFn(args) { + return function (dirtyIndex, options) { + var context = options !== null && options !== void 0 && options.context ? String(options.context) : 'standalone'; + var valuesArray; + if (context === 'formatting' && args.formattingValues) { + var defaultWidth = args.defaultFormattingWidth || args.defaultWidth; + var width = options !== null && options !== void 0 && options.width ? String(options.width) : defaultWidth; + valuesArray = args.formattingValues[width] || args.formattingValues[defaultWidth]; + } else { + var _defaultWidth = args.defaultWidth; + var _width = options !== null && options !== void 0 && options.width ? String(options.width) : args.defaultWidth; + valuesArray = args.values[_width] || args.values[_defaultWidth]; + } + var index = args.argumentCallback ? args.argumentCallback(dirtyIndex) : dirtyIndex; + // @ts-ignore: For some reason TypeScript just don't want to match it, no matter how hard we try. I challenge you to try to remove it! + return valuesArray[index]; + }; +} + +var eraValues = { + narrow: ['B', 'A'], + abbreviated: ['BC', 'AD'], + wide: ['Before Christ', 'Anno Domini'] +}; +var quarterValues = { + narrow: ['1', '2', '3', '4'], + abbreviated: ['Q1', 'Q2', 'Q3', 'Q4'], + wide: ['1st quarter', '2nd quarter', '3rd quarter', '4th quarter'] +}; + +// Note: in English, the names of days of the week and months are capitalized. +// If you are making a new locale based on this one, check if the same is true for the language you're working on. +// Generally, formatted dates should look like they are in the middle of a sentence, +// e.g. in Spanish language the weekdays and months should be in the lowercase. +var monthValues = { + narrow: ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], + abbreviated: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], + wide: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] +}; +var dayValues = { + narrow: ['S', 'M', 'T', 'W', 'T', 'F', 'S'], + short: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], + abbreviated: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], + wide: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] +}; +var dayPeriodValues = { + narrow: { + am: 'a', + pm: 'p', + midnight: 'mi', + noon: 'n', + morning: 'morning', + afternoon: 'afternoon', + evening: 'evening', + night: 'night' + }, + abbreviated: { + am: 'AM', + pm: 'PM', + midnight: 'midnight', + noon: 'noon', + morning: 'morning', + afternoon: 'afternoon', + evening: 'evening', + night: 'night' + }, + wide: { + am: 'a.m.', + pm: 'p.m.', + midnight: 'midnight', + noon: 'noon', + morning: 'morning', + afternoon: 'afternoon', + evening: 'evening', + night: 'night' + } +}; +var formattingDayPeriodValues = { + narrow: { + am: 'a', + pm: 'p', + midnight: 'mi', + noon: 'n', + morning: 'in the morning', + afternoon: 'in the afternoon', + evening: 'in the evening', + night: 'at night' + }, + abbreviated: { + am: 'AM', + pm: 'PM', + midnight: 'midnight', + noon: 'noon', + morning: 'in the morning', + afternoon: 'in the afternoon', + evening: 'in the evening', + night: 'at night' + }, + wide: { + am: 'a.m.', + pm: 'p.m.', + midnight: 'midnight', + noon: 'noon', + morning: 'in the morning', + afternoon: 'in the afternoon', + evening: 'in the evening', + night: 'at night' + } +}; +var ordinalNumber = function ordinalNumber(dirtyNumber, _options) { + var number = Number(dirtyNumber); + + // If ordinal numbers depend on context, for example, + // if they are different for different grammatical genders, + // use `options.unit`. + // + // `unit` can be 'year', 'quarter', 'month', 'week', 'date', 'dayOfYear', + // 'day', 'hour', 'minute', 'second'. + + var rem100 = number % 100; + if (rem100 > 20 || rem100 < 10) { + switch (rem100 % 10) { + case 1: + return number + 'st'; + case 2: + return number + 'nd'; + case 3: + return number + 'rd'; + } + } + return number + 'th'; +}; +var localize = { + ordinalNumber: ordinalNumber, + era: buildLocalizeFn({ + values: eraValues, + defaultWidth: 'wide' + }), + quarter: buildLocalizeFn({ + values: quarterValues, + defaultWidth: 'wide', + argumentCallback: function argumentCallback(quarter) { + return quarter - 1; + } + }), + month: buildLocalizeFn({ + values: monthValues, + defaultWidth: 'wide' + }), + day: buildLocalizeFn({ + values: dayValues, + defaultWidth: 'wide' + }), + dayPeriod: buildLocalizeFn({ + values: dayPeriodValues, + defaultWidth: 'wide', + formattingValues: formattingDayPeriodValues, + defaultFormattingWidth: 'wide' + }) +}; +var localize$1 = localize; + +function buildMatchFn(args) { + return function (string) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var width = options.width; + var matchPattern = width && args.matchPatterns[width] || args.matchPatterns[args.defaultMatchWidth]; + var matchResult = string.match(matchPattern); + if (!matchResult) { + return null; + } + var matchedString = matchResult[0]; + var parsePatterns = width && args.parsePatterns[width] || args.parsePatterns[args.defaultParseWidth]; + var key = Array.isArray(parsePatterns) ? findIndex(parsePatterns, function (pattern) { + return pattern.test(matchedString); + }) : findKey(parsePatterns, function (pattern) { + return pattern.test(matchedString); + }); + var value; + value = args.valueCallback ? args.valueCallback(key) : key; + value = options.valueCallback ? options.valueCallback(value) : value; + var rest = string.slice(matchedString.length); + return { + value: value, + rest: rest + }; + }; +} +function findKey(object, predicate) { + for (var key in object) { + if (object.hasOwnProperty(key) && predicate(object[key])) { + return key; + } + } + return undefined; +} +function findIndex(array, predicate) { + for (var key = 0; key < array.length; key++) { + if (predicate(array[key])) { + return key; + } + } + return undefined; +} + +function buildMatchPatternFn(args) { + return function (string) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var matchResult = string.match(args.matchPattern); + if (!matchResult) return null; + var matchedString = matchResult[0]; + var parseResult = string.match(args.parsePattern); + if (!parseResult) return null; + var value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0]; + value = options.valueCallback ? options.valueCallback(value) : value; + var rest = string.slice(matchedString.length); + return { + value: value, + rest: rest + }; + }; +} + +var matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i; +var parseOrdinalNumberPattern = /\d+/i; +var matchEraPatterns = { + narrow: /^(b|a)/i, + abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i, + wide: /^(before christ|before common era|anno domini|common era)/i +}; +var parseEraPatterns = { + any: [/^b/i, /^(a|c)/i] +}; +var matchQuarterPatterns = { + narrow: /^[1234]/i, + abbreviated: /^q[1234]/i, + wide: /^[1234](th|st|nd|rd)? quarter/i +}; +var parseQuarterPatterns = { + any: [/1/i, /2/i, /3/i, /4/i] +}; +var matchMonthPatterns = { + narrow: /^[jfmasond]/i, + abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i, + wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i +}; +var parseMonthPatterns = { + narrow: [/^j/i, /^f/i, /^m/i, /^a/i, /^m/i, /^j/i, /^j/i, /^a/i, /^s/i, /^o/i, /^n/i, /^d/i], + any: [/^ja/i, /^f/i, /^mar/i, /^ap/i, /^may/i, /^jun/i, /^jul/i, /^au/i, /^s/i, /^o/i, /^n/i, /^d/i] +}; +var matchDayPatterns = { + narrow: /^[smtwf]/i, + short: /^(su|mo|tu|we|th|fr|sa)/i, + abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i, + wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i +}; +var parseDayPatterns = { + narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i], + any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i] +}; +var matchDayPeriodPatterns = { + narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i, + any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i +}; +var parseDayPeriodPatterns = { + any: { + am: /^a/i, + pm: /^p/i, + midnight: /^mi/i, + noon: /^no/i, + morning: /morning/i, + afternoon: /afternoon/i, + evening: /evening/i, + night: /night/i + } +}; +var match = { + ordinalNumber: buildMatchPatternFn({ + matchPattern: matchOrdinalNumberPattern, + parsePattern: parseOrdinalNumberPattern, + valueCallback: function valueCallback(value) { + return parseInt(value, 10); + } + }), + era: buildMatchFn({ + matchPatterns: matchEraPatterns, + defaultMatchWidth: 'wide', + parsePatterns: parseEraPatterns, + defaultParseWidth: 'any' + }), + quarter: buildMatchFn({ + matchPatterns: matchQuarterPatterns, + defaultMatchWidth: 'wide', + parsePatterns: parseQuarterPatterns, + defaultParseWidth: 'any', + valueCallback: function valueCallback(index) { + return index + 1; + } + }), + month: buildMatchFn({ + matchPatterns: matchMonthPatterns, + defaultMatchWidth: 'wide', + parsePatterns: parseMonthPatterns, + defaultParseWidth: 'any' + }), + day: buildMatchFn({ + matchPatterns: matchDayPatterns, + defaultMatchWidth: 'wide', + parsePatterns: parseDayPatterns, + defaultParseWidth: 'any' + }), + dayPeriod: buildMatchFn({ + matchPatterns: matchDayPeriodPatterns, + defaultMatchWidth: 'any', + parsePatterns: parseDayPeriodPatterns, + defaultParseWidth: 'any' + }) +}; +var match$1 = match; + +/** + * @type {Locale} + * @category Locales + * @summary English locale (United States). + * @language English + * @iso-639-2 eng + * @author Sasha Koss [@kossnocorp]{@link https://github.com/kossnocorp} + * @author Lesha Koss [@leshakoss]{@link https://github.com/leshakoss} + */ +var locale = { + code: 'en-US', + formatDistance: formatDistance$1, + formatLong: formatLong$1, + formatRelative: formatRelative$1, + localize: localize$1, + match: match$1, + options: { + weekStartsOn: 0 /* Sunday */, + firstWeekContainsDate: 1 + } +}; +var defaultLocale = locale; + +// - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token +// (one of the certain letters followed by `o`) +// - (\w)\1* matches any sequences of the same letter +// - '' matches two quote characters in a row +// - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('), +// except a single quote symbol, which ends the sequence. +// Two quote characters do not end the sequence. +// If there is no matching single quote +// then the sequence will continue until the end of the string. +// - . matches any single character unmatched by previous parts of the RegExps +var formattingTokensRegExp$1 = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g; + +// This RegExp catches symbols escaped by quotes, and also +// sequences of symbols P, p, and the combinations like `PPPPPPPppppp` +var longFormattingTokensRegExp$1 = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g; +var escapedStringRegExp$1 = /^'([^]*?)'?$/; +var doubleQuoteRegExp$1 = /''/g; +var unescapedLatinCharacterRegExp$1 = /[a-zA-Z]/; + +/** + * @name format + * @category Common Helpers + * @summary Format the date. + * + * @description + * Return the formatted date string in the given format. The result may vary by locale. + * + * > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries. + * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * + * The characters wrapped between two single quotes characters (') are escaped. + * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote. + * (see the last example) + * + * Format of the string is based on Unicode Technical Standard #35: + * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table + * with a few additions (see note 7 below the table). + * + * Accepted patterns: + * | Unit | Pattern | Result examples | Notes | + * |---------------------------------|---------|-----------------------------------|-------| + * | Era | G..GGG | AD, BC | | + * | | GGGG | Anno Domini, Before Christ | 2 | + * | | GGGGG | A, B | | + * | Calendar year | y | 44, 1, 1900, 2017 | 5 | + * | | yo | 44th, 1st, 0th, 17th | 5,7 | + * | | yy | 44, 01, 00, 17 | 5 | + * | | yyy | 044, 001, 1900, 2017 | 5 | + * | | yyyy | 0044, 0001, 1900, 2017 | 5 | + * | | yyyyy | ... | 3,5 | + * | Local week-numbering year | Y | 44, 1, 1900, 2017 | 5 | + * | | Yo | 44th, 1st, 1900th, 2017th | 5,7 | + * | | YY | 44, 01, 00, 17 | 5,8 | + * | | YYY | 044, 001, 1900, 2017 | 5 | + * | | YYYY | 0044, 0001, 1900, 2017 | 5,8 | + * | | YYYYY | ... | 3,5 | + * | ISO week-numbering year | R | -43, 0, 1, 1900, 2017 | 5,7 | + * | | RR | -43, 00, 01, 1900, 2017 | 5,7 | + * | | RRR | -043, 000, 001, 1900, 2017 | 5,7 | + * | | RRRR | -0043, 0000, 0001, 1900, 2017 | 5,7 | + * | | RRRRR | ... | 3,5,7 | + * | Extended year | u | -43, 0, 1, 1900, 2017 | 5 | + * | | uu | -43, 01, 1900, 2017 | 5 | + * | | uuu | -043, 001, 1900, 2017 | 5 | + * | | uuuu | -0043, 0001, 1900, 2017 | 5 | + * | | uuuuu | ... | 3,5 | + * | Quarter (formatting) | Q | 1, 2, 3, 4 | | + * | | Qo | 1st, 2nd, 3rd, 4th | 7 | + * | | QQ | 01, 02, 03, 04 | | + * | | QQQ | Q1, Q2, Q3, Q4 | | + * | | QQQQ | 1st quarter, 2nd quarter, ... | 2 | + * | | QQQQQ | 1, 2, 3, 4 | 4 | + * | Quarter (stand-alone) | q | 1, 2, 3, 4 | | + * | | qo | 1st, 2nd, 3rd, 4th | 7 | + * | | qq | 01, 02, 03, 04 | | + * | | qqq | Q1, Q2, Q3, Q4 | | + * | | qqqq | 1st quarter, 2nd quarter, ... | 2 | + * | | qqqqq | 1, 2, 3, 4 | 4 | + * | Month (formatting) | M | 1, 2, ..., 12 | | + * | | Mo | 1st, 2nd, ..., 12th | 7 | + * | | MM | 01, 02, ..., 12 | | + * | | MMM | Jan, Feb, ..., Dec | | + * | | MMMM | January, February, ..., December | 2 | + * | | MMMMM | J, F, ..., D | | + * | Month (stand-alone) | L | 1, 2, ..., 12 | | + * | | Lo | 1st, 2nd, ..., 12th | 7 | + * | | LL | 01, 02, ..., 12 | | + * | | LLL | Jan, Feb, ..., Dec | | + * | | LLLL | January, February, ..., December | 2 | + * | | LLLLL | J, F, ..., D | | + * | Local week of year | w | 1, 2, ..., 53 | | + * | | wo | 1st, 2nd, ..., 53th | 7 | + * | | ww | 01, 02, ..., 53 | | + * | ISO week of year | I | 1, 2, ..., 53 | 7 | + * | | Io | 1st, 2nd, ..., 53th | 7 | + * | | II | 01, 02, ..., 53 | 7 | + * | Day of month | d | 1, 2, ..., 31 | | + * | | do | 1st, 2nd, ..., 31st | 7 | + * | | dd | 01, 02, ..., 31 | | + * | Day of year | D | 1, 2, ..., 365, 366 | 9 | + * | | Do | 1st, 2nd, ..., 365th, 366th | 7 | + * | | DD | 01, 02, ..., 365, 366 | 9 | + * | | DDD | 001, 002, ..., 365, 366 | | + * | | DDDD | ... | 3 | + * | Day of week (formatting) | E..EEE | Mon, Tue, Wed, ..., Sun | | + * | | EEEE | Monday, Tuesday, ..., Sunday | 2 | + * | | EEEEE | M, T, W, T, F, S, S | | + * | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | | + * | ISO day of week (formatting) | i | 1, 2, 3, ..., 7 | 7 | + * | | io | 1st, 2nd, ..., 7th | 7 | + * | | ii | 01, 02, ..., 07 | 7 | + * | | iii | Mon, Tue, Wed, ..., Sun | 7 | + * | | iiii | Monday, Tuesday, ..., Sunday | 2,7 | + * | | iiiii | M, T, W, T, F, S, S | 7 | + * | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 7 | + * | Local day of week (formatting) | e | 2, 3, 4, ..., 1 | | + * | | eo | 2nd, 3rd, ..., 1st | 7 | + * | | ee | 02, 03, ..., 01 | | + * | | eee | Mon, Tue, Wed, ..., Sun | | + * | | eeee | Monday, Tuesday, ..., Sunday | 2 | + * | | eeeee | M, T, W, T, F, S, S | | + * | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | | + * | Local day of week (stand-alone) | c | 2, 3, 4, ..., 1 | | + * | | co | 2nd, 3rd, ..., 1st | 7 | + * | | cc | 02, 03, ..., 01 | | + * | | ccc | Mon, Tue, Wed, ..., Sun | | + * | | cccc | Monday, Tuesday, ..., Sunday | 2 | + * | | ccccc | M, T, W, T, F, S, S | | + * | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | | + * | AM, PM | a..aa | AM, PM | | + * | | aaa | am, pm | | + * | | aaaa | a.m., p.m. | 2 | + * | | aaaaa | a, p | | + * | AM, PM, noon, midnight | b..bb | AM, PM, noon, midnight | | + * | | bbb | am, pm, noon, midnight | | + * | | bbbb | a.m., p.m., noon, midnight | 2 | + * | | bbbbb | a, p, n, mi | | + * | Flexible day period | B..BBB | at night, in the morning, ... | | + * | | BBBB | at night, in the morning, ... | 2 | + * | | BBBBB | at night, in the morning, ... | | + * | Hour [1-12] | h | 1, 2, ..., 11, 12 | | + * | | ho | 1st, 2nd, ..., 11th, 12th | 7 | + * | | hh | 01, 02, ..., 11, 12 | | + * | Hour [0-23] | H | 0, 1, 2, ..., 23 | | + * | | Ho | 0th, 1st, 2nd, ..., 23rd | 7 | + * | | HH | 00, 01, 02, ..., 23 | | + * | Hour [0-11] | K | 1, 2, ..., 11, 0 | | + * | | Ko | 1st, 2nd, ..., 11th, 0th | 7 | + * | | KK | 01, 02, ..., 11, 00 | | + * | Hour [1-24] | k | 24, 1, 2, ..., 23 | | + * | | ko | 24th, 1st, 2nd, ..., 23rd | 7 | + * | | kk | 24, 01, 02, ..., 23 | | + * | Minute | m | 0, 1, ..., 59 | | + * | | mo | 0th, 1st, ..., 59th | 7 | + * | | mm | 00, 01, ..., 59 | | + * | Second | s | 0, 1, ..., 59 | | + * | | so | 0th, 1st, ..., 59th | 7 | + * | | ss | 00, 01, ..., 59 | | + * | Fraction of second | S | 0, 1, ..., 9 | | + * | | SS | 00, 01, ..., 99 | | + * | | SSS | 000, 001, ..., 999 | | + * | | SSSS | ... | 3 | + * | Timezone (ISO-8601 w/ Z) | X | -08, +0530, Z | | + * | | XX | -0800, +0530, Z | | + * | | XXX | -08:00, +05:30, Z | | + * | | XXXX | -0800, +0530, Z, +123456 | 2 | + * | | XXXXX | -08:00, +05:30, Z, +12:34:56 | | + * | Timezone (ISO-8601 w/o Z) | x | -08, +0530, +00 | | + * | | xx | -0800, +0530, +0000 | | + * | | xxx | -08:00, +05:30, +00:00 | 2 | + * | | xxxx | -0800, +0530, +0000, +123456 | | + * | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | | + * | Timezone (GMT) | O...OOO | GMT-8, GMT+5:30, GMT+0 | | + * | | OOOO | GMT-08:00, GMT+05:30, GMT+00:00 | 2 | + * | Timezone (specific non-locat.) | z...zzz | GMT-8, GMT+5:30, GMT+0 | 6 | + * | | zzzz | GMT-08:00, GMT+05:30, GMT+00:00 | 2,6 | + * | Seconds timestamp | t | 512969520 | 7 | + * | | tt | ... | 3,7 | + * | Milliseconds timestamp | T | 512969520900 | 7 | + * | | TT | ... | 3,7 | + * | Long localized date | P | 04/29/1453 | 7 | + * | | PP | Apr 29, 1453 | 7 | + * | | PPP | April 29th, 1453 | 7 | + * | | PPPP | Friday, April 29th, 1453 | 2,7 | + * | Long localized time | p | 12:00 AM | 7 | + * | | pp | 12:00:00 AM | 7 | + * | | ppp | 12:00:00 AM GMT+2 | 7 | + * | | pppp | 12:00:00 AM GMT+02:00 | 2,7 | + * | Combination of date and time | Pp | 04/29/1453, 12:00 AM | 7 | + * | | PPpp | Apr 29, 1453, 12:00:00 AM | 7 | + * | | PPPppp | April 29th, 1453 at ... | 7 | + * | | PPPPpppp| Friday, April 29th, 1453 at ... | 2,7 | + * Notes: + * 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale + * are the same as "stand-alone" units, but are different in some languages. + * "Formatting" units are declined according to the rules of the language + * in the context of a date. "Stand-alone" units are always nominative singular: + * + * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'` + * + * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'` + * + * 2. Any sequence of the identical letters is a pattern, unless it is escaped by + * the single quote characters (see below). + * If the sequence is longer than listed in table (e.g. `EEEEEEEEEEE`) + * the output will be the same as default pattern for this unit, usually + * the longest one (in case of ISO weekdays, `EEEE`). Default patterns for units + * are marked with "2" in the last column of the table. + * + * `format(new Date(2017, 10, 6), 'MMM') //=> 'Nov'` + * + * `format(new Date(2017, 10, 6), 'MMMM') //=> 'November'` + * + * `format(new Date(2017, 10, 6), 'MMMMM') //=> 'N'` + * + * `format(new Date(2017, 10, 6), 'MMMMMM') //=> 'November'` + * + * `format(new Date(2017, 10, 6), 'MMMMMMM') //=> 'November'` + * + * 3. Some patterns could be unlimited length (such as `yyyyyyyy`). + * The output will be padded with zeros to match the length of the pattern. + * + * `format(new Date(2017, 10, 6), 'yyyyyyyy') //=> '00002017'` + * + * 4. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales. + * These tokens represent the shortest form of the quarter. + * + * 5. The main difference between `y` and `u` patterns are B.C. years: + * + * | Year | `y` | `u` | + * |------|-----|-----| + * | AC 1 | 1 | 1 | + * | BC 1 | 1 | 0 | + * | BC 2 | 2 | -1 | + * + * Also `yy` always returns the last two digits of a year, + * while `uu` pads single digit years to 2 characters and returns other years unchanged: + * + * | Year | `yy` | `uu` | + * |------|------|------| + * | 1 | 01 | 01 | + * | 14 | 14 | 14 | + * | 376 | 76 | 376 | + * | 1453 | 53 | 1453 | + * + * The same difference is true for local and ISO week-numbering years (`Y` and `R`), + * except local week-numbering years are dependent on `options.weekStartsOn` + * and `options.firstWeekContainsDate` (compare [getISOWeekYear]{@link https://date-fns.org/docs/getISOWeekYear} + * and [getWeekYear]{@link https://date-fns.org/docs/getWeekYear}). + * + * 6. Specific non-location timezones are currently unavailable in `date-fns`, + * so right now these tokens fall back to GMT timezones. + * + * 7. These patterns are not in the Unicode Technical Standard #35: + * - `i`: ISO day of week + * - `I`: ISO week of year + * - `R`: ISO week-numbering year + * - `t`: seconds timestamp + * - `T`: milliseconds timestamp + * - `o`: ordinal number modifier + * - `P`: long localized date + * - `p`: long localized time + * + * 8. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years. + * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * + * 9. `D` and `DD` tokens represent days of the year but they are often confused with days of the month. + * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * + * @param {Date|Number} date - the original date + * @param {String} format - the string of tokens + * @param {Object} [options] - an object with options. + * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} + * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) + * @param {Number} [options.firstWeekContainsDate=1] - the day of January, which is + * @param {Boolean} [options.useAdditionalWeekYearTokens=false] - if true, allows usage of the week-numbering year tokens `YY` and `YYYY`; + * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @param {Boolean} [options.useAdditionalDayOfYearTokens=false] - if true, allows usage of the day of year tokens `D` and `DD`; + * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @returns {String} the formatted date string + * @throws {TypeError} 2 arguments required + * @throws {RangeError} `date` must not be Invalid Date + * @throws {RangeError} `options.locale` must contain `localize` property + * @throws {RangeError} `options.locale` must contain `formatLong` property + * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 + * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7 + * @throws {RangeError} use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} format string contains an unescaped latin alphabet character + * + * @example + * // Represent 11 February 2014 in middle-endian format: + * const result = format(new Date(2014, 1, 11), 'MM/dd/yyyy') + * //=> '02/11/2014' + * + * @example + * // Represent 2 July 2014 in Esperanto: + * import { eoLocale } from 'date-fns/locale/eo' + * const result = format(new Date(2014, 6, 2), "do 'de' MMMM yyyy", { + * locale: eoLocale + * }) + * //=> '2-a de julio 2014' + * + * @example + * // Escape string by single quote characters: + * const result = format(new Date(2014, 6, 2, 15), "h 'o''clock'") + * //=> "3 o'clock" + */ + +function format$1(dirtyDate, dirtyFormatStr, options) { + var _ref, _options$locale, _ref2, _ref3, _ref4, _options$firstWeekCon, _options$locale2, _options$locale2$opti, _defaultOptions$local, _defaultOptions$local2, _ref5, _ref6, _ref7, _options$weekStartsOn, _options$locale3, _options$locale3$opti, _defaultOptions$local3, _defaultOptions$local4; + requiredArgs(2, arguments); + var formatStr = String(dirtyFormatStr); + var defaultOptions = getDefaultOptions(); + var locale = (_ref = (_options$locale = options === null || options === void 0 ? void 0 : options.locale) !== null && _options$locale !== void 0 ? _options$locale : defaultOptions.locale) !== null && _ref !== void 0 ? _ref : defaultLocale; + var firstWeekContainsDate = toInteger((_ref2 = (_ref3 = (_ref4 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale2 = options.locale) === null || _options$locale2 === void 0 ? void 0 : (_options$locale2$opti = _options$locale2.options) === null || _options$locale2$opti === void 0 ? void 0 : _options$locale2$opti.firstWeekContainsDate) !== null && _ref4 !== void 0 ? _ref4 : defaultOptions.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : 1); + + // Test if weekStartsOn is between 1 and 7 _and_ is not NaN + if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) { + throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively'); + } + var weekStartsOn = toInteger((_ref5 = (_ref6 = (_ref7 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale3 = options.locale) === null || _options$locale3 === void 0 ? void 0 : (_options$locale3$opti = _options$locale3.options) === null || _options$locale3$opti === void 0 ? void 0 : _options$locale3$opti.weekStartsOn) !== null && _ref7 !== void 0 ? _ref7 : defaultOptions.weekStartsOn) !== null && _ref6 !== void 0 ? _ref6 : (_defaultOptions$local3 = defaultOptions.locale) === null || _defaultOptions$local3 === void 0 ? void 0 : (_defaultOptions$local4 = _defaultOptions$local3.options) === null || _defaultOptions$local4 === void 0 ? void 0 : _defaultOptions$local4.weekStartsOn) !== null && _ref5 !== void 0 ? _ref5 : 0); + + // Test if weekStartsOn is between 0 and 6 _and_ is not NaN + if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { + throw new RangeError('weekStartsOn must be between 0 and 6 inclusively'); + } + if (!locale.localize) { + throw new RangeError('locale must contain localize property'); + } + if (!locale.formatLong) { + throw new RangeError('locale must contain formatLong property'); + } + var originalDate = toDate(dirtyDate); + if (!isValid(originalDate)) { + throw new RangeError('Invalid time value'); + } + + // Convert the date in system timezone to the same date in UTC+00:00 timezone. + // This ensures that when UTC functions will be implemented, locales will be compatible with them. + // See an issue about UTC functions: https://github.com/date-fns/date-fns/issues/376 + var timezoneOffset = getTimezoneOffsetInMilliseconds(originalDate); + var utcDate = subMilliseconds(originalDate, timezoneOffset); + var formatterOptions = { + firstWeekContainsDate: firstWeekContainsDate, + weekStartsOn: weekStartsOn, + locale: locale, + _originalDate: originalDate + }; + var result = formatStr.match(longFormattingTokensRegExp$1).map(function (substring) { + var firstCharacter = substring[0]; + if (firstCharacter === 'p' || firstCharacter === 'P') { + var longFormatter = longFormatters$1[firstCharacter]; + return longFormatter(substring, locale.formatLong); + } + return substring; + }).join('').match(formattingTokensRegExp$1).map(function (substring) { + // Replace two single quote characters with one single quote character + if (substring === "''") { + return "'"; + } + var firstCharacter = substring[0]; + if (firstCharacter === "'") { + return cleanEscapedString$1(substring); + } + var formatter = formatters$1[firstCharacter]; + if (formatter) { + if (!(options !== null && options !== void 0 && options.useAdditionalWeekYearTokens) && isProtectedWeekYearToken(substring)) { + throwProtectedError(substring, dirtyFormatStr, String(dirtyDate)); + } + if (!(options !== null && options !== void 0 && options.useAdditionalDayOfYearTokens) && isProtectedDayOfYearToken(substring)) { + throwProtectedError(substring, dirtyFormatStr, String(dirtyDate)); + } + return formatter(utcDate, substring, locale.localize, formatterOptions); + } + if (firstCharacter.match(unescapedLatinCharacterRegExp$1)) { + throw new RangeError('Format string contains an unescaped latin alphabet character `' + firstCharacter + '`'); + } + return substring; + }).join(''); + return result; +} +function cleanEscapedString$1(input) { + var matched = input.match(escapedStringRegExp$1); + if (!matched) { + return input; + } + return matched[1].replace(doubleQuoteRegExp$1, "'"); +} + +var MILLISECONDS_IN_MINUTE = 60000; + +/** + * @name addMinutes + * @category Minute Helpers + * @summary Add the specified number of minutes to the given date. + * + * @description + * Add the specified number of minutes to the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of minutes to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the minutes added + * @throws {TypeError} 2 arguments required + * + * @example + * // Add 30 minutes to 10 July 2014 12:00:00: + * const result = addMinutes(new Date(2014, 6, 10, 12, 0), 30) + * //=> Thu Jul 10 2014 12:30:00 + */ +function addMinutes(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var amount = toInteger(dirtyAmount); + return addMilliseconds(dirtyDate, amount * MILLISECONDS_IN_MINUTE); +} + +var MILLISECONDS_IN_HOUR = 3600000; + +/** + * @name addHours + * @category Hour Helpers + * @summary Add the specified number of hours to the given date. + * + * @description + * Add the specified number of hours to the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of hours to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the hours added + * @throws {TypeError} 2 arguments required + * + * @example + * // Add 2 hours to 10 July 2014 23:00:00: + * const result = addHours(new Date(2014, 6, 10, 23, 0), 2) + * //=> Fri Jul 11 2014 01:00:00 + */ +function addHours(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var amount = toInteger(dirtyAmount); + return addMilliseconds(dirtyDate, amount * MILLISECONDS_IN_HOUR); +} + +/** + * @name addDays + * @category Day Helpers + * @summary Add the specified number of days to the given date. + * + * @description + * Add the specified number of days to the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of days to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} - the new date with the days added + * @throws {TypeError} - 2 arguments required + * + * @example + * // Add 10 days to 1 September 2014: + * const result = addDays(new Date(2014, 8, 1), 10) + * //=> Thu Sep 11 2014 00:00:00 + */ +function addDays(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var date = toDate(dirtyDate); + var amount = toInteger(dirtyAmount); + if (isNaN(amount)) { + return new Date(NaN); + } + if (!amount) { + // If 0 days, no-op to avoid changing times in the hour before end of DST + return date; + } + date.setDate(date.getDate() + amount); + return date; +} + +/** + * @name addWeeks + * @category Week Helpers + * @summary Add the specified number of weeks to the given date. + * + * @description + * Add the specified number of week to the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of weeks to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the weeks added + * @throws {TypeError} 2 arguments required + * + * @example + * // Add 4 weeks to 1 September 2014: + * const result = addWeeks(new Date(2014, 8, 1), 4) + * //=> Mon Sep 29 2014 00:00:00 + */ +function addWeeks(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var amount = toInteger(dirtyAmount); + var days = amount * 7; + return addDays(dirtyDate, days); +} + +/** + * @name addMonths + * @category Month Helpers + * @summary Add the specified number of months to the given date. + * + * @description + * Add the specified number of months to the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of months to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the months added + * @throws {TypeError} 2 arguments required + * + * @example + * // Add 5 months to 1 September 2014: + * const result = addMonths(new Date(2014, 8, 1), 5) + * //=> Sun Feb 01 2015 00:00:00 + */ +function addMonths(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var date = toDate(dirtyDate); + var amount = toInteger(dirtyAmount); + if (isNaN(amount)) { + return new Date(NaN); + } + if (!amount) { + // If 0 months, no-op to avoid changing times in the hour before end of DST + return date; + } + var dayOfMonth = date.getDate(); + + // The JS Date object supports date math by accepting out-of-bounds values for + // month, day, etc. For example, new Date(2020, 0, 0) returns 31 Dec 2019 and + // new Date(2020, 13, 1) returns 1 Feb 2021. This is *almost* the behavior we + // want except that dates will wrap around the end of a month, meaning that + // new Date(2020, 13, 31) will return 3 Mar 2021 not 28 Feb 2021 as desired. So + // we'll default to the end of the desired month by adding 1 to the desired + // month and using a date of 0 to back up one day to the end of the desired + // month. + var endOfDesiredMonth = new Date(date.getTime()); + endOfDesiredMonth.setMonth(date.getMonth() + amount + 1, 0); + var daysInMonth = endOfDesiredMonth.getDate(); + if (dayOfMonth >= daysInMonth) { + // If we're already at the end of the month, then this is the correct date + // and we're done. + return endOfDesiredMonth; + } else { + // Otherwise, we now know that setting the original day-of-month value won't + // cause an overflow, so set the desired day-of-month. Note that we can't + // just set the date of `endOfDesiredMonth` because that object may have had + // its time changed in the unusual case where where a DST transition was on + // the last day of the month and its local time was in the hour skipped or + // repeated next to a DST transition. So we use `date` instead which is + // guaranteed to still have the original time. + date.setFullYear(endOfDesiredMonth.getFullYear(), endOfDesiredMonth.getMonth(), dayOfMonth); + return date; + } +} + +/** + * @name addQuarters + * @category Quarter Helpers + * @summary Add the specified number of year quarters to the given date. + * + * @description + * Add the specified number of year quarters to the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of quarters to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the quarters added + * @throws {TypeError} 2 arguments required + * + * @example + * // Add 1 quarter to 1 September 2014: + * const result = addQuarters(new Date(2014, 8, 1), 1) + * //=> Mon Dec 01 2014 00:00:00 + */ +function addQuarters(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var amount = toInteger(dirtyAmount); + var months = amount * 3; + return addMonths(dirtyDate, months); +} + +/** + * @name addYears + * @category Year Helpers + * @summary Add the specified number of years to the given date. + * + * @description + * Add the specified number of years to the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of years to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the years added + * @throws {TypeError} 2 arguments required + * + * @example + * // Add 5 years to 1 September 2014: + * const result = addYears(new Date(2014, 8, 1), 5) + * //=> Sun Sep 01 2019 00:00:00 + */ +function addYears(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var amount = toInteger(dirtyAmount); + return addMonths(dirtyDate, amount * 12); +} + +/** + * @name subDays + * @category Day Helpers + * @summary Subtract the specified number of days from the given date. + * + * @description + * Subtract the specified number of days from the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of days to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the days subtracted + * @throws {TypeError} 2 arguments required + * + * @example + * // Subtract 10 days from 1 September 2014: + * const result = subDays(new Date(2014, 8, 1), 10) + * //=> Fri Aug 22 2014 00:00:00 + */ +function subDays(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var amount = toInteger(dirtyAmount); + return addDays(dirtyDate, -amount); +} + +/** + * @name subWeeks + * @category Week Helpers + * @summary Subtract the specified number of weeks from the given date. + * + * @description + * Subtract the specified number of weeks from the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of weeks to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the weeks subtracted + * @throws {TypeError} 2 arguments required + * + * @example + * // Subtract 4 weeks from 1 September 2014: + * const result = subWeeks(new Date(2014, 8, 1), 4) + * //=> Mon Aug 04 2014 00:00:00 + */ +function subWeeks(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var amount = toInteger(dirtyAmount); + return addWeeks(dirtyDate, -amount); +} + +/** + * @name subMonths + * @category Month Helpers + * @summary Subtract the specified number of months from the given date. + * + * @description + * Subtract the specified number of months from the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of months to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the months subtracted + * @throws {TypeError} 2 arguments required + * + * @example + * // Subtract 5 months from 1 February 2015: + * const result = subMonths(new Date(2015, 1, 1), 5) + * //=> Mon Sep 01 2014 00:00:00 + */ +function subMonths(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var amount = toInteger(dirtyAmount); + return addMonths(dirtyDate, -amount); +} + +/** + * @name subQuarters + * @category Quarter Helpers + * @summary Subtract the specified number of year quarters from the given date. + * + * @description + * Subtract the specified number of year quarters from the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of quarters to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the quarters subtracted + * @throws {TypeError} 2 arguments required + * + * @example + * // Subtract 3 quarters from 1 September 2014: + * const result = subQuarters(new Date(2014, 8, 1), 3) + * //=> Sun Dec 01 2013 00:00:00 + */ +function subQuarters(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var amount = toInteger(dirtyAmount); + return addQuarters(dirtyDate, -amount); +} + +/** + * @name subYears + * @category Year Helpers + * @summary Subtract the specified number of years from the given date. + * + * @description + * Subtract the specified number of years from the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} amount - the amount of years to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`. + * @returns {Date} the new date with the years subtracted + * @throws {TypeError} 2 arguments required + * + * @example + * // Subtract 5 years from 1 September 2014: + * const result = subYears(new Date(2014, 8, 1), 5) + * //=> Tue Sep 01 2009 00:00:00 + */ +function subYears(dirtyDate, dirtyAmount) { + requiredArgs(2, arguments); + var amount = toInteger(dirtyAmount); + return addYears(dirtyDate, -amount); +} + +/** + * @name getSeconds + * @category Second Helpers + * @summary Get the seconds of the given date. + * + * @description + * Get the seconds of the given date. + * + * @param {Date|Number} date - the given date + * @returns {Number} the seconds + * @throws {TypeError} 1 argument required + * + * @example + * // Get the seconds of 29 February 2012 11:45:05.123: + * const result = getSeconds(new Date(2012, 1, 29, 11, 45, 5, 123)) + * //=> 5 + */ +function getSeconds(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var seconds = date.getSeconds(); + return seconds; +} + +/** + * @name getMinutes + * @category Minute Helpers + * @summary Get the minutes of the given date. + * + * @description + * Get the minutes of the given date. + * + * @param {Date|Number} date - the given date + * @returns {Number} the minutes + * @throws {TypeError} 1 argument required + * + * @example + * // Get the minutes of 29 February 2012 11:45:05: + * const result = getMinutes(new Date(2012, 1, 29, 11, 45, 5)) + * //=> 45 + */ +function getMinutes(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var minutes = date.getMinutes(); + return minutes; +} + +/** + * @name getHours + * @category Hour Helpers + * @summary Get the hours of the given date. + * + * @description + * Get the hours of the given date. + * + * @param {Date|Number} date - the given date + * @returns {Number} the hours + * @throws {TypeError} 1 argument required + * + * @example + * // Get the hours of 29 February 2012 11:45:00: + * const result = getHours(new Date(2012, 1, 29, 11, 45)) + * //=> 11 + */ +function getHours(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var hours = date.getHours(); + return hours; +} + +/** + * @name getDay + * @category Weekday Helpers + * @summary Get the day of the week of the given date. + * + * @description + * Get the day of the week of the given date. + * + * @param {Date|Number} date - the given date + * @returns {0|1|2|3|4|5|6} the day of week, 0 represents Sunday + * @throws {TypeError} 1 argument required + * + * @example + * // Which day of the week is 29 February 2012? + * const result = getDay(new Date(2012, 1, 29)) + * //=> 3 + */ +function getDay(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var day = date.getDay(); + return day; +} + +/** + * @name getDate + * @category Day Helpers + * @summary Get the day of the month of the given date. + * + * @description + * Get the day of the month of the given date. + * + * @param {Date|Number} date - the given date + * @returns {Number} the day of month + * @throws {TypeError} 1 argument required + * + * @example + * // Which day of the month is 29 February 2012? + * const result = getDate(new Date(2012, 1, 29)) + * //=> 29 + */ +function getDate(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var dayOfMonth = date.getDate(); + return dayOfMonth; +} + +/** + * @name startOfWeek + * @category Week Helpers + * @summary Return the start of a week for the given date. + * + * @description + * Return the start of a week for the given date. + * The result will be in the local timezone. + * + * @param {Date|Number} date - the original date + * @param {Object} [options] - an object with options. + * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} + * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) + * @returns {Date} the start of a week + * @throws {TypeError} 1 argument required + * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 + * + * @example + * // The start of a week for 2 September 2014 11:55:00: + * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0)) + * //=> Sun Aug 31 2014 00:00:00 + * + * @example + * // If the week starts on Monday, the start of the week for 2 September 2014 11:55:00: + * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 }) + * //=> Mon Sep 01 2014 00:00:00 + */ +function startOfWeek(dirtyDate, options) { + var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; + requiredArgs(1, arguments); + var defaultOptions = getDefaultOptions(); + var weekStartsOn = toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0); + + // Test if weekStartsOn is between 0 and 6 _and_ is not NaN + if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { + throw new RangeError('weekStartsOn must be between 0 and 6 inclusively'); + } + var date = toDate(dirtyDate); + var day = date.getDay(); + var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; + date.setDate(date.getDate() - diff); + date.setHours(0, 0, 0, 0); + return date; +} + +/** + * @name startOfISOWeek + * @category ISO Week Helpers + * @summary Return the start of an ISO week for the given date. + * + * @description + * Return the start of an ISO week for the given date. + * The result will be in the local timezone. + * + * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date + * + * @param {Date|Number} date - the original date + * @returns {Date} the start of an ISO week + * @throws {TypeError} 1 argument required + * + * @example + * // The start of an ISO week for 2 September 2014 11:55:00: + * const result = startOfISOWeek(new Date(2014, 8, 2, 11, 55, 0)) + * //=> Mon Sep 01 2014 00:00:00 + */ +function startOfISOWeek(dirtyDate) { + requiredArgs(1, arguments); + return startOfWeek(dirtyDate, { + weekStartsOn: 1 + }); +} + +/** + * @name getISOWeekYear + * @category ISO Week-Numbering Year Helpers + * @summary Get the ISO week-numbering year of the given date. + * + * @description + * Get the ISO week-numbering year of the given date, + * which always starts 3 days before the year's first Thursday. + * + * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date + * + * @param {Date|Number} date - the given date + * @returns {Number} the ISO week-numbering year + * @throws {TypeError} 1 argument required + * + * @example + * // Which ISO-week numbering year is 2 January 2005? + * const result = getISOWeekYear(new Date(2005, 0, 2)) + * //=> 2004 + */ +function getISOWeekYear(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var year = date.getFullYear(); + var fourthOfJanuaryOfNextYear = new Date(0); + fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4); + fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0); + var startOfNextYear = startOfISOWeek(fourthOfJanuaryOfNextYear); + var fourthOfJanuaryOfThisYear = new Date(0); + fourthOfJanuaryOfThisYear.setFullYear(year, 0, 4); + fourthOfJanuaryOfThisYear.setHours(0, 0, 0, 0); + var startOfThisYear = startOfISOWeek(fourthOfJanuaryOfThisYear); + if (date.getTime() >= startOfNextYear.getTime()) { + return year + 1; + } else if (date.getTime() >= startOfThisYear.getTime()) { + return year; + } else { + return year - 1; + } +} + +/** + * @name startOfISOWeekYear + * @category ISO Week-Numbering Year Helpers + * @summary Return the start of an ISO week-numbering year for the given date. + * + * @description + * Return the start of an ISO week-numbering year, + * which always starts 3 days before the year's first Thursday. + * The result will be in the local timezone. + * + * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date + * + * @param {Date|Number} date - the original date + * @returns {Date} the start of an ISO week-numbering year + * @throws {TypeError} 1 argument required + * + * @example + * // The start of an ISO week-numbering year for 2 July 2005: + * const result = startOfISOWeekYear(new Date(2005, 6, 2)) + * //=> Mon Jan 03 2005 00:00:00 + */ +function startOfISOWeekYear(dirtyDate) { + requiredArgs(1, arguments); + var year = getISOWeekYear(dirtyDate); + var fourthOfJanuary = new Date(0); + fourthOfJanuary.setFullYear(year, 0, 4); + fourthOfJanuary.setHours(0, 0, 0, 0); + var date = startOfISOWeek(fourthOfJanuary); + return date; +} + +var MILLISECONDS_IN_WEEK = 604800000; + +/** + * @name getISOWeek + * @category ISO Week Helpers + * @summary Get the ISO week of the given date. + * + * @description + * Get the ISO week of the given date. + * + * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date + * + * @param {Date|Number} date - the given date + * @returns {Number} the ISO week + * @throws {TypeError} 1 argument required + * + * @example + * // Which week of the ISO-week numbering year is 2 January 2005? + * const result = getISOWeek(new Date(2005, 0, 2)) + * //=> 53 + */ +function getISOWeek(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var diff = startOfISOWeek(date).getTime() - startOfISOWeekYear(date).getTime(); + + // Round the number of days to the nearest integer + // because the number of milliseconds in a week is not constant + // (e.g. it's different in the week of the daylight saving time clock shift) + return Math.round(diff / MILLISECONDS_IN_WEEK) + 1; +} + +/** + * @name getMonth + * @category Month Helpers + * @summary Get the month of the given date. + * + * @description + * Get the month of the given date. + * + * @param {Date|Number} date - the given date + * @returns {Number} the month + * @throws {TypeError} 1 argument required + * + * @example + * // Which month is 29 February 2012? + * const result = getMonth(new Date(2012, 1, 29)) + * //=> 1 + */ +function getMonth(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var month = date.getMonth(); + return month; +} + +/** + * @name getQuarter + * @category Quarter Helpers + * @summary Get the year quarter of the given date. + * + * @description + * Get the year quarter of the given date. + * + * @param {Date|Number} date - the given date + * @returns {Number} the quarter + * @throws {TypeError} 1 argument required + * + * @example + * // Which quarter is 2 July 2014? + * const result = getQuarter(new Date(2014, 6, 2)) + * //=> 3 + */ +function getQuarter(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var quarter = Math.floor(date.getMonth() / 3) + 1; + return quarter; +} + +/** + * @name getYear + * @category Year Helpers + * @summary Get the year of the given date. + * + * @description + * Get the year of the given date. + * + * @param {Date|Number} date - the given date + * @returns {Number} the year + * @throws {TypeError} 1 argument required + * + * @example + * // Which year is 2 July 2014? + * const result = getYear(new Date(2014, 6, 2)) + * //=> 2014 + */ +function getYear(dirtyDate) { + requiredArgs(1, arguments); + return toDate(dirtyDate).getFullYear(); +} + +/** + * @name getTime + * @category Timestamp Helpers + * @summary Get the milliseconds timestamp of the given date. + * + * @description + * Get the milliseconds timestamp of the given date. + * + * @param {Date|Number} date - the given date + * @returns {Number} the timestamp + * @throws {TypeError} 1 argument required + * + * @example + * // Get the timestamp of 29 February 2012 11:45:05.123: + * const result = getTime(new Date(2012, 1, 29, 11, 45, 5, 123)) + * //=> 1330515905123 + */ +function getTime(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var timestamp = date.getTime(); + return timestamp; +} + +/** + * @name setSeconds + * @category Second Helpers + * @summary Set the seconds to the given date. + * + * @description + * Set the seconds to the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} seconds - the seconds of the new date + * @returns {Date} the new date with the seconds set + * @throws {TypeError} 2 arguments required + * + * @example + * // Set 45 seconds to 1 September 2014 11:30:40: + * const result = setSeconds(new Date(2014, 8, 1, 11, 30, 40), 45) + * //=> Mon Sep 01 2014 11:30:45 + */ +function setSeconds(dirtyDate, dirtySeconds) { + requiredArgs(2, arguments); + var date = toDate(dirtyDate); + var seconds = toInteger(dirtySeconds); + date.setSeconds(seconds); + return date; +} + +/** + * @name setMinutes + * @category Minute Helpers + * @summary Set the minutes to the given date. + * + * @description + * Set the minutes to the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} minutes - the minutes of the new date + * @returns {Date} the new date with the minutes set + * @throws {TypeError} 2 arguments required + * + * @example + * // Set 45 minutes to 1 September 2014 11:30:40: + * const result = setMinutes(new Date(2014, 8, 1, 11, 30, 40), 45) + * //=> Mon Sep 01 2014 11:45:40 + */ +function setMinutes(dirtyDate, dirtyMinutes) { + requiredArgs(2, arguments); + var date = toDate(dirtyDate); + var minutes = toInteger(dirtyMinutes); + date.setMinutes(minutes); + return date; +} + +/** + * @name setHours + * @category Hour Helpers + * @summary Set the hours to the given date. + * + * @description + * Set the hours to the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} hours - the hours of the new date + * @returns {Date} the new date with the hours set + * @throws {TypeError} 2 arguments required + * + * @example + * // Set 4 hours to 1 September 2014 11:30:00: + * const result = setHours(new Date(2014, 8, 1, 11, 30), 4) + * //=> Mon Sep 01 2014 04:30:00 + */ +function setHours(dirtyDate, dirtyHours) { + requiredArgs(2, arguments); + var date = toDate(dirtyDate); + var hours = toInteger(dirtyHours); + date.setHours(hours); + return date; +} + +/** + * @name getDaysInMonth + * @category Month Helpers + * @summary Get the number of days in a month of the given date. + * + * @description + * Get the number of days in a month of the given date. + * + * @param {Date|Number} date - the given date + * @returns {Number} the number of days in a month + * @throws {TypeError} 1 argument required + * + * @example + * // How many days are in February 2000? + * const result = getDaysInMonth(new Date(2000, 1)) + * //=> 29 + */ +function getDaysInMonth(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var year = date.getFullYear(); + var monthIndex = date.getMonth(); + var lastDayOfMonth = new Date(0); + lastDayOfMonth.setFullYear(year, monthIndex + 1, 0); + lastDayOfMonth.setHours(0, 0, 0, 0); + return lastDayOfMonth.getDate(); +} + +/** + * @name setMonth + * @category Month Helpers + * @summary Set the month to the given date. + * + * @description + * Set the month to the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} month - the month of the new date + * @returns {Date} the new date with the month set + * @throws {TypeError} 2 arguments required + * + * @example + * // Set February to 1 September 2014: + * const result = setMonth(new Date(2014, 8, 1), 1) + * //=> Sat Feb 01 2014 00:00:00 + */ +function setMonth(dirtyDate, dirtyMonth) { + requiredArgs(2, arguments); + var date = toDate(dirtyDate); + var month = toInteger(dirtyMonth); + var year = date.getFullYear(); + var day = date.getDate(); + var dateWithDesiredMonth = new Date(0); + dateWithDesiredMonth.setFullYear(year, month, 15); + dateWithDesiredMonth.setHours(0, 0, 0, 0); + var daysInMonth = getDaysInMonth(dateWithDesiredMonth); + // Set the last day of the new month + // if the original date was the last day of the longer month + date.setMonth(month, Math.min(day, daysInMonth)); + return date; +} + +/** + * @name setQuarter + * @category Quarter Helpers + * @summary Set the year quarter to the given date. + * + * @description + * Set the year quarter to the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} quarter - the quarter of the new date + * @returns {Date} the new date with the quarter set + * @throws {TypeError} 2 arguments required + * + * @example + * // Set the 2nd quarter to 2 July 2014: + * const result = setQuarter(new Date(2014, 6, 2), 2) + * //=> Wed Apr 02 2014 00:00:00 + */ +function setQuarter(dirtyDate, dirtyQuarter) { + requiredArgs(2, arguments); + var date = toDate(dirtyDate); + var quarter = toInteger(dirtyQuarter); + var oldQuarter = Math.floor(date.getMonth() / 3) + 1; + var diff = quarter - oldQuarter; + return setMonth(date, date.getMonth() + diff * 3); +} + +/** + * @name setYear + * @category Year Helpers + * @summary Set the year to the given date. + * + * @description + * Set the year to the given date. + * + * @param {Date|Number} date - the date to be changed + * @param {Number} year - the year of the new date + * @returns {Date} the new date with the year set + * @throws {TypeError} 2 arguments required + * + * @example + * // Set year 2013 to 1 September 2014: + * const result = setYear(new Date(2014, 8, 1), 2013) + * //=> Sun Sep 01 2013 00:00:00 + */ +function setYear(dirtyDate, dirtyYear) { + requiredArgs(2, arguments); + var date = toDate(dirtyDate); + var year = toInteger(dirtyYear); + + // Check if date is Invalid Date because Date.prototype.setFullYear ignores the value of Invalid Date + if (isNaN(date.getTime())) { + return new Date(NaN); + } + date.setFullYear(year); + return date; +} + +/** + * @name min + * @category Common Helpers + * @summary Returns the earliest of the given dates. + * + * @description + * Returns the earliest of the given dates. + * + * @param {Date[]|Number[]} datesArray - the dates to compare + * @returns {Date} - the earliest of the dates + * @throws {TypeError} 1 argument required + * + * @example + * // Which of these dates is the earliest? + * const result = min([ + * new Date(1989, 6, 10), + * new Date(1987, 1, 11), + * new Date(1995, 6, 2), + * new Date(1990, 0, 1) + * ]) + * //=> Wed Feb 11 1987 00:00:00 + */ +function min$1(dirtyDatesArray) { + requiredArgs(1, arguments); + var datesArray; + // `dirtyDatesArray` is Array, Set or Map, or object with custom `forEach` method + if (dirtyDatesArray && typeof dirtyDatesArray.forEach === 'function') { + datesArray = dirtyDatesArray; + // If `dirtyDatesArray` is Array-like Object, convert to Array. + } else if (_typeof$1(dirtyDatesArray) === 'object' && dirtyDatesArray !== null) { + datesArray = Array.prototype.slice.call(dirtyDatesArray); + } else { + // `dirtyDatesArray` is non-iterable, return Invalid Date + return new Date(NaN); + } + var result; + datesArray.forEach(function (dirtyDate) { + var currentDate = toDate(dirtyDate); + if (result === undefined || result > currentDate || isNaN(currentDate.getDate())) { + result = currentDate; + } + }); + return result || new Date(NaN); +} + +/** + * @name max + * @category Common Helpers + * @summary Return the latest of the given dates. + * + * @description + * Return the latest of the given dates. + * + * @param {Date[]|Number[]} datesArray - the dates to compare + * @returns {Date} the latest of the dates + * @throws {TypeError} 1 argument required + * + * @example + * // Which of these dates is the latest? + * const result = max([ + * new Date(1989, 6, 10), + * new Date(1987, 1, 11), + * new Date(1995, 6, 2), + * new Date(1990, 0, 1) + * ]) + * //=> Sun Jul 02 1995 00:00:00 + */ +function max$1(dirtyDatesArray) { + requiredArgs(1, arguments); + var datesArray; + // `dirtyDatesArray` is Array, Set or Map, or object with custom `forEach` method + if (dirtyDatesArray && typeof dirtyDatesArray.forEach === 'function') { + datesArray = dirtyDatesArray; + + // If `dirtyDatesArray` is Array-like Object, convert to Array. + } else if (_typeof$1(dirtyDatesArray) === 'object' && dirtyDatesArray !== null) { + datesArray = Array.prototype.slice.call(dirtyDatesArray); + } else { + // `dirtyDatesArray` is non-iterable, return Invalid Date + return new Date(NaN); + } + var result; + datesArray.forEach(function (dirtyDate) { + var currentDate = toDate(dirtyDate); + if (result === undefined || result < currentDate || isNaN(Number(currentDate))) { + result = currentDate; + } + }); + return result || new Date(NaN); +} + +/** + * @name startOfDay + * @category Day Helpers + * @summary Return the start of a day for the given date. + * + * @description + * Return the start of a day for the given date. + * The result will be in the local timezone. + * + * @param {Date|Number} date - the original date + * @returns {Date} the start of a day + * @throws {TypeError} 1 argument required + * + * @example + * // The start of a day for 2 September 2014 11:55:00: + * const result = startOfDay(new Date(2014, 8, 2, 11, 55, 0)) + * //=> Tue Sep 02 2014 00:00:00 + */ +function startOfDay(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + date.setHours(0, 0, 0, 0); + return date; +} + +var MILLISECONDS_IN_DAY = 86400000; + +/** + * @name differenceInCalendarDays + * @category Day Helpers + * @summary Get the number of calendar days between the given dates. + * + * @description + * Get the number of calendar days between the given dates. This means that the times are removed + * from the dates and then the difference in days is calculated. + * + * @param {Date|Number} dateLeft - the later date + * @param {Date|Number} dateRight - the earlier date + * @returns {Number} the number of calendar days + * @throws {TypeError} 2 arguments required + * + * @example + * // How many calendar days are between + * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00? + * const result = differenceInCalendarDays( + * new Date(2012, 6, 2, 0, 0), + * new Date(2011, 6, 2, 23, 0) + * ) + * //=> 366 + * // How many calendar days are between + * // 2 July 2011 23:59:00 and 3 July 2011 00:01:00? + * const result = differenceInCalendarDays( + * new Date(2011, 6, 3, 0, 1), + * new Date(2011, 6, 2, 23, 59) + * ) + * //=> 1 + */ +function differenceInCalendarDays(dirtyDateLeft, dirtyDateRight) { + requiredArgs(2, arguments); + var startOfDayLeft = startOfDay(dirtyDateLeft); + var startOfDayRight = startOfDay(dirtyDateRight); + var timestampLeft = startOfDayLeft.getTime() - getTimezoneOffsetInMilliseconds(startOfDayLeft); + var timestampRight = startOfDayRight.getTime() - getTimezoneOffsetInMilliseconds(startOfDayRight); + + // Round the number of days to the nearest integer + // because the number of milliseconds in a day is not constant + // (e.g. it's different in the day of the daylight saving time clock shift) + return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_DAY); +} + +/** + * @name differenceInCalendarMonths + * @category Month Helpers + * @summary Get the number of calendar months between the given dates. + * + * @description + * Get the number of calendar months between the given dates. + * + * @param {Date|Number} dateLeft - the later date + * @param {Date|Number} dateRight - the earlier date + * @returns {Number} the number of calendar months + * @throws {TypeError} 2 arguments required + * + * @example + * // How many calendar months are between 31 January 2014 and 1 September 2014? + * const result = differenceInCalendarMonths( + * new Date(2014, 8, 1), + * new Date(2014, 0, 31) + * ) + * //=> 8 + */ +function differenceInCalendarMonths(dirtyDateLeft, dirtyDateRight) { + requiredArgs(2, arguments); + var dateLeft = toDate(dirtyDateLeft); + var dateRight = toDate(dirtyDateRight); + var yearDiff = dateLeft.getFullYear() - dateRight.getFullYear(); + var monthDiff = dateLeft.getMonth() - dateRight.getMonth(); + return yearDiff * 12 + monthDiff; +} + +/** + * @name differenceInCalendarYears + * @category Year Helpers + * @summary Get the number of calendar years between the given dates. + * + * @description + * Get the number of calendar years between the given dates. + * + * @param {Date|Number} dateLeft - the later date + * @param {Date|Number} dateRight - the earlier date + * @returns {Number} the number of calendar years + * @throws {TypeError} 2 arguments required + * + * @example + * // How many calendar years are between 31 December 2013 and 11 February 2015? + * const result = differenceInCalendarYears( + * new Date(2015, 1, 11), + * new Date(2013, 11, 31) + * ) + * //=> 2 + */ +function differenceInCalendarYears(dirtyDateLeft, dirtyDateRight) { + requiredArgs(2, arguments); + var dateLeft = toDate(dirtyDateLeft); + var dateRight = toDate(dirtyDateRight); + return dateLeft.getFullYear() - dateRight.getFullYear(); +} + +/** + * @name startOfMonth + * @category Month Helpers + * @summary Return the start of a month for the given date. + * + * @description + * Return the start of a month for the given date. + * The result will be in the local timezone. + * + * @param {Date|Number} date - the original date + * @returns {Date} the start of a month + * @throws {TypeError} 1 argument required + * + * @example + * // The start of a month for 2 September 2014 11:55:00: + * const result = startOfMonth(new Date(2014, 8, 2, 11, 55, 0)) + * //=> Mon Sep 01 2014 00:00:00 + */ +function startOfMonth(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + date.setDate(1); + date.setHours(0, 0, 0, 0); + return date; +} + +/** + * @name startOfQuarter + * @category Quarter Helpers + * @summary Return the start of a year quarter for the given date. + * + * @description + * Return the start of a year quarter for the given date. + * The result will be in the local timezone. + * + * @param {Date|Number} date - the original date + * @returns {Date} the start of a quarter + * @throws {TypeError} 1 argument required + * + * @example + * // The start of a quarter for 2 September 2014 11:55:00: + * const result = startOfQuarter(new Date(2014, 8, 2, 11, 55, 0)) + * //=> Tue Jul 01 2014 00:00:00 + */ +function startOfQuarter(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var currentMonth = date.getMonth(); + var month = currentMonth - currentMonth % 3; + date.setMonth(month, 1); + date.setHours(0, 0, 0, 0); + return date; +} + +/** + * @name startOfYear + * @category Year Helpers + * @summary Return the start of a year for the given date. + * + * @description + * Return the start of a year for the given date. + * The result will be in the local timezone. + * + * @param {Date|Number} date - the original date + * @returns {Date} the start of a year + * @throws {TypeError} 1 argument required + * + * @example + * // The start of a year for 2 September 2014 11:55:00: + * const result = startOfYear(new Date(2014, 8, 2, 11, 55, 00)) + * //=> Wed Jan 01 2014 00:00:00 + */ +function startOfYear(dirtyDate) { + requiredArgs(1, arguments); + var cleanDate = toDate(dirtyDate); + var date = new Date(0); + date.setFullYear(cleanDate.getFullYear(), 0, 1); + date.setHours(0, 0, 0, 0); + return date; +} + +/** + * @name endOfDay + * @category Day Helpers + * @summary Return the end of a day for the given date. + * + * @description + * Return the end of a day for the given date. + * The result will be in the local timezone. + * + * @param {Date|Number} date - the original date + * @returns {Date} the end of a day + * @throws {TypeError} 1 argument required + * + * @example + * // The end of a day for 2 September 2014 11:55:00: + * const result = endOfDay(new Date(2014, 8, 2, 11, 55, 0)) + * //=> Tue Sep 02 2014 23:59:59.999 + */ +function endOfDay(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + date.setHours(23, 59, 59, 999); + return date; +} + +/** + * @name endOfMonth + * @category Month Helpers + * @summary Return the end of a month for the given date. + * + * @description + * Return the end of a month for the given date. + * The result will be in the local timezone. + * + * @param {Date|Number} date - the original date + * @returns {Date} the end of a month + * @throws {TypeError} 1 argument required + * + * @example + * // The end of a month for 2 September 2014 11:55:00: + * const result = endOfMonth(new Date(2014, 8, 2, 11, 55, 0)) + * //=> Tue Sep 30 2014 23:59:59.999 + */ +function endOfMonth(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var month = date.getMonth(); + date.setFullYear(date.getFullYear(), month + 1, 0); + date.setHours(23, 59, 59, 999); + return date; +} + +/** + * @name endOfYear + * @category Year Helpers + * @summary Return the end of a year for the given date. + * + * @description + * Return the end of a year for the given date. + * The result will be in the local timezone. + * + * @param {Date|Number} date - the original date + * @returns {Date} the end of a year + * @throws {TypeError} 1 argument required + * + * @example + * // The end of a year for 2 September 2014 11:55:00: + * const result = endOfYear(new Date(2014, 8, 2, 11, 55, 00)) + * //=> Wed Dec 31 2014 23:59:59.999 + */ +function endOfYear(dirtyDate) { + requiredArgs(1, arguments); + var date = toDate(dirtyDate); + var year = date.getFullYear(); + date.setFullYear(year + 1, 0, 0); + date.setHours(23, 59, 59, 999); + return date; +} + +/** + * @name isEqual + * @category Common Helpers + * @summary Are the given dates equal? + * + * @description + * Are the given dates equal? + * + * @param {Date|Number} dateLeft - the first date to compare + * @param {Date|Number} dateRight - the second date to compare + * @returns {Boolean} the dates are equal + * @throws {TypeError} 2 arguments required + * + * @example + * // Are 2 July 2014 06:30:45.000 and 2 July 2014 06:30:45.500 equal? + * const result = isEqual( + * new Date(2014, 6, 2, 6, 30, 45, 0), + * new Date(2014, 6, 2, 6, 30, 45, 500) + * ) + * //=> false + */ +function isEqual$1(dirtyLeftDate, dirtyRightDate) { + requiredArgs(2, arguments); + var dateLeft = toDate(dirtyLeftDate); + var dateRight = toDate(dirtyRightDate); + return dateLeft.getTime() === dateRight.getTime(); +} + +/** + * @name isSameDay + * @category Day Helpers + * @summary Are the given dates in the same day (and year and month)? + * + * @description + * Are the given dates in the same day (and year and month)? + * + * @param {Date|Number} dateLeft - the first date to check + * @param {Date|Number} dateRight - the second date to check + * @returns {Boolean} the dates are in the same day (and year and month) + * @throws {TypeError} 2 arguments required + * + * @example + * // Are 4 September 06:00:00 and 4 September 18:00:00 in the same day? + * const result = isSameDay(new Date(2014, 8, 4, 6, 0), new Date(2014, 8, 4, 18, 0)) + * //=> true + * + * @example + * // Are 4 September and 4 October in the same day? + * const result = isSameDay(new Date(2014, 8, 4), new Date(2014, 9, 4)) + * //=> false + * + * @example + * // Are 4 September, 2014 and 4 September, 2015 in the same day? + * const result = isSameDay(new Date(2014, 8, 4), new Date(2015, 8, 4)) + * //=> false + */ +function isSameDay(dirtyDateLeft, dirtyDateRight) { + requiredArgs(2, arguments); + var dateLeftStartOfDay = startOfDay(dirtyDateLeft); + var dateRightStartOfDay = startOfDay(dirtyDateRight); + return dateLeftStartOfDay.getTime() === dateRightStartOfDay.getTime(); +} + +/** + * @name isSameMonth + * @category Month Helpers + * @summary Are the given dates in the same month (and year)? + * + * @description + * Are the given dates in the same month (and year)? + * + * @param {Date|Number} dateLeft - the first date to check + * @param {Date|Number} dateRight - the second date to check + * @returns {Boolean} the dates are in the same month (and year) + * @throws {TypeError} 2 arguments required + * + * @example + * // Are 2 September 2014 and 25 September 2014 in the same month? + * const result = isSameMonth(new Date(2014, 8, 2), new Date(2014, 8, 25)) + * //=> true + * + * @example + * // Are 2 September 2014 and 25 September 2015 in the same month? + * const result = isSameMonth(new Date(2014, 8, 2), new Date(2015, 8, 25)) + * //=> false + */ +function isSameMonth(dirtyDateLeft, dirtyDateRight) { + requiredArgs(2, arguments); + var dateLeft = toDate(dirtyDateLeft); + var dateRight = toDate(dirtyDateRight); + return dateLeft.getFullYear() === dateRight.getFullYear() && dateLeft.getMonth() === dateRight.getMonth(); +} + +/** + * @name isSameYear + * @category Year Helpers + * @summary Are the given dates in the same year? + * + * @description + * Are the given dates in the same year? + * + * @param {Date|Number} dateLeft - the first date to check + * @param {Date|Number} dateRight - the second date to check + * @returns {Boolean} the dates are in the same year + * @throws {TypeError} 2 arguments required + * + * @example + * // Are 2 September 2014 and 25 September 2014 in the same year? + * const result = isSameYear(new Date(2014, 8, 2), new Date(2014, 8, 25)) + * //=> true + */ +function isSameYear(dirtyDateLeft, dirtyDateRight) { + requiredArgs(2, arguments); + var dateLeft = toDate(dirtyDateLeft); + var dateRight = toDate(dirtyDateRight); + return dateLeft.getFullYear() === dateRight.getFullYear(); +} + +/** + * @name isSameQuarter + * @category Quarter Helpers + * @summary Are the given dates in the same quarter (and year)? + * + * @description + * Are the given dates in the same quarter (and year)? + * + * @param {Date|Number} dateLeft - the first date to check + * @param {Date|Number} dateRight - the second date to check + * @returns {Boolean} the dates are in the same quarter (and year) + * @throws {TypeError} 2 arguments required + * + * @example + * // Are 1 January 2014 and 8 March 2014 in the same quarter? + * const result = isSameQuarter(new Date(2014, 0, 1), new Date(2014, 2, 8)) + * //=> true + * + * @example + * // Are 1 January 2014 and 1 January 2015 in the same quarter? + * const result = isSameQuarter(new Date(2014, 0, 1), new Date(2015, 0, 1)) + * //=> false + */ +function isSameQuarter(dirtyDateLeft, dirtyDateRight) { + requiredArgs(2, arguments); + var dateLeftStartOfQuarter = startOfQuarter(dirtyDateLeft); + var dateRightStartOfQuarter = startOfQuarter(dirtyDateRight); + return dateLeftStartOfQuarter.getTime() === dateRightStartOfQuarter.getTime(); +} + +/** + * @name isAfter + * @category Common Helpers + * @summary Is the first date after the second one? + * + * @description + * Is the first date after the second one? + * + * @param {Date|Number} date - the date that should be after the other one to return true + * @param {Date|Number} dateToCompare - the date to compare with + * @returns {Boolean} the first date is after the second date + * @throws {TypeError} 2 arguments required + * + * @example + * // Is 10 July 1989 after 11 February 1987? + * const result = isAfter(new Date(1989, 6, 10), new Date(1987, 1, 11)) + * //=> true + */ +function isAfter(dirtyDate, dirtyDateToCompare) { + requiredArgs(2, arguments); + var date = toDate(dirtyDate); + var dateToCompare = toDate(dirtyDateToCompare); + return date.getTime() > dateToCompare.getTime(); +} + +/** + * @name isBefore + * @category Common Helpers + * @summary Is the first date before the second one? + * + * @description + * Is the first date before the second one? + * + * @param {Date|Number} date - the date that should be before the other one to return true + * @param {Date|Number} dateToCompare - the date to compare with + * @returns {Boolean} the first date is before the second date + * @throws {TypeError} 2 arguments required + * + * @example + * // Is 10 July 1989 before 11 February 1987? + * const result = isBefore(new Date(1989, 6, 10), new Date(1987, 1, 11)) + * //=> false + */ +function isBefore(dirtyDate, dirtyDateToCompare) { + requiredArgs(2, arguments); + var date = toDate(dirtyDate); + var dateToCompare = toDate(dirtyDateToCompare); + return date.getTime() < dateToCompare.getTime(); +} + +/** + * @name isWithinInterval + * @category Interval Helpers + * @summary Is the given date within the interval? + * + * @description + * Is the given date within the interval? (Including start and end.) + * + * @param {Date|Number} date - the date to check + * @param {Interval} interval - the interval to check + * @returns {Boolean} the date is within the interval + * @throws {TypeError} 2 arguments required + * @throws {RangeError} The start of an interval cannot be after its end + * @throws {RangeError} Date in interval cannot be `Invalid Date` + * + * @example + * // For the date within the interval: + * isWithinInterval(new Date(2014, 0, 3), { + * start: new Date(2014, 0, 1), + * end: new Date(2014, 0, 7) + * }) + * //=> true + * + * @example + * // For the date outside of the interval: + * isWithinInterval(new Date(2014, 0, 10), { + * start: new Date(2014, 0, 1), + * end: new Date(2014, 0, 7) + * }) + * //=> false + * + * @example + * // For date equal to interval start: + * isWithinInterval(date, { start, end: date }) // => true + * + * @example + * // For date equal to interval end: + * isWithinInterval(date, { start: date, end }) // => true + */ +function isWithinInterval(dirtyDate, interval) { + requiredArgs(2, arguments); + var time = toDate(dirtyDate).getTime(); + var startTime = toDate(interval.start).getTime(); + var endTime = toDate(interval.end).getTime(); + + // Throw an exception if start date is after end date or if any date is `Invalid Date` + if (!(startTime <= endTime)) { + throw new RangeError('Invalid interval'); + } + return time >= startTime && time <= endTime; +} + +function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) len = arr.length; + for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; + return arr2; +} + +function _unsupportedIterableToArray(o, minLen) { + if (!o) return; + if (typeof o === "string") return _arrayLikeToArray(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); +} + +function _createForOfIteratorHelper(o, allowArrayLike) { + var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; + if (!it) { + if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { + if (it) o = it; + var i = 0; + var F = function F() {}; + return { + s: F, + n: function n() { + if (i >= o.length) return { + done: true + }; + return { + done: false, + value: o[i++] + }; + }, + e: function e(_e) { + throw _e; + }, + f: F + }; + } + throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + var normalCompletion = true, + didErr = false, + err; + return { + s: function s() { + it = it.call(o); + }, + n: function n() { + var step = it.next(); + normalCompletion = step.done; + return step; + }, + e: function e(_e2) { + didErr = true; + err = _e2; + }, + f: function f() { + try { + if (!normalCompletion && it["return"] != null) it["return"](); + } finally { + if (didErr) throw err; + } + } + }; +} + +function assign(target, object) { + if (target == null) { + throw new TypeError('assign requires that input parameter not be null or undefined'); + } + for (var property in object) { + if (Object.prototype.hasOwnProperty.call(object, property)) { + target[property] = object[property]; + } + } + return target; +} + +function _assertThisInitialized$2(self) { + if (self === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return self; +} + +function _setPrototypeOf$2(o, p) { + _setPrototypeOf$2 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + return _setPrototypeOf$2(o, p); +} + +function _inherits$1(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function"); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + writable: true, + configurable: true + } + }); + Object.defineProperty(subClass, "prototype", { + writable: false + }); + if (superClass) _setPrototypeOf$2(subClass, superClass); +} + +function _getPrototypeOf$1(o) { + _getPrototypeOf$1 = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + return _getPrototypeOf$1(o); +} + +function _isNativeReflectConstruct$1() { + if (typeof Reflect === "undefined" || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === "function") return true; + try { + Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); + return true; + } catch (e) { + return false; + } +} + +function _possibleConstructorReturn$1(self, call) { + if (call && (_typeof$1(call) === "object" || typeof call === "function")) { + return call; + } else if (call !== void 0) { + throw new TypeError("Derived constructors may only return object or undefined"); + } + return _assertThisInitialized$2(self); +} + +function _createSuper$1(Derived) { + var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); + return function _createSuperInternal() { + var Super = _getPrototypeOf$1(Derived), + result; + if (hasNativeReflectConstruct) { + var NewTarget = _getPrototypeOf$1(this).constructor; + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + return _possibleConstructorReturn$1(this, result); + }; +} + +function _classCallCheck$1(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } +} + +function _toPrimitive(input, hint) { + if (_typeof$1(input) !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== undefined) { + var res = prim.call(input, hint || "default"); + if (_typeof$1(res) !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); +} + +function _toPropertyKey(arg) { + var key = _toPrimitive(arg, "string"); + return _typeof$1(key) === "symbol" ? key : String(key); +} + +function _defineProperties$1(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); + } +} +function _createClass$1(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties$1(Constructor.prototype, protoProps); + if (staticProps) _defineProperties$1(Constructor, staticProps); + Object.defineProperty(Constructor, "prototype", { + writable: false + }); + return Constructor; +} + +function _defineProperty$1(obj, key, value) { + key = _toPropertyKey(key); + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + return obj; +} + +var TIMEZONE_UNIT_PRIORITY = 10; +var Setter = /*#__PURE__*/function () { + function Setter() { + _classCallCheck$1(this, Setter); + _defineProperty$1(this, "priority", void 0); + _defineProperty$1(this, "subPriority", 0); + } + _createClass$1(Setter, [{ + key: "validate", + value: function validate(_utcDate, _options) { + return true; + } + }]); + return Setter; +}(); +var ValueSetter = /*#__PURE__*/function (_Setter) { + _inherits$1(ValueSetter, _Setter); + var _super = _createSuper$1(ValueSetter); + function ValueSetter(value, validateValue, setValue, priority, subPriority) { + var _this; + _classCallCheck$1(this, ValueSetter); + _this = _super.call(this); + _this.value = value; + _this.validateValue = validateValue; + _this.setValue = setValue; + _this.priority = priority; + if (subPriority) { + _this.subPriority = subPriority; + } + return _this; + } + _createClass$1(ValueSetter, [{ + key: "validate", + value: function validate(utcDate, options) { + return this.validateValue(utcDate, this.value, options); + } + }, { + key: "set", + value: function set(utcDate, flags, options) { + return this.setValue(utcDate, flags, this.value, options); + } + }]); + return ValueSetter; +}(Setter); +var DateToSystemTimezoneSetter = /*#__PURE__*/function (_Setter2) { + _inherits$1(DateToSystemTimezoneSetter, _Setter2); + var _super2 = _createSuper$1(DateToSystemTimezoneSetter); + function DateToSystemTimezoneSetter() { + var _this2; + _classCallCheck$1(this, DateToSystemTimezoneSetter); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this2 = _super2.call.apply(_super2, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this2), "priority", TIMEZONE_UNIT_PRIORITY); + _defineProperty$1(_assertThisInitialized$2(_this2), "subPriority", -1); + return _this2; + } + _createClass$1(DateToSystemTimezoneSetter, [{ + key: "set", + value: function set(date, flags) { + if (flags.timestampIsSet) { + return date; + } + var convertedDate = new Date(0); + convertedDate.setFullYear(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()); + convertedDate.setHours(date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds()); + return convertedDate; + } + }]); + return DateToSystemTimezoneSetter; +}(Setter); + +var Parser = /*#__PURE__*/function () { + function Parser() { + _classCallCheck$1(this, Parser); + _defineProperty$1(this, "incompatibleTokens", void 0); + _defineProperty$1(this, "priority", void 0); + _defineProperty$1(this, "subPriority", void 0); + } + _createClass$1(Parser, [{ + key: "run", + value: function run(dateString, token, match, options) { + var result = this.parse(dateString, token, match, options); + if (!result) { + return null; + } + return { + setter: new ValueSetter(result.value, this.validate, this.set, this.priority, this.subPriority), + rest: result.rest + }; + } + }, { + key: "validate", + value: function validate(_utcDate, _value, _options) { + return true; + } + }]); + return Parser; +}(); + +var EraParser = /*#__PURE__*/function (_Parser) { + _inherits$1(EraParser, _Parser); + var _super = _createSuper$1(EraParser); + function EraParser() { + var _this; + _classCallCheck$1(this, EraParser); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this), "priority", 140); + _defineProperty$1(_assertThisInitialized$2(_this), "incompatibleTokens", ['R', 'u', 't', 'T']); + return _this; + } + _createClass$1(EraParser, [{ + key: "parse", + value: function parse(dateString, token, match) { + switch (token) { + // AD, BC + case 'G': + case 'GG': + case 'GGG': + return match.era(dateString, { + width: 'abbreviated' + }) || match.era(dateString, { + width: 'narrow' + }); + // A, B + case 'GGGGG': + return match.era(dateString, { + width: 'narrow' + }); + // Anno Domini, Before Christ + case 'GGGG': + default: + return match.era(dateString, { + width: 'wide' + }) || match.era(dateString, { + width: 'abbreviated' + }) || match.era(dateString, { + width: 'narrow' + }); + } + } + }, { + key: "set", + value: function set(date, flags, value) { + flags.era = value; + date.setUTCFullYear(value, 0, 1); + date.setUTCHours(0, 0, 0, 0); + return date; + } + }]); + return EraParser; +}(Parser); + +/** + * Days in 1 week. + * + * @name daysInWeek + * @constant + * @type {number} + * @default + */ + +/** + * Milliseconds in 1 minute + * + * @name millisecondsInMinute + * @constant + * @type {number} + * @default + */ +var millisecondsInMinute = 60000; + +/** + * Milliseconds in 1 hour + * + * @name millisecondsInHour + * @constant + * @type {number} + * @default + */ +var millisecondsInHour = 3600000; + +/** + * Milliseconds in 1 second + * + * @name millisecondsInSecond + * @constant + * @type {number} + * @default + */ +var millisecondsInSecond = 1000; + +var numericPatterns = { + month: /^(1[0-2]|0?\d)/, + // 0 to 12 + date: /^(3[0-1]|[0-2]?\d)/, + // 0 to 31 + dayOfYear: /^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/, + // 0 to 366 + week: /^(5[0-3]|[0-4]?\d)/, + // 0 to 53 + hour23h: /^(2[0-3]|[0-1]?\d)/, + // 0 to 23 + hour24h: /^(2[0-4]|[0-1]?\d)/, + // 0 to 24 + hour11h: /^(1[0-1]|0?\d)/, + // 0 to 11 + hour12h: /^(1[0-2]|0?\d)/, + // 0 to 12 + minute: /^[0-5]?\d/, + // 0 to 59 + second: /^[0-5]?\d/, + // 0 to 59 + + singleDigit: /^\d/, + // 0 to 9 + twoDigits: /^\d{1,2}/, + // 0 to 99 + threeDigits: /^\d{1,3}/, + // 0 to 999 + fourDigits: /^\d{1,4}/, + // 0 to 9999 + + anyDigitsSigned: /^-?\d+/, + singleDigitSigned: /^-?\d/, + // 0 to 9, -0 to -9 + twoDigitsSigned: /^-?\d{1,2}/, + // 0 to 99, -0 to -99 + threeDigitsSigned: /^-?\d{1,3}/, + // 0 to 999, -0 to -999 + fourDigitsSigned: /^-?\d{1,4}/ // 0 to 9999, -0 to -9999 +}; + +var timezonePatterns = { + basicOptionalMinutes: /^([+-])(\d{2})(\d{2})?|Z/, + basic: /^([+-])(\d{2})(\d{2})|Z/, + basicOptionalSeconds: /^([+-])(\d{2})(\d{2})((\d{2}))?|Z/, + extended: /^([+-])(\d{2}):(\d{2})|Z/, + extendedOptionalSeconds: /^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/ +}; + +function mapValue(parseFnResult, mapFn) { + if (!parseFnResult) { + return parseFnResult; + } + return { + value: mapFn(parseFnResult.value), + rest: parseFnResult.rest + }; +} +function parseNumericPattern(pattern, dateString) { + var matchResult = dateString.match(pattern); + if (!matchResult) { + return null; + } + return { + value: parseInt(matchResult[0], 10), + rest: dateString.slice(matchResult[0].length) + }; +} +function parseTimezonePattern(pattern, dateString) { + var matchResult = dateString.match(pattern); + if (!matchResult) { + return null; + } + + // Input is 'Z' + if (matchResult[0] === 'Z') { + return { + value: 0, + rest: dateString.slice(1) + }; + } + var sign = matchResult[1] === '+' ? 1 : -1; + var hours = matchResult[2] ? parseInt(matchResult[2], 10) : 0; + var minutes = matchResult[3] ? parseInt(matchResult[3], 10) : 0; + var seconds = matchResult[5] ? parseInt(matchResult[5], 10) : 0; + return { + value: sign * (hours * millisecondsInHour + minutes * millisecondsInMinute + seconds * millisecondsInSecond), + rest: dateString.slice(matchResult[0].length) + }; +} +function parseAnyDigitsSigned(dateString) { + return parseNumericPattern(numericPatterns.anyDigitsSigned, dateString); +} +function parseNDigits(n, dateString) { + switch (n) { + case 1: + return parseNumericPattern(numericPatterns.singleDigit, dateString); + case 2: + return parseNumericPattern(numericPatterns.twoDigits, dateString); + case 3: + return parseNumericPattern(numericPatterns.threeDigits, dateString); + case 4: + return parseNumericPattern(numericPatterns.fourDigits, dateString); + default: + return parseNumericPattern(new RegExp('^\\d{1,' + n + '}'), dateString); + } +} +function parseNDigitsSigned(n, dateString) { + switch (n) { + case 1: + return parseNumericPattern(numericPatterns.singleDigitSigned, dateString); + case 2: + return parseNumericPattern(numericPatterns.twoDigitsSigned, dateString); + case 3: + return parseNumericPattern(numericPatterns.threeDigitsSigned, dateString); + case 4: + return parseNumericPattern(numericPatterns.fourDigitsSigned, dateString); + default: + return parseNumericPattern(new RegExp('^-?\\d{1,' + n + '}'), dateString); + } +} +function dayPeriodEnumToHours(dayPeriod) { + switch (dayPeriod) { + case 'morning': + return 4; + case 'evening': + return 17; + case 'pm': + case 'noon': + case 'afternoon': + return 12; + case 'am': + case 'midnight': + case 'night': + default: + return 0; + } +} +function normalizeTwoDigitYear(twoDigitYear, currentYear) { + var isCommonEra = currentYear > 0; + // Absolute number of the current year: + // 1 -> 1 AC + // 0 -> 1 BC + // -1 -> 2 BC + var absCurrentYear = isCommonEra ? currentYear : 1 - currentYear; + var result; + if (absCurrentYear <= 50) { + result = twoDigitYear || 100; + } else { + var rangeEnd = absCurrentYear + 50; + var rangeEndCentury = Math.floor(rangeEnd / 100) * 100; + var isPreviousCentury = twoDigitYear >= rangeEnd % 100; + result = twoDigitYear + rangeEndCentury - (isPreviousCentury ? 100 : 0); + } + return isCommonEra ? result : 1 - result; +} +function isLeapYearIndex$1(year) { + return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0; +} + +// From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns +// | Year | y | yy | yyy | yyyy | yyyyy | +// |----------|-------|----|-------|-------|-------| +// | AD 1 | 1 | 01 | 001 | 0001 | 00001 | +// | AD 12 | 12 | 12 | 012 | 0012 | 00012 | +// | AD 123 | 123 | 23 | 123 | 0123 | 00123 | +// | AD 1234 | 1234 | 34 | 1234 | 1234 | 01234 | +// | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 | +var YearParser = /*#__PURE__*/function (_Parser) { + _inherits$1(YearParser, _Parser); + var _super = _createSuper$1(YearParser); + function YearParser() { + var _this; + _classCallCheck$1(this, YearParser); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this), "priority", 130); + _defineProperty$1(_assertThisInitialized$2(_this), "incompatibleTokens", ['Y', 'R', 'u', 'w', 'I', 'i', 'e', 'c', 't', 'T']); + return _this; + } + _createClass$1(YearParser, [{ + key: "parse", + value: function parse(dateString, token, match) { + var valueCallback = function valueCallback(year) { + return { + year: year, + isTwoDigitYear: token === 'yy' + }; + }; + switch (token) { + case 'y': + return mapValue(parseNDigits(4, dateString), valueCallback); + case 'yo': + return mapValue(match.ordinalNumber(dateString, { + unit: 'year' + }), valueCallback); + default: + return mapValue(parseNDigits(token.length, dateString), valueCallback); + } + } + }, { + key: "validate", + value: function validate(_date, value) { + return value.isTwoDigitYear || value.year > 0; + } + }, { + key: "set", + value: function set(date, flags, value) { + var currentYear = date.getUTCFullYear(); + if (value.isTwoDigitYear) { + var normalizedTwoDigitYear = normalizeTwoDigitYear(value.year, currentYear); + date.setUTCFullYear(normalizedTwoDigitYear, 0, 1); + date.setUTCHours(0, 0, 0, 0); + return date; + } + var year = !('era' in flags) || flags.era === 1 ? value.year : 1 - value.year; + date.setUTCFullYear(year, 0, 1); + date.setUTCHours(0, 0, 0, 0); + return date; + } + }]); + return YearParser; +}(Parser); + +// Local week-numbering year +var LocalWeekYearParser = /*#__PURE__*/function (_Parser) { + _inherits$1(LocalWeekYearParser, _Parser); + var _super = _createSuper$1(LocalWeekYearParser); + function LocalWeekYearParser() { + var _this; + _classCallCheck$1(this, LocalWeekYearParser); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this), "priority", 130); + _defineProperty$1(_assertThisInitialized$2(_this), "incompatibleTokens", ['y', 'R', 'u', 'Q', 'q', 'M', 'L', 'I', 'd', 'D', 'i', 't', 'T']); + return _this; + } + _createClass$1(LocalWeekYearParser, [{ + key: "parse", + value: function parse(dateString, token, match) { + var valueCallback = function valueCallback(year) { + return { + year: year, + isTwoDigitYear: token === 'YY' + }; + }; + switch (token) { + case 'Y': + return mapValue(parseNDigits(4, dateString), valueCallback); + case 'Yo': + return mapValue(match.ordinalNumber(dateString, { + unit: 'year' + }), valueCallback); + default: + return mapValue(parseNDigits(token.length, dateString), valueCallback); + } + } + }, { + key: "validate", + value: function validate(_date, value) { + return value.isTwoDigitYear || value.year > 0; + } + }, { + key: "set", + value: function set(date, flags, value, options) { + var currentYear = getUTCWeekYear(date, options); + if (value.isTwoDigitYear) { + var normalizedTwoDigitYear = normalizeTwoDigitYear(value.year, currentYear); + date.setUTCFullYear(normalizedTwoDigitYear, 0, options.firstWeekContainsDate); + date.setUTCHours(0, 0, 0, 0); + return startOfUTCWeek(date, options); + } + var year = !('era' in flags) || flags.era === 1 ? value.year : 1 - value.year; + date.setUTCFullYear(year, 0, options.firstWeekContainsDate); + date.setUTCHours(0, 0, 0, 0); + return startOfUTCWeek(date, options); + } + }]); + return LocalWeekYearParser; +}(Parser); + +var ISOWeekYearParser = /*#__PURE__*/function (_Parser) { + _inherits$1(ISOWeekYearParser, _Parser); + var _super = _createSuper$1(ISOWeekYearParser); + function ISOWeekYearParser() { + var _this; + _classCallCheck$1(this, ISOWeekYearParser); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this), "priority", 130); + _defineProperty$1(_assertThisInitialized$2(_this), "incompatibleTokens", ['G', 'y', 'Y', 'u', 'Q', 'q', 'M', 'L', 'w', 'd', 'D', 'e', 'c', 't', 'T']); + return _this; + } + _createClass$1(ISOWeekYearParser, [{ + key: "parse", + value: function parse(dateString, token) { + if (token === 'R') { + return parseNDigitsSigned(4, dateString); + } + return parseNDigitsSigned(token.length, dateString); + } + }, { + key: "set", + value: function set(_date, _flags, value) { + var firstWeekOfYear = new Date(0); + firstWeekOfYear.setUTCFullYear(value, 0, 4); + firstWeekOfYear.setUTCHours(0, 0, 0, 0); + return startOfUTCISOWeek(firstWeekOfYear); + } + }]); + return ISOWeekYearParser; +}(Parser); + +var ExtendedYearParser = /*#__PURE__*/function (_Parser) { + _inherits$1(ExtendedYearParser, _Parser); + var _super = _createSuper$1(ExtendedYearParser); + function ExtendedYearParser() { + var _this; + _classCallCheck$1(this, ExtendedYearParser); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this), "priority", 130); + _defineProperty$1(_assertThisInitialized$2(_this), "incompatibleTokens", ['G', 'y', 'Y', 'R', 'w', 'I', 'i', 'e', 'c', 't', 'T']); + return _this; + } + _createClass$1(ExtendedYearParser, [{ + key: "parse", + value: function parse(dateString, token) { + if (token === 'u') { + return parseNDigitsSigned(4, dateString); + } + return parseNDigitsSigned(token.length, dateString); + } + }, { + key: "set", + value: function set(date, _flags, value) { + date.setUTCFullYear(value, 0, 1); + date.setUTCHours(0, 0, 0, 0); + return date; + } + }]); + return ExtendedYearParser; +}(Parser); + +var QuarterParser = /*#__PURE__*/function (_Parser) { + _inherits$1(QuarterParser, _Parser); + var _super = _createSuper$1(QuarterParser); + function QuarterParser() { + var _this; + _classCallCheck$1(this, QuarterParser); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this), "priority", 120); + _defineProperty$1(_assertThisInitialized$2(_this), "incompatibleTokens", ['Y', 'R', 'q', 'M', 'L', 'w', 'I', 'd', 'D', 'i', 'e', 'c', 't', 'T']); + return _this; + } + _createClass$1(QuarterParser, [{ + key: "parse", + value: function parse(dateString, token, match) { + switch (token) { + // 1, 2, 3, 4 + case 'Q': + case 'QQ': + // 01, 02, 03, 04 + return parseNDigits(token.length, dateString); + // 1st, 2nd, 3rd, 4th + case 'Qo': + return match.ordinalNumber(dateString, { + unit: 'quarter' + }); + // Q1, Q2, Q3, Q4 + case 'QQQ': + return match.quarter(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.quarter(dateString, { + width: 'narrow', + context: 'formatting' + }); + // 1, 2, 3, 4 (narrow quarter; could be not numerical) + case 'QQQQQ': + return match.quarter(dateString, { + width: 'narrow', + context: 'formatting' + }); + // 1st quarter, 2nd quarter, ... + case 'QQQQ': + default: + return match.quarter(dateString, { + width: 'wide', + context: 'formatting' + }) || match.quarter(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.quarter(dateString, { + width: 'narrow', + context: 'formatting' + }); + } + } + }, { + key: "validate", + value: function validate(_date, value) { + return value >= 1 && value <= 4; + } + }, { + key: "set", + value: function set(date, _flags, value) { + date.setUTCMonth((value - 1) * 3, 1); + date.setUTCHours(0, 0, 0, 0); + return date; + } + }]); + return QuarterParser; +}(Parser); + +var StandAloneQuarterParser = /*#__PURE__*/function (_Parser) { + _inherits$1(StandAloneQuarterParser, _Parser); + var _super = _createSuper$1(StandAloneQuarterParser); + function StandAloneQuarterParser() { + var _this; + _classCallCheck$1(this, StandAloneQuarterParser); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this), "priority", 120); + _defineProperty$1(_assertThisInitialized$2(_this), "incompatibleTokens", ['Y', 'R', 'Q', 'M', 'L', 'w', 'I', 'd', 'D', 'i', 'e', 'c', 't', 'T']); + return _this; + } + _createClass$1(StandAloneQuarterParser, [{ + key: "parse", + value: function parse(dateString, token, match) { + switch (token) { + // 1, 2, 3, 4 + case 'q': + case 'qq': + // 01, 02, 03, 04 + return parseNDigits(token.length, dateString); + // 1st, 2nd, 3rd, 4th + case 'qo': + return match.ordinalNumber(dateString, { + unit: 'quarter' + }); + // Q1, Q2, Q3, Q4 + case 'qqq': + return match.quarter(dateString, { + width: 'abbreviated', + context: 'standalone' + }) || match.quarter(dateString, { + width: 'narrow', + context: 'standalone' + }); + // 1, 2, 3, 4 (narrow quarter; could be not numerical) + case 'qqqqq': + return match.quarter(dateString, { + width: 'narrow', + context: 'standalone' + }); + // 1st quarter, 2nd quarter, ... + case 'qqqq': + default: + return match.quarter(dateString, { + width: 'wide', + context: 'standalone' + }) || match.quarter(dateString, { + width: 'abbreviated', + context: 'standalone' + }) || match.quarter(dateString, { + width: 'narrow', + context: 'standalone' + }); + } + } + }, { + key: "validate", + value: function validate(_date, value) { + return value >= 1 && value <= 4; + } + }, { + key: "set", + value: function set(date, _flags, value) { + date.setUTCMonth((value - 1) * 3, 1); + date.setUTCHours(0, 0, 0, 0); + return date; + } + }]); + return StandAloneQuarterParser; +}(Parser); + +var MonthParser = /*#__PURE__*/function (_Parser) { + _inherits$1(MonthParser, _Parser); + var _super = _createSuper$1(MonthParser); + function MonthParser() { + var _this; + _classCallCheck$1(this, MonthParser); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this), "incompatibleTokens", ['Y', 'R', 'q', 'Q', 'L', 'w', 'I', 'D', 'i', 'e', 'c', 't', 'T']); + _defineProperty$1(_assertThisInitialized$2(_this), "priority", 110); + return _this; + } + _createClass$1(MonthParser, [{ + key: "parse", + value: function parse(dateString, token, match) { + var valueCallback = function valueCallback(value) { + return value - 1; + }; + switch (token) { + // 1, 2, ..., 12 + case 'M': + return mapValue(parseNumericPattern(numericPatterns.month, dateString), valueCallback); + // 01, 02, ..., 12 + case 'MM': + return mapValue(parseNDigits(2, dateString), valueCallback); + // 1st, 2nd, ..., 12th + case 'Mo': + return mapValue(match.ordinalNumber(dateString, { + unit: 'month' + }), valueCallback); + // Jan, Feb, ..., Dec + case 'MMM': + return match.month(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.month(dateString, { + width: 'narrow', + context: 'formatting' + }); + // J, F, ..., D + case 'MMMMM': + return match.month(dateString, { + width: 'narrow', + context: 'formatting' + }); + // January, February, ..., December + case 'MMMM': + default: + return match.month(dateString, { + width: 'wide', + context: 'formatting' + }) || match.month(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.month(dateString, { + width: 'narrow', + context: 'formatting' + }); + } + } + }, { + key: "validate", + value: function validate(_date, value) { + return value >= 0 && value <= 11; + } + }, { + key: "set", + value: function set(date, _flags, value) { + date.setUTCMonth(value, 1); + date.setUTCHours(0, 0, 0, 0); + return date; + } + }]); + return MonthParser; +}(Parser); + +var StandAloneMonthParser = /*#__PURE__*/function (_Parser) { + _inherits$1(StandAloneMonthParser, _Parser); + var _super = _createSuper$1(StandAloneMonthParser); + function StandAloneMonthParser() { + var _this; + _classCallCheck$1(this, StandAloneMonthParser); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this), "priority", 110); + _defineProperty$1(_assertThisInitialized$2(_this), "incompatibleTokens", ['Y', 'R', 'q', 'Q', 'M', 'w', 'I', 'D', 'i', 'e', 'c', 't', 'T']); + return _this; + } + _createClass$1(StandAloneMonthParser, [{ + key: "parse", + value: function parse(dateString, token, match) { + var valueCallback = function valueCallback(value) { + return value - 1; + }; + switch (token) { + // 1, 2, ..., 12 + case 'L': + return mapValue(parseNumericPattern(numericPatterns.month, dateString), valueCallback); + // 01, 02, ..., 12 + case 'LL': + return mapValue(parseNDigits(2, dateString), valueCallback); + // 1st, 2nd, ..., 12th + case 'Lo': + return mapValue(match.ordinalNumber(dateString, { + unit: 'month' + }), valueCallback); + // Jan, Feb, ..., Dec + case 'LLL': + return match.month(dateString, { + width: 'abbreviated', + context: 'standalone' + }) || match.month(dateString, { + width: 'narrow', + context: 'standalone' + }); + // J, F, ..., D + case 'LLLLL': + return match.month(dateString, { + width: 'narrow', + context: 'standalone' + }); + // January, February, ..., December + case 'LLLL': + default: + return match.month(dateString, { + width: 'wide', + context: 'standalone' + }) || match.month(dateString, { + width: 'abbreviated', + context: 'standalone' + }) || match.month(dateString, { + width: 'narrow', + context: 'standalone' + }); + } + } + }, { + key: "validate", + value: function validate(_date, value) { + return value >= 0 && value <= 11; + } + }, { + key: "set", + value: function set(date, _flags, value) { + date.setUTCMonth(value, 1); + date.setUTCHours(0, 0, 0, 0); + return date; + } + }]); + return StandAloneMonthParser; +}(Parser); + +function setUTCWeek(dirtyDate, dirtyWeek, options) { + requiredArgs(2, arguments); + var date = toDate(dirtyDate); + var week = toInteger(dirtyWeek); + var diff = getUTCWeek(date, options) - week; + date.setUTCDate(date.getUTCDate() - diff * 7); + return date; +} + +var LocalWeekParser = /*#__PURE__*/function (_Parser) { + _inherits$1(LocalWeekParser, _Parser); + var _super = _createSuper$1(LocalWeekParser); + function LocalWeekParser() { + var _this; + _classCallCheck$1(this, LocalWeekParser); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this), "priority", 100); + _defineProperty$1(_assertThisInitialized$2(_this), "incompatibleTokens", ['y', 'R', 'u', 'q', 'Q', 'M', 'L', 'I', 'd', 'D', 'i', 't', 'T']); + return _this; + } + _createClass$1(LocalWeekParser, [{ + key: "parse", + value: function parse(dateString, token, match) { + switch (token) { + case 'w': + return parseNumericPattern(numericPatterns.week, dateString); + case 'wo': + return match.ordinalNumber(dateString, { + unit: 'week' + }); + default: + return parseNDigits(token.length, dateString); + } + } + }, { + key: "validate", + value: function validate(_date, value) { + return value >= 1 && value <= 53; + } + }, { + key: "set", + value: function set(date, _flags, value, options) { + return startOfUTCWeek(setUTCWeek(date, value, options), options); + } + }]); + return LocalWeekParser; +}(Parser); + +function setUTCISOWeek(dirtyDate, dirtyISOWeek) { + requiredArgs(2, arguments); + var date = toDate(dirtyDate); + var isoWeek = toInteger(dirtyISOWeek); + var diff = getUTCISOWeek(date) - isoWeek; + date.setUTCDate(date.getUTCDate() - diff * 7); + return date; +} + +var ISOWeekParser = /*#__PURE__*/function (_Parser) { + _inherits$1(ISOWeekParser, _Parser); + var _super = _createSuper$1(ISOWeekParser); + function ISOWeekParser() { + var _this; + _classCallCheck$1(this, ISOWeekParser); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this), "priority", 100); + _defineProperty$1(_assertThisInitialized$2(_this), "incompatibleTokens", ['y', 'Y', 'u', 'q', 'Q', 'M', 'L', 'w', 'd', 'D', 'e', 'c', 't', 'T']); + return _this; + } + _createClass$1(ISOWeekParser, [{ + key: "parse", + value: function parse(dateString, token, match) { + switch (token) { + case 'I': + return parseNumericPattern(numericPatterns.week, dateString); + case 'Io': + return match.ordinalNumber(dateString, { + unit: 'week' + }); + default: + return parseNDigits(token.length, dateString); + } + } + }, { + key: "validate", + value: function validate(_date, value) { + return value >= 1 && value <= 53; + } + }, { + key: "set", + value: function set(date, _flags, value) { + return startOfUTCISOWeek(setUTCISOWeek(date, value)); + } + }]); + return ISOWeekParser; +}(Parser); + +var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +var DAYS_IN_MONTH_LEAP_YEAR = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + +// Day of the month +var DateParser = /*#__PURE__*/function (_Parser) { + _inherits$1(DateParser, _Parser); + var _super = _createSuper$1(DateParser); + function DateParser() { + var _this; + _classCallCheck$1(this, DateParser); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this), "priority", 90); + _defineProperty$1(_assertThisInitialized$2(_this), "subPriority", 1); + _defineProperty$1(_assertThisInitialized$2(_this), "incompatibleTokens", ['Y', 'R', 'q', 'Q', 'w', 'I', 'D', 'i', 'e', 'c', 't', 'T']); + return _this; + } + _createClass$1(DateParser, [{ + key: "parse", + value: function parse(dateString, token, match) { + switch (token) { + case 'd': + return parseNumericPattern(numericPatterns.date, dateString); + case 'do': + return match.ordinalNumber(dateString, { + unit: 'date' + }); + default: + return parseNDigits(token.length, dateString); + } + } + }, { + key: "validate", + value: function validate(date, value) { + var year = date.getUTCFullYear(); + var isLeapYear = isLeapYearIndex$1(year); + var month = date.getUTCMonth(); + if (isLeapYear) { + return value >= 1 && value <= DAYS_IN_MONTH_LEAP_YEAR[month]; + } else { + return value >= 1 && value <= DAYS_IN_MONTH[month]; + } + } + }, { + key: "set", + value: function set(date, _flags, value) { + date.setUTCDate(value); + date.setUTCHours(0, 0, 0, 0); + return date; + } + }]); + return DateParser; +}(Parser); + +var DayOfYearParser = /*#__PURE__*/function (_Parser) { + _inherits$1(DayOfYearParser, _Parser); + var _super = _createSuper$1(DayOfYearParser); + function DayOfYearParser() { + var _this; + _classCallCheck$1(this, DayOfYearParser); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this), "priority", 90); + _defineProperty$1(_assertThisInitialized$2(_this), "subpriority", 1); + _defineProperty$1(_assertThisInitialized$2(_this), "incompatibleTokens", ['Y', 'R', 'q', 'Q', 'M', 'L', 'w', 'I', 'd', 'E', 'i', 'e', 'c', 't', 'T']); + return _this; + } + _createClass$1(DayOfYearParser, [{ + key: "parse", + value: function parse(dateString, token, match) { + switch (token) { + case 'D': + case 'DD': + return parseNumericPattern(numericPatterns.dayOfYear, dateString); + case 'Do': + return match.ordinalNumber(dateString, { + unit: 'date' + }); + default: + return parseNDigits(token.length, dateString); + } + } + }, { + key: "validate", + value: function validate(date, value) { + var year = date.getUTCFullYear(); + var isLeapYear = isLeapYearIndex$1(year); + if (isLeapYear) { + return value >= 1 && value <= 366; + } else { + return value >= 1 && value <= 365; + } + } + }, { + key: "set", + value: function set(date, _flags, value) { + date.setUTCMonth(0, value); + date.setUTCHours(0, 0, 0, 0); + return date; + } + }]); + return DayOfYearParser; +}(Parser); + +function setUTCDay(dirtyDate, dirtyDay, options) { + var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; + requiredArgs(2, arguments); + var defaultOptions = getDefaultOptions(); + var weekStartsOn = toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0); + + // Test if weekStartsOn is between 0 and 6 _and_ is not NaN + if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { + throw new RangeError('weekStartsOn must be between 0 and 6 inclusively'); + } + var date = toDate(dirtyDate); + var day = toInteger(dirtyDay); + var currentDay = date.getUTCDay(); + var remainder = day % 7; + var dayIndex = (remainder + 7) % 7; + var diff = (dayIndex < weekStartsOn ? 7 : 0) + day - currentDay; + date.setUTCDate(date.getUTCDate() + diff); + return date; +} + +var DayParser = /*#__PURE__*/function (_Parser) { + _inherits$1(DayParser, _Parser); + var _super = _createSuper$1(DayParser); + function DayParser() { + var _this; + _classCallCheck$1(this, DayParser); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this), "priority", 90); + _defineProperty$1(_assertThisInitialized$2(_this), "incompatibleTokens", ['D', 'i', 'e', 'c', 't', 'T']); + return _this; + } + _createClass$1(DayParser, [{ + key: "parse", + value: function parse(dateString, token, match) { + switch (token) { + // Tue + case 'E': + case 'EE': + case 'EEE': + return match.day(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.day(dateString, { + width: 'short', + context: 'formatting' + }) || match.day(dateString, { + width: 'narrow', + context: 'formatting' + }); + // T + case 'EEEEE': + return match.day(dateString, { + width: 'narrow', + context: 'formatting' + }); + // Tu + case 'EEEEEE': + return match.day(dateString, { + width: 'short', + context: 'formatting' + }) || match.day(dateString, { + width: 'narrow', + context: 'formatting' + }); + // Tuesday + case 'EEEE': + default: + return match.day(dateString, { + width: 'wide', + context: 'formatting' + }) || match.day(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.day(dateString, { + width: 'short', + context: 'formatting' + }) || match.day(dateString, { + width: 'narrow', + context: 'formatting' + }); + } + } + }, { + key: "validate", + value: function validate(_date, value) { + return value >= 0 && value <= 6; + } + }, { + key: "set", + value: function set(date, _flags, value, options) { + date = setUTCDay(date, value, options); + date.setUTCHours(0, 0, 0, 0); + return date; + } + }]); + return DayParser; +}(Parser); + +var LocalDayParser = /*#__PURE__*/function (_Parser) { + _inherits$1(LocalDayParser, _Parser); + var _super = _createSuper$1(LocalDayParser); + function LocalDayParser() { + var _this; + _classCallCheck$1(this, LocalDayParser); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this), "priority", 90); + _defineProperty$1(_assertThisInitialized$2(_this), "incompatibleTokens", ['y', 'R', 'u', 'q', 'Q', 'M', 'L', 'I', 'd', 'D', 'E', 'i', 'c', 't', 'T']); + return _this; + } + _createClass$1(LocalDayParser, [{ + key: "parse", + value: function parse(dateString, token, match, options) { + var valueCallback = function valueCallback(value) { + var wholeWeekDays = Math.floor((value - 1) / 7) * 7; + return (value + options.weekStartsOn + 6) % 7 + wholeWeekDays; + }; + switch (token) { + // 3 + case 'e': + case 'ee': + // 03 + return mapValue(parseNDigits(token.length, dateString), valueCallback); + // 3rd + case 'eo': + return mapValue(match.ordinalNumber(dateString, { + unit: 'day' + }), valueCallback); + // Tue + case 'eee': + return match.day(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.day(dateString, { + width: 'short', + context: 'formatting' + }) || match.day(dateString, { + width: 'narrow', + context: 'formatting' + }); + // T + case 'eeeee': + return match.day(dateString, { + width: 'narrow', + context: 'formatting' + }); + // Tu + case 'eeeeee': + return match.day(dateString, { + width: 'short', + context: 'formatting' + }) || match.day(dateString, { + width: 'narrow', + context: 'formatting' + }); + // Tuesday + case 'eeee': + default: + return match.day(dateString, { + width: 'wide', + context: 'formatting' + }) || match.day(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.day(dateString, { + width: 'short', + context: 'formatting' + }) || match.day(dateString, { + width: 'narrow', + context: 'formatting' + }); + } + } + }, { + key: "validate", + value: function validate(_date, value) { + return value >= 0 && value <= 6; + } + }, { + key: "set", + value: function set(date, _flags, value, options) { + date = setUTCDay(date, value, options); + date.setUTCHours(0, 0, 0, 0); + return date; + } + }]); + return LocalDayParser; +}(Parser); + +var StandAloneLocalDayParser = /*#__PURE__*/function (_Parser) { + _inherits$1(StandAloneLocalDayParser, _Parser); + var _super = _createSuper$1(StandAloneLocalDayParser); + function StandAloneLocalDayParser() { + var _this; + _classCallCheck$1(this, StandAloneLocalDayParser); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this), "priority", 90); + _defineProperty$1(_assertThisInitialized$2(_this), "incompatibleTokens", ['y', 'R', 'u', 'q', 'Q', 'M', 'L', 'I', 'd', 'D', 'E', 'i', 'e', 't', 'T']); + return _this; + } + _createClass$1(StandAloneLocalDayParser, [{ + key: "parse", + value: function parse(dateString, token, match, options) { + var valueCallback = function valueCallback(value) { + var wholeWeekDays = Math.floor((value - 1) / 7) * 7; + return (value + options.weekStartsOn + 6) % 7 + wholeWeekDays; + }; + switch (token) { + // 3 + case 'c': + case 'cc': + // 03 + return mapValue(parseNDigits(token.length, dateString), valueCallback); + // 3rd + case 'co': + return mapValue(match.ordinalNumber(dateString, { + unit: 'day' + }), valueCallback); + // Tue + case 'ccc': + return match.day(dateString, { + width: 'abbreviated', + context: 'standalone' + }) || match.day(dateString, { + width: 'short', + context: 'standalone' + }) || match.day(dateString, { + width: 'narrow', + context: 'standalone' + }); + // T + case 'ccccc': + return match.day(dateString, { + width: 'narrow', + context: 'standalone' + }); + // Tu + case 'cccccc': + return match.day(dateString, { + width: 'short', + context: 'standalone' + }) || match.day(dateString, { + width: 'narrow', + context: 'standalone' + }); + // Tuesday + case 'cccc': + default: + return match.day(dateString, { + width: 'wide', + context: 'standalone' + }) || match.day(dateString, { + width: 'abbreviated', + context: 'standalone' + }) || match.day(dateString, { + width: 'short', + context: 'standalone' + }) || match.day(dateString, { + width: 'narrow', + context: 'standalone' + }); + } + } + }, { + key: "validate", + value: function validate(_date, value) { + return value >= 0 && value <= 6; + } + }, { + key: "set", + value: function set(date, _flags, value, options) { + date = setUTCDay(date, value, options); + date.setUTCHours(0, 0, 0, 0); + return date; + } + }]); + return StandAloneLocalDayParser; +}(Parser); + +function setUTCISODay(dirtyDate, dirtyDay) { + requiredArgs(2, arguments); + var day = toInteger(dirtyDay); + if (day % 7 === 0) { + day = day - 7; + } + var weekStartsOn = 1; + var date = toDate(dirtyDate); + var currentDay = date.getUTCDay(); + var remainder = day % 7; + var dayIndex = (remainder + 7) % 7; + var diff = (dayIndex < weekStartsOn ? 7 : 0) + day - currentDay; + date.setUTCDate(date.getUTCDate() + diff); + return date; +} + +var ISODayParser = /*#__PURE__*/function (_Parser) { + _inherits$1(ISODayParser, _Parser); + var _super = _createSuper$1(ISODayParser); + function ISODayParser() { + var _this; + _classCallCheck$1(this, ISODayParser); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this), "priority", 90); + _defineProperty$1(_assertThisInitialized$2(_this), "incompatibleTokens", ['y', 'Y', 'u', 'q', 'Q', 'M', 'L', 'w', 'd', 'D', 'E', 'e', 'c', 't', 'T']); + return _this; + } + _createClass$1(ISODayParser, [{ + key: "parse", + value: function parse(dateString, token, match) { + var valueCallback = function valueCallback(value) { + if (value === 0) { + return 7; + } + return value; + }; + switch (token) { + // 2 + case 'i': + case 'ii': + // 02 + return parseNDigits(token.length, dateString); + // 2nd + case 'io': + return match.ordinalNumber(dateString, { + unit: 'day' + }); + // Tue + case 'iii': + return mapValue(match.day(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.day(dateString, { + width: 'short', + context: 'formatting' + }) || match.day(dateString, { + width: 'narrow', + context: 'formatting' + }), valueCallback); + // T + case 'iiiii': + return mapValue(match.day(dateString, { + width: 'narrow', + context: 'formatting' + }), valueCallback); + // Tu + case 'iiiiii': + return mapValue(match.day(dateString, { + width: 'short', + context: 'formatting' + }) || match.day(dateString, { + width: 'narrow', + context: 'formatting' + }), valueCallback); + // Tuesday + case 'iiii': + default: + return mapValue(match.day(dateString, { + width: 'wide', + context: 'formatting' + }) || match.day(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.day(dateString, { + width: 'short', + context: 'formatting' + }) || match.day(dateString, { + width: 'narrow', + context: 'formatting' + }), valueCallback); + } + } + }, { + key: "validate", + value: function validate(_date, value) { + return value >= 1 && value <= 7; + } + }, { + key: "set", + value: function set(date, _flags, value) { + date = setUTCISODay(date, value); + date.setUTCHours(0, 0, 0, 0); + return date; + } + }]); + return ISODayParser; +}(Parser); + +var AMPMParser = /*#__PURE__*/function (_Parser) { + _inherits$1(AMPMParser, _Parser); + var _super = _createSuper$1(AMPMParser); + function AMPMParser() { + var _this; + _classCallCheck$1(this, AMPMParser); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this), "priority", 80); + _defineProperty$1(_assertThisInitialized$2(_this), "incompatibleTokens", ['b', 'B', 'H', 'k', 't', 'T']); + return _this; + } + _createClass$1(AMPMParser, [{ + key: "parse", + value: function parse(dateString, token, match) { + switch (token) { + case 'a': + case 'aa': + case 'aaa': + return match.dayPeriod(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting' + }); + case 'aaaaa': + return match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting' + }); + case 'aaaa': + default: + return match.dayPeriod(dateString, { + width: 'wide', + context: 'formatting' + }) || match.dayPeriod(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting' + }); + } + } + }, { + key: "set", + value: function set(date, _flags, value) { + date.setUTCHours(dayPeriodEnumToHours(value), 0, 0, 0); + return date; + } + }]); + return AMPMParser; +}(Parser); + +var AMPMMidnightParser = /*#__PURE__*/function (_Parser) { + _inherits$1(AMPMMidnightParser, _Parser); + var _super = _createSuper$1(AMPMMidnightParser); + function AMPMMidnightParser() { + var _this; + _classCallCheck$1(this, AMPMMidnightParser); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this), "priority", 80); + _defineProperty$1(_assertThisInitialized$2(_this), "incompatibleTokens", ['a', 'B', 'H', 'k', 't', 'T']); + return _this; + } + _createClass$1(AMPMMidnightParser, [{ + key: "parse", + value: function parse(dateString, token, match) { + switch (token) { + case 'b': + case 'bb': + case 'bbb': + return match.dayPeriod(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting' + }); + case 'bbbbb': + return match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting' + }); + case 'bbbb': + default: + return match.dayPeriod(dateString, { + width: 'wide', + context: 'formatting' + }) || match.dayPeriod(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting' + }); + } + } + }, { + key: "set", + value: function set(date, _flags, value) { + date.setUTCHours(dayPeriodEnumToHours(value), 0, 0, 0); + return date; + } + }]); + return AMPMMidnightParser; +}(Parser); + +var DayPeriodParser = /*#__PURE__*/function (_Parser) { + _inherits$1(DayPeriodParser, _Parser); + var _super = _createSuper$1(DayPeriodParser); + function DayPeriodParser() { + var _this; + _classCallCheck$1(this, DayPeriodParser); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this), "priority", 80); + _defineProperty$1(_assertThisInitialized$2(_this), "incompatibleTokens", ['a', 'b', 't', 'T']); + return _this; + } + _createClass$1(DayPeriodParser, [{ + key: "parse", + value: function parse(dateString, token, match) { + switch (token) { + case 'B': + case 'BB': + case 'BBB': + return match.dayPeriod(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting' + }); + case 'BBBBB': + return match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting' + }); + case 'BBBB': + default: + return match.dayPeriod(dateString, { + width: 'wide', + context: 'formatting' + }) || match.dayPeriod(dateString, { + width: 'abbreviated', + context: 'formatting' + }) || match.dayPeriod(dateString, { + width: 'narrow', + context: 'formatting' + }); + } + } + }, { + key: "set", + value: function set(date, _flags, value) { + date.setUTCHours(dayPeriodEnumToHours(value), 0, 0, 0); + return date; + } + }]); + return DayPeriodParser; +}(Parser); + +var Hour1to12Parser = /*#__PURE__*/function (_Parser) { + _inherits$1(Hour1to12Parser, _Parser); + var _super = _createSuper$1(Hour1to12Parser); + function Hour1to12Parser() { + var _this; + _classCallCheck$1(this, Hour1to12Parser); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this), "priority", 70); + _defineProperty$1(_assertThisInitialized$2(_this), "incompatibleTokens", ['H', 'K', 'k', 't', 'T']); + return _this; + } + _createClass$1(Hour1to12Parser, [{ + key: "parse", + value: function parse(dateString, token, match) { + switch (token) { + case 'h': + return parseNumericPattern(numericPatterns.hour12h, dateString); + case 'ho': + return match.ordinalNumber(dateString, { + unit: 'hour' + }); + default: + return parseNDigits(token.length, dateString); + } + } + }, { + key: "validate", + value: function validate(_date, value) { + return value >= 1 && value <= 12; + } + }, { + key: "set", + value: function set(date, _flags, value) { + var isPM = date.getUTCHours() >= 12; + if (isPM && value < 12) { + date.setUTCHours(value + 12, 0, 0, 0); + } else if (!isPM && value === 12) { + date.setUTCHours(0, 0, 0, 0); + } else { + date.setUTCHours(value, 0, 0, 0); + } + return date; + } + }]); + return Hour1to12Parser; +}(Parser); + +var Hour0to23Parser = /*#__PURE__*/function (_Parser) { + _inherits$1(Hour0to23Parser, _Parser); + var _super = _createSuper$1(Hour0to23Parser); + function Hour0to23Parser() { + var _this; + _classCallCheck$1(this, Hour0to23Parser); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this), "priority", 70); + _defineProperty$1(_assertThisInitialized$2(_this), "incompatibleTokens", ['a', 'b', 'h', 'K', 'k', 't', 'T']); + return _this; + } + _createClass$1(Hour0to23Parser, [{ + key: "parse", + value: function parse(dateString, token, match) { + switch (token) { + case 'H': + return parseNumericPattern(numericPatterns.hour23h, dateString); + case 'Ho': + return match.ordinalNumber(dateString, { + unit: 'hour' + }); + default: + return parseNDigits(token.length, dateString); + } + } + }, { + key: "validate", + value: function validate(_date, value) { + return value >= 0 && value <= 23; + } + }, { + key: "set", + value: function set(date, _flags, value) { + date.setUTCHours(value, 0, 0, 0); + return date; + } + }]); + return Hour0to23Parser; +}(Parser); + +var Hour0To11Parser = /*#__PURE__*/function (_Parser) { + _inherits$1(Hour0To11Parser, _Parser); + var _super = _createSuper$1(Hour0To11Parser); + function Hour0To11Parser() { + var _this; + _classCallCheck$1(this, Hour0To11Parser); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this), "priority", 70); + _defineProperty$1(_assertThisInitialized$2(_this), "incompatibleTokens", ['h', 'H', 'k', 't', 'T']); + return _this; + } + _createClass$1(Hour0To11Parser, [{ + key: "parse", + value: function parse(dateString, token, match) { + switch (token) { + case 'K': + return parseNumericPattern(numericPatterns.hour11h, dateString); + case 'Ko': + return match.ordinalNumber(dateString, { + unit: 'hour' + }); + default: + return parseNDigits(token.length, dateString); + } + } + }, { + key: "validate", + value: function validate(_date, value) { + return value >= 0 && value <= 11; + } + }, { + key: "set", + value: function set(date, _flags, value) { + var isPM = date.getUTCHours() >= 12; + if (isPM && value < 12) { + date.setUTCHours(value + 12, 0, 0, 0); + } else { + date.setUTCHours(value, 0, 0, 0); + } + return date; + } + }]); + return Hour0To11Parser; +}(Parser); + +var Hour1To24Parser = /*#__PURE__*/function (_Parser) { + _inherits$1(Hour1To24Parser, _Parser); + var _super = _createSuper$1(Hour1To24Parser); + function Hour1To24Parser() { + var _this; + _classCallCheck$1(this, Hour1To24Parser); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this), "priority", 70); + _defineProperty$1(_assertThisInitialized$2(_this), "incompatibleTokens", ['a', 'b', 'h', 'H', 'K', 't', 'T']); + return _this; + } + _createClass$1(Hour1To24Parser, [{ + key: "parse", + value: function parse(dateString, token, match) { + switch (token) { + case 'k': + return parseNumericPattern(numericPatterns.hour24h, dateString); + case 'ko': + return match.ordinalNumber(dateString, { + unit: 'hour' + }); + default: + return parseNDigits(token.length, dateString); + } + } + }, { + key: "validate", + value: function validate(_date, value) { + return value >= 1 && value <= 24; + } + }, { + key: "set", + value: function set(date, _flags, value) { + var hours = value <= 24 ? value % 24 : value; + date.setUTCHours(hours, 0, 0, 0); + return date; + } + }]); + return Hour1To24Parser; +}(Parser); + +var MinuteParser = /*#__PURE__*/function (_Parser) { + _inherits$1(MinuteParser, _Parser); + var _super = _createSuper$1(MinuteParser); + function MinuteParser() { + var _this; + _classCallCheck$1(this, MinuteParser); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this), "priority", 60); + _defineProperty$1(_assertThisInitialized$2(_this), "incompatibleTokens", ['t', 'T']); + return _this; + } + _createClass$1(MinuteParser, [{ + key: "parse", + value: function parse(dateString, token, match) { + switch (token) { + case 'm': + return parseNumericPattern(numericPatterns.minute, dateString); + case 'mo': + return match.ordinalNumber(dateString, { + unit: 'minute' + }); + default: + return parseNDigits(token.length, dateString); + } + } + }, { + key: "validate", + value: function validate(_date, value) { + return value >= 0 && value <= 59; + } + }, { + key: "set", + value: function set(date, _flags, value) { + date.setUTCMinutes(value, 0, 0); + return date; + } + }]); + return MinuteParser; +}(Parser); + +var SecondParser = /*#__PURE__*/function (_Parser) { + _inherits$1(SecondParser, _Parser); + var _super = _createSuper$1(SecondParser); + function SecondParser() { + var _this; + _classCallCheck$1(this, SecondParser); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this), "priority", 50); + _defineProperty$1(_assertThisInitialized$2(_this), "incompatibleTokens", ['t', 'T']); + return _this; + } + _createClass$1(SecondParser, [{ + key: "parse", + value: function parse(dateString, token, match) { + switch (token) { + case 's': + return parseNumericPattern(numericPatterns.second, dateString); + case 'so': + return match.ordinalNumber(dateString, { + unit: 'second' + }); + default: + return parseNDigits(token.length, dateString); + } + } + }, { + key: "validate", + value: function validate(_date, value) { + return value >= 0 && value <= 59; + } + }, { + key: "set", + value: function set(date, _flags, value) { + date.setUTCSeconds(value, 0); + return date; + } + }]); + return SecondParser; +}(Parser); + +var FractionOfSecondParser = /*#__PURE__*/function (_Parser) { + _inherits$1(FractionOfSecondParser, _Parser); + var _super = _createSuper$1(FractionOfSecondParser); + function FractionOfSecondParser() { + var _this; + _classCallCheck$1(this, FractionOfSecondParser); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this), "priority", 30); + _defineProperty$1(_assertThisInitialized$2(_this), "incompatibleTokens", ['t', 'T']); + return _this; + } + _createClass$1(FractionOfSecondParser, [{ + key: "parse", + value: function parse(dateString, token) { + var valueCallback = function valueCallback(value) { + return Math.floor(value * Math.pow(10, -token.length + 3)); + }; + return mapValue(parseNDigits(token.length, dateString), valueCallback); + } + }, { + key: "set", + value: function set(date, _flags, value) { + date.setUTCMilliseconds(value); + return date; + } + }]); + return FractionOfSecondParser; +}(Parser); + +var ISOTimezoneWithZParser = /*#__PURE__*/function (_Parser) { + _inherits$1(ISOTimezoneWithZParser, _Parser); + var _super = _createSuper$1(ISOTimezoneWithZParser); + function ISOTimezoneWithZParser() { + var _this; + _classCallCheck$1(this, ISOTimezoneWithZParser); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this), "priority", 10); + _defineProperty$1(_assertThisInitialized$2(_this), "incompatibleTokens", ['t', 'T', 'x']); + return _this; + } + _createClass$1(ISOTimezoneWithZParser, [{ + key: "parse", + value: function parse(dateString, token) { + switch (token) { + case 'X': + return parseTimezonePattern(timezonePatterns.basicOptionalMinutes, dateString); + case 'XX': + return parseTimezonePattern(timezonePatterns.basic, dateString); + case 'XXXX': + return parseTimezonePattern(timezonePatterns.basicOptionalSeconds, dateString); + case 'XXXXX': + return parseTimezonePattern(timezonePatterns.extendedOptionalSeconds, dateString); + case 'XXX': + default: + return parseTimezonePattern(timezonePatterns.extended, dateString); + } + } + }, { + key: "set", + value: function set(date, flags, value) { + if (flags.timestampIsSet) { + return date; + } + return new Date(date.getTime() - value); + } + }]); + return ISOTimezoneWithZParser; +}(Parser); + +var ISOTimezoneParser = /*#__PURE__*/function (_Parser) { + _inherits$1(ISOTimezoneParser, _Parser); + var _super = _createSuper$1(ISOTimezoneParser); + function ISOTimezoneParser() { + var _this; + _classCallCheck$1(this, ISOTimezoneParser); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this), "priority", 10); + _defineProperty$1(_assertThisInitialized$2(_this), "incompatibleTokens", ['t', 'T', 'X']); + return _this; + } + _createClass$1(ISOTimezoneParser, [{ + key: "parse", + value: function parse(dateString, token) { + switch (token) { + case 'x': + return parseTimezonePattern(timezonePatterns.basicOptionalMinutes, dateString); + case 'xx': + return parseTimezonePattern(timezonePatterns.basic, dateString); + case 'xxxx': + return parseTimezonePattern(timezonePatterns.basicOptionalSeconds, dateString); + case 'xxxxx': + return parseTimezonePattern(timezonePatterns.extendedOptionalSeconds, dateString); + case 'xxx': + default: + return parseTimezonePattern(timezonePatterns.extended, dateString); + } + } + }, { + key: "set", + value: function set(date, flags, value) { + if (flags.timestampIsSet) { + return date; + } + return new Date(date.getTime() - value); + } + }]); + return ISOTimezoneParser; +}(Parser); + +var TimestampSecondsParser = /*#__PURE__*/function (_Parser) { + _inherits$1(TimestampSecondsParser, _Parser); + var _super = _createSuper$1(TimestampSecondsParser); + function TimestampSecondsParser() { + var _this; + _classCallCheck$1(this, TimestampSecondsParser); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this), "priority", 40); + _defineProperty$1(_assertThisInitialized$2(_this), "incompatibleTokens", '*'); + return _this; + } + _createClass$1(TimestampSecondsParser, [{ + key: "parse", + value: function parse(dateString) { + return parseAnyDigitsSigned(dateString); + } + }, { + key: "set", + value: function set(_date, _flags, value) { + return [new Date(value * 1000), { + timestampIsSet: true + }]; + } + }]); + return TimestampSecondsParser; +}(Parser); + +var TimestampMillisecondsParser = /*#__PURE__*/function (_Parser) { + _inherits$1(TimestampMillisecondsParser, _Parser); + var _super = _createSuper$1(TimestampMillisecondsParser); + function TimestampMillisecondsParser() { + var _this; + _classCallCheck$1(this, TimestampMillisecondsParser); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty$1(_assertThisInitialized$2(_this), "priority", 20); + _defineProperty$1(_assertThisInitialized$2(_this), "incompatibleTokens", '*'); + return _this; + } + _createClass$1(TimestampMillisecondsParser, [{ + key: "parse", + value: function parse(dateString) { + return parseAnyDigitsSigned(dateString); + } + }, { + key: "set", + value: function set(_date, _flags, value) { + return [new Date(value), { + timestampIsSet: true + }]; + } + }]); + return TimestampMillisecondsParser; +}(Parser); + +/* + * | | Unit | | Unit | + * |-----|--------------------------------|-----|--------------------------------| + * | a | AM, PM | A* | Milliseconds in day | + * | b | AM, PM, noon, midnight | B | Flexible day period | + * | c | Stand-alone local day of week | C* | Localized hour w/ day period | + * | d | Day of month | D | Day of year | + * | e | Local day of week | E | Day of week | + * | f | | F* | Day of week in month | + * | g* | Modified Julian day | G | Era | + * | h | Hour [1-12] | H | Hour [0-23] | + * | i! | ISO day of week | I! | ISO week of year | + * | j* | Localized hour w/ day period | J* | Localized hour w/o day period | + * | k | Hour [1-24] | K | Hour [0-11] | + * | l* | (deprecated) | L | Stand-alone month | + * | m | Minute | M | Month | + * | n | | N | | + * | o! | Ordinal number modifier | O* | Timezone (GMT) | + * | p | | P | | + * | q | Stand-alone quarter | Q | Quarter | + * | r* | Related Gregorian year | R! | ISO week-numbering year | + * | s | Second | S | Fraction of second | + * | t! | Seconds timestamp | T! | Milliseconds timestamp | + * | u | Extended year | U* | Cyclic year | + * | v* | Timezone (generic non-locat.) | V* | Timezone (location) | + * | w | Local week of year | W* | Week of month | + * | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) | + * | y | Year (abs) | Y | Local week-numbering year | + * | z* | Timezone (specific non-locat.) | Z* | Timezone (aliases) | + * + * Letters marked by * are not implemented but reserved by Unicode standard. + * + * Letters marked by ! are non-standard, but implemented by date-fns: + * - `o` modifies the previous token to turn it into an ordinal (see `parse` docs) + * - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days, + * i.e. 7 for Sunday, 1 for Monday, etc. + * - `I` is ISO week of year, as opposed to `w` which is local week of year. + * - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year. + * `R` is supposed to be used in conjunction with `I` and `i` + * for universal ISO week-numbering date, whereas + * `Y` is supposed to be used in conjunction with `w` and `e` + * for week-numbering date specific to the locale. + */ +var parsers = { + G: new EraParser(), + y: new YearParser(), + Y: new LocalWeekYearParser(), + R: new ISOWeekYearParser(), + u: new ExtendedYearParser(), + Q: new QuarterParser(), + q: new StandAloneQuarterParser(), + M: new MonthParser(), + L: new StandAloneMonthParser(), + w: new LocalWeekParser(), + I: new ISOWeekParser(), + d: new DateParser(), + D: new DayOfYearParser(), + E: new DayParser(), + e: new LocalDayParser(), + c: new StandAloneLocalDayParser(), + i: new ISODayParser(), + a: new AMPMParser(), + b: new AMPMMidnightParser(), + B: new DayPeriodParser(), + h: new Hour1to12Parser(), + H: new Hour0to23Parser(), + K: new Hour0To11Parser(), + k: new Hour1To24Parser(), + m: new MinuteParser(), + s: new SecondParser(), + S: new FractionOfSecondParser(), + X: new ISOTimezoneWithZParser(), + x: new ISOTimezoneParser(), + t: new TimestampSecondsParser(), + T: new TimestampMillisecondsParser() +}; + +// - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token +// (one of the certain letters followed by `o`) +// - (\w)\1* matches any sequences of the same letter +// - '' matches two quote characters in a row +// - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('), +// except a single quote symbol, which ends the sequence. +// Two quote characters do not end the sequence. +// If there is no matching single quote +// then the sequence will continue until the end of the string. +// - . matches any single character unmatched by previous parts of the RegExps +var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g; + +// This RegExp catches symbols escaped by quotes, and also +// sequences of symbols P, p, and the combinations like `PPPPPPPppppp` +var longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g; +var escapedStringRegExp = /^'([^]*?)'?$/; +var doubleQuoteRegExp = /''/g; +var notWhitespaceRegExp = /\S/; +var unescapedLatinCharacterRegExp = /[a-zA-Z]/; + +/** + * @name parse + * @category Common Helpers + * @summary Parse the date. + * + * @description + * Return the date parsed from string using the given format string. + * + * > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries. + * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * + * The characters in the format string wrapped between two single quotes characters (') are escaped. + * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote. + * + * Format of the format string is based on Unicode Technical Standard #35: + * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table + * with a few additions (see note 5 below the table). + * + * Not all tokens are compatible. Combinations that don't make sense or could lead to bugs are prohibited + * and will throw `RangeError`. For example usage of 24-hour format token with AM/PM token will throw an exception: + * + * ```javascript + * parse('23 AM', 'HH a', new Date()) + * //=> RangeError: The format string mustn't contain `HH` and `a` at the same time + * ``` + * + * See the compatibility table: https://docs.google.com/spreadsheets/d/e/2PACX-1vQOPU3xUhplll6dyoMmVUXHKl_8CRDs6_ueLmex3SoqwhuolkuN3O05l4rqx5h1dKX8eb46Ul-CCSrq/pubhtml?gid=0&single=true + * + * Accepted format string patterns: + * | Unit |Prior| Pattern | Result examples | Notes | + * |---------------------------------|-----|---------|-----------------------------------|-------| + * | Era | 140 | G..GGG | AD, BC | | + * | | | GGGG | Anno Domini, Before Christ | 2 | + * | | | GGGGG | A, B | | + * | Calendar year | 130 | y | 44, 1, 1900, 2017, 9999 | 4 | + * | | | yo | 44th, 1st, 1900th, 9999999th | 4,5 | + * | | | yy | 44, 01, 00, 17 | 4 | + * | | | yyy | 044, 001, 123, 999 | 4 | + * | | | yyyy | 0044, 0001, 1900, 2017 | 4 | + * | | | yyyyy | ... | 2,4 | + * | Local week-numbering year | 130 | Y | 44, 1, 1900, 2017, 9000 | 4 | + * | | | Yo | 44th, 1st, 1900th, 9999999th | 4,5 | + * | | | YY | 44, 01, 00, 17 | 4,6 | + * | | | YYY | 044, 001, 123, 999 | 4 | + * | | | YYYY | 0044, 0001, 1900, 2017 | 4,6 | + * | | | YYYYY | ... | 2,4 | + * | ISO week-numbering year | 130 | R | -43, 1, 1900, 2017, 9999, -9999 | 4,5 | + * | | | RR | -43, 01, 00, 17 | 4,5 | + * | | | RRR | -043, 001, 123, 999, -999 | 4,5 | + * | | | RRRR | -0043, 0001, 2017, 9999, -9999 | 4,5 | + * | | | RRRRR | ... | 2,4,5 | + * | Extended year | 130 | u | -43, 1, 1900, 2017, 9999, -999 | 4 | + * | | | uu | -43, 01, 99, -99 | 4 | + * | | | uuu | -043, 001, 123, 999, -999 | 4 | + * | | | uuuu | -0043, 0001, 2017, 9999, -9999 | 4 | + * | | | uuuuu | ... | 2,4 | + * | Quarter (formatting) | 120 | Q | 1, 2, 3, 4 | | + * | | | Qo | 1st, 2nd, 3rd, 4th | 5 | + * | | | QQ | 01, 02, 03, 04 | | + * | | | QQQ | Q1, Q2, Q3, Q4 | | + * | | | QQQQ | 1st quarter, 2nd quarter, ... | 2 | + * | | | QQQQQ | 1, 2, 3, 4 | 4 | + * | Quarter (stand-alone) | 120 | q | 1, 2, 3, 4 | | + * | | | qo | 1st, 2nd, 3rd, 4th | 5 | + * | | | qq | 01, 02, 03, 04 | | + * | | | qqq | Q1, Q2, Q3, Q4 | | + * | | | qqqq | 1st quarter, 2nd quarter, ... | 2 | + * | | | qqqqq | 1, 2, 3, 4 | 3 | + * | Month (formatting) | 110 | M | 1, 2, ..., 12 | | + * | | | Mo | 1st, 2nd, ..., 12th | 5 | + * | | | MM | 01, 02, ..., 12 | | + * | | | MMM | Jan, Feb, ..., Dec | | + * | | | MMMM | January, February, ..., December | 2 | + * | | | MMMMM | J, F, ..., D | | + * | Month (stand-alone) | 110 | L | 1, 2, ..., 12 | | + * | | | Lo | 1st, 2nd, ..., 12th | 5 | + * | | | LL | 01, 02, ..., 12 | | + * | | | LLL | Jan, Feb, ..., Dec | | + * | | | LLLL | January, February, ..., December | 2 | + * | | | LLLLL | J, F, ..., D | | + * | Local week of year | 100 | w | 1, 2, ..., 53 | | + * | | | wo | 1st, 2nd, ..., 53th | 5 | + * | | | ww | 01, 02, ..., 53 | | + * | ISO week of year | 100 | I | 1, 2, ..., 53 | 5 | + * | | | Io | 1st, 2nd, ..., 53th | 5 | + * | | | II | 01, 02, ..., 53 | 5 | + * | Day of month | 90 | d | 1, 2, ..., 31 | | + * | | | do | 1st, 2nd, ..., 31st | 5 | + * | | | dd | 01, 02, ..., 31 | | + * | Day of year | 90 | D | 1, 2, ..., 365, 366 | 7 | + * | | | Do | 1st, 2nd, ..., 365th, 366th | 5 | + * | | | DD | 01, 02, ..., 365, 366 | 7 | + * | | | DDD | 001, 002, ..., 365, 366 | | + * | | | DDDD | ... | 2 | + * | Day of week (formatting) | 90 | E..EEE | Mon, Tue, Wed, ..., Sun | | + * | | | EEEE | Monday, Tuesday, ..., Sunday | 2 | + * | | | EEEEE | M, T, W, T, F, S, S | | + * | | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | | + * | ISO day of week (formatting) | 90 | i | 1, 2, 3, ..., 7 | 5 | + * | | | io | 1st, 2nd, ..., 7th | 5 | + * | | | ii | 01, 02, ..., 07 | 5 | + * | | | iii | Mon, Tue, Wed, ..., Sun | 5 | + * | | | iiii | Monday, Tuesday, ..., Sunday | 2,5 | + * | | | iiiii | M, T, W, T, F, S, S | 5 | + * | | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 5 | + * | Local day of week (formatting) | 90 | e | 2, 3, 4, ..., 1 | | + * | | | eo | 2nd, 3rd, ..., 1st | 5 | + * | | | ee | 02, 03, ..., 01 | | + * | | | eee | Mon, Tue, Wed, ..., Sun | | + * | | | eeee | Monday, Tuesday, ..., Sunday | 2 | + * | | | eeeee | M, T, W, T, F, S, S | | + * | | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | | + * | Local day of week (stand-alone) | 90 | c | 2, 3, 4, ..., 1 | | + * | | | co | 2nd, 3rd, ..., 1st | 5 | + * | | | cc | 02, 03, ..., 01 | | + * | | | ccc | Mon, Tue, Wed, ..., Sun | | + * | | | cccc | Monday, Tuesday, ..., Sunday | 2 | + * | | | ccccc | M, T, W, T, F, S, S | | + * | | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | | + * | AM, PM | 80 | a..aaa | AM, PM | | + * | | | aaaa | a.m., p.m. | 2 | + * | | | aaaaa | a, p | | + * | AM, PM, noon, midnight | 80 | b..bbb | AM, PM, noon, midnight | | + * | | | bbbb | a.m., p.m., noon, midnight | 2 | + * | | | bbbbb | a, p, n, mi | | + * | Flexible day period | 80 | B..BBB | at night, in the morning, ... | | + * | | | BBBB | at night, in the morning, ... | 2 | + * | | | BBBBB | at night, in the morning, ... | | + * | Hour [1-12] | 70 | h | 1, 2, ..., 11, 12 | | + * | | | ho | 1st, 2nd, ..., 11th, 12th | 5 | + * | | | hh | 01, 02, ..., 11, 12 | | + * | Hour [0-23] | 70 | H | 0, 1, 2, ..., 23 | | + * | | | Ho | 0th, 1st, 2nd, ..., 23rd | 5 | + * | | | HH | 00, 01, 02, ..., 23 | | + * | Hour [0-11] | 70 | K | 1, 2, ..., 11, 0 | | + * | | | Ko | 1st, 2nd, ..., 11th, 0th | 5 | + * | | | KK | 01, 02, ..., 11, 00 | | + * | Hour [1-24] | 70 | k | 24, 1, 2, ..., 23 | | + * | | | ko | 24th, 1st, 2nd, ..., 23rd | 5 | + * | | | kk | 24, 01, 02, ..., 23 | | + * | Minute | 60 | m | 0, 1, ..., 59 | | + * | | | mo | 0th, 1st, ..., 59th | 5 | + * | | | mm | 00, 01, ..., 59 | | + * | Second | 50 | s | 0, 1, ..., 59 | | + * | | | so | 0th, 1st, ..., 59th | 5 | + * | | | ss | 00, 01, ..., 59 | | + * | Seconds timestamp | 40 | t | 512969520 | | + * | | | tt | ... | 2 | + * | Fraction of second | 30 | S | 0, 1, ..., 9 | | + * | | | SS | 00, 01, ..., 99 | | + * | | | SSS | 000, 001, ..., 999 | | + * | | | SSSS | ... | 2 | + * | Milliseconds timestamp | 20 | T | 512969520900 | | + * | | | TT | ... | 2 | + * | Timezone (ISO-8601 w/ Z) | 10 | X | -08, +0530, Z | | + * | | | XX | -0800, +0530, Z | | + * | | | XXX | -08:00, +05:30, Z | | + * | | | XXXX | -0800, +0530, Z, +123456 | 2 | + * | | | XXXXX | -08:00, +05:30, Z, +12:34:56 | | + * | Timezone (ISO-8601 w/o Z) | 10 | x | -08, +0530, +00 | | + * | | | xx | -0800, +0530, +0000 | | + * | | | xxx | -08:00, +05:30, +00:00 | 2 | + * | | | xxxx | -0800, +0530, +0000, +123456 | | + * | | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | | + * | Long localized date | NA | P | 05/29/1453 | 5,8 | + * | | | PP | May 29, 1453 | | + * | | | PPP | May 29th, 1453 | | + * | | | PPPP | Sunday, May 29th, 1453 | 2,5,8 | + * | Long localized time | NA | p | 12:00 AM | 5,8 | + * | | | pp | 12:00:00 AM | | + * | Combination of date and time | NA | Pp | 05/29/1453, 12:00 AM | | + * | | | PPpp | May 29, 1453, 12:00:00 AM | | + * | | | PPPpp | May 29th, 1453 at ... | | + * | | | PPPPpp | Sunday, May 29th, 1453 at ... | 2,5,8 | + * Notes: + * 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale + * are the same as "stand-alone" units, but are different in some languages. + * "Formatting" units are declined according to the rules of the language + * in the context of a date. "Stand-alone" units are always nominative singular. + * In `format` function, they will produce different result: + * + * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'` + * + * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'` + * + * `parse` will try to match both formatting and stand-alone units interchangably. + * + * 2. Any sequence of the identical letters is a pattern, unless it is escaped by + * the single quote characters (see below). + * If the sequence is longer than listed in table: + * - for numerical units (`yyyyyyyy`) `parse` will try to match a number + * as wide as the sequence + * - for text units (`MMMMMMMM`) `parse` will try to match the widest variation of the unit. + * These variations are marked with "2" in the last column of the table. + * + * 3. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales. + * These tokens represent the shortest form of the quarter. + * + * 4. The main difference between `y` and `u` patterns are B.C. years: + * + * | Year | `y` | `u` | + * |------|-----|-----| + * | AC 1 | 1 | 1 | + * | BC 1 | 1 | 0 | + * | BC 2 | 2 | -1 | + * + * Also `yy` will try to guess the century of two digit year by proximity with `referenceDate`: + * + * `parse('50', 'yy', new Date(2018, 0, 1)) //=> Sat Jan 01 2050 00:00:00` + * + * `parse('75', 'yy', new Date(2018, 0, 1)) //=> Wed Jan 01 1975 00:00:00` + * + * while `uu` will just assign the year as is: + * + * `parse('50', 'uu', new Date(2018, 0, 1)) //=> Sat Jan 01 0050 00:00:00` + * + * `parse('75', 'uu', new Date(2018, 0, 1)) //=> Tue Jan 01 0075 00:00:00` + * + * The same difference is true for local and ISO week-numbering years (`Y` and `R`), + * except local week-numbering years are dependent on `options.weekStartsOn` + * and `options.firstWeekContainsDate` (compare [setISOWeekYear]{@link https://date-fns.org/docs/setISOWeekYear} + * and [setWeekYear]{@link https://date-fns.org/docs/setWeekYear}). + * + * 5. These patterns are not in the Unicode Technical Standard #35: + * - `i`: ISO day of week + * - `I`: ISO week of year + * - `R`: ISO week-numbering year + * - `o`: ordinal number modifier + * - `P`: long localized date + * - `p`: long localized time + * + * 6. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years. + * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * + * 7. `D` and `DD` tokens represent days of the year but they are ofthen confused with days of the month. + * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * + * 8. `P+` tokens do not have a defined priority since they are merely aliases to other tokens based + * on the given locale. + * + * using `en-US` locale: `P` => `MM/dd/yyyy` + * using `en-US` locale: `p` => `hh:mm a` + * using `pt-BR` locale: `P` => `dd/MM/yyyy` + * using `pt-BR` locale: `p` => `HH:mm` + * + * Values will be assigned to the date in the descending order of its unit's priority. + * Units of an equal priority overwrite each other in the order of appearance. + * + * If no values of higher priority are parsed (e.g. when parsing string 'January 1st' without a year), + * the values will be taken from 3rd argument `referenceDate` which works as a context of parsing. + * + * `referenceDate` must be passed for correct work of the function. + * If you're not sure which `referenceDate` to supply, create a new instance of Date: + * `parse('02/11/2014', 'MM/dd/yyyy', new Date())` + * In this case parsing will be done in the context of the current date. + * If `referenceDate` is `Invalid Date` or a value not convertible to valid `Date`, + * then `Invalid Date` will be returned. + * + * The result may vary by locale. + * + * If `formatString` matches with `dateString` but does not provides tokens, `referenceDate` will be returned. + * + * If parsing failed, `Invalid Date` will be returned. + * Invalid Date is a Date, whose time value is NaN. + * Time value of Date: http://es5.github.io/#x15.9.1.1 + * + * @param {String} dateString - the string to parse + * @param {String} formatString - the string of tokens + * @param {Date|Number} referenceDate - defines values missing from the parsed dateString + * @param {Object} [options] - an object with options. + * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} + * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) + * @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year + * @param {Boolean} [options.useAdditionalWeekYearTokens=false] - if true, allows usage of the week-numbering year tokens `YY` and `YYYY`; + * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @param {Boolean} [options.useAdditionalDayOfYearTokens=false] - if true, allows usage of the day of year tokens `D` and `DD`; + * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @returns {Date} the parsed date + * @throws {TypeError} 3 arguments required + * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 + * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7 + * @throws {RangeError} `options.locale` must contain `match` property + * @throws {RangeError} use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md + * @throws {RangeError} format string contains an unescaped latin alphabet character + * + * @example + * // Parse 11 February 2014 from middle-endian format: + * var result = parse('02/11/2014', 'MM/dd/yyyy', new Date()) + * //=> Tue Feb 11 2014 00:00:00 + * + * @example + * // Parse 28th of February in Esperanto locale in the context of 2010 year: + * import eo from 'date-fns/locale/eo' + * var result = parse('28-a de februaro', "do 'de' MMMM", new Date(2010, 0, 1), { + * locale: eo + * }) + * //=> Sun Feb 28 2010 00:00:00 + */ +function parse$1(dirtyDateString, dirtyFormatString, dirtyReferenceDate, options) { + var _ref, _options$locale, _ref2, _ref3, _ref4, _options$firstWeekCon, _options$locale2, _options$locale2$opti, _defaultOptions$local, _defaultOptions$local2, _ref5, _ref6, _ref7, _options$weekStartsOn, _options$locale3, _options$locale3$opti, _defaultOptions$local3, _defaultOptions$local4; + requiredArgs(3, arguments); + var dateString = String(dirtyDateString); + var formatString = String(dirtyFormatString); + var defaultOptions = getDefaultOptions(); + var locale = (_ref = (_options$locale = options === null || options === void 0 ? void 0 : options.locale) !== null && _options$locale !== void 0 ? _options$locale : defaultOptions.locale) !== null && _ref !== void 0 ? _ref : defaultLocale; + if (!locale.match) { + throw new RangeError('locale must contain match property'); + } + var firstWeekContainsDate = toInteger((_ref2 = (_ref3 = (_ref4 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale2 = options.locale) === null || _options$locale2 === void 0 ? void 0 : (_options$locale2$opti = _options$locale2.options) === null || _options$locale2$opti === void 0 ? void 0 : _options$locale2$opti.firstWeekContainsDate) !== null && _ref4 !== void 0 ? _ref4 : defaultOptions.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : 1); + + // Test if weekStartsOn is between 1 and 7 _and_ is not NaN + if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) { + throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively'); + } + var weekStartsOn = toInteger((_ref5 = (_ref6 = (_ref7 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale3 = options.locale) === null || _options$locale3 === void 0 ? void 0 : (_options$locale3$opti = _options$locale3.options) === null || _options$locale3$opti === void 0 ? void 0 : _options$locale3$opti.weekStartsOn) !== null && _ref7 !== void 0 ? _ref7 : defaultOptions.weekStartsOn) !== null && _ref6 !== void 0 ? _ref6 : (_defaultOptions$local3 = defaultOptions.locale) === null || _defaultOptions$local3 === void 0 ? void 0 : (_defaultOptions$local4 = _defaultOptions$local3.options) === null || _defaultOptions$local4 === void 0 ? void 0 : _defaultOptions$local4.weekStartsOn) !== null && _ref5 !== void 0 ? _ref5 : 0); + + // Test if weekStartsOn is between 0 and 6 _and_ is not NaN + if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { + throw new RangeError('weekStartsOn must be between 0 and 6 inclusively'); + } + if (formatString === '') { + if (dateString === '') { + return toDate(dirtyReferenceDate); + } else { + return new Date(NaN); + } + } + var subFnOptions = { + firstWeekContainsDate: firstWeekContainsDate, + weekStartsOn: weekStartsOn, + locale: locale + }; + + // If timezone isn't specified, it will be set to the system timezone + var setters = [new DateToSystemTimezoneSetter()]; + var tokens = formatString.match(longFormattingTokensRegExp).map(function (substring) { + var firstCharacter = substring[0]; + if (firstCharacter in longFormatters$1) { + var longFormatter = longFormatters$1[firstCharacter]; + return longFormatter(substring, locale.formatLong); + } + return substring; + }).join('').match(formattingTokensRegExp); + var usedTokens = []; + var _iterator = _createForOfIteratorHelper(tokens), + _step; + try { + var _loop = function _loop() { + var token = _step.value; + if (!(options !== null && options !== void 0 && options.useAdditionalWeekYearTokens) && isProtectedWeekYearToken(token)) { + throwProtectedError(token, formatString, dirtyDateString); + } + if (!(options !== null && options !== void 0 && options.useAdditionalDayOfYearTokens) && isProtectedDayOfYearToken(token)) { + throwProtectedError(token, formatString, dirtyDateString); + } + var firstCharacter = token[0]; + var parser = parsers[firstCharacter]; + if (parser) { + var incompatibleTokens = parser.incompatibleTokens; + if (Array.isArray(incompatibleTokens)) { + var incompatibleToken = usedTokens.find(function (usedToken) { + return incompatibleTokens.includes(usedToken.token) || usedToken.token === firstCharacter; + }); + if (incompatibleToken) { + throw new RangeError("The format string mustn't contain `".concat(incompatibleToken.fullToken, "` and `").concat(token, "` at the same time")); + } + } else if (parser.incompatibleTokens === '*' && usedTokens.length > 0) { + throw new RangeError("The format string mustn't contain `".concat(token, "` and any other token at the same time")); + } + usedTokens.push({ + token: firstCharacter, + fullToken: token + }); + var parseResult = parser.run(dateString, token, locale.match, subFnOptions); + if (!parseResult) { + return { + v: new Date(NaN) + }; + } + setters.push(parseResult.setter); + dateString = parseResult.rest; + } else { + if (firstCharacter.match(unescapedLatinCharacterRegExp)) { + throw new RangeError('Format string contains an unescaped latin alphabet character `' + firstCharacter + '`'); + } + + // Replace two single quote characters with one single quote character + if (token === "''") { + token = "'"; + } else if (firstCharacter === "'") { + token = cleanEscapedString(token); + } + + // Cut token from string, or, if string doesn't match the token, return Invalid Date + if (dateString.indexOf(token) === 0) { + dateString = dateString.slice(token.length); + } else { + return { + v: new Date(NaN) + }; + } + } + }; + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var _ret = _loop(); + if (_typeof$1(_ret) === "object") return _ret.v; + } + + // Check if the remaining input contains something other than whitespace + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + if (dateString.length > 0 && notWhitespaceRegExp.test(dateString)) { + return new Date(NaN); + } + var uniquePrioritySetters = setters.map(function (setter) { + return setter.priority; + }).sort(function (a, b) { + return b - a; + }).filter(function (priority, index, array) { + return array.indexOf(priority) === index; + }).map(function (priority) { + return setters.filter(function (setter) { + return setter.priority === priority; + }).sort(function (a, b) { + return b.subPriority - a.subPriority; + }); + }).map(function (setterArray) { + return setterArray[0]; + }); + var date = toDate(dirtyReferenceDate); + if (isNaN(date.getTime())) { + return new Date(NaN); + } + + // Convert the date in system timezone to the same date in UTC+00:00 timezone. + var utcDate = subMilliseconds(date, getTimezoneOffsetInMilliseconds(date)); + var flags = {}; + var _iterator2 = _createForOfIteratorHelper(uniquePrioritySetters), + _step2; + try { + for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { + var setter = _step2.value; + if (!setter.validate(utcDate, subFnOptions)) { + return new Date(NaN); + } + var result = setter.set(utcDate, flags, subFnOptions); + // Result is tuple (date, flags) + if (Array.isArray(result)) { + utcDate = result[0]; + assign(flags, result[1]); + // Result is date + } else { + utcDate = result; + } + } + } catch (err) { + _iterator2.e(err); + } finally { + _iterator2.f(); + } + return utcDate; +} +function cleanEscapedString(input) { + return input.match(escapedStringRegExp)[1].replace(doubleQuoteRegExp, "'"); +} + +/** + * @name parseISO + * @category Common Helpers + * @summary Parse ISO string + * + * @description + * Parse the given string in ISO 8601 format and return an instance of Date. + * + * Function accepts complete ISO 8601 formats as well as partial implementations. + * ISO 8601: http://en.wikipedia.org/wiki/ISO_8601 + * + * If the argument isn't a string, the function cannot parse the string or + * the values are invalid, it returns Invalid Date. + * + * @param {String} argument - the value to convert + * @param {Object} [options] - an object with options. + * @param {0|1|2} [options.additionalDigits=2] - the additional number of digits in the extended year format + * @returns {Date} the parsed date in the local time zone + * @throws {TypeError} 1 argument required + * @throws {RangeError} `options.additionalDigits` must be 0, 1 or 2 + * + * @example + * // Convert string '2014-02-11T11:30:30' to date: + * const result = parseISO('2014-02-11T11:30:30') + * //=> Tue Feb 11 2014 11:30:30 + * + * @example + * // Convert string '+02014101' to date, + * // if the additional number of digits in the extended year format is 1: + * const result = parseISO('+02014101', { additionalDigits: 1 }) + * //=> Fri Apr 11 2014 00:00:00 + */ +function parseISO(argument, options) { + var _options$additionalDi; + requiredArgs(1, arguments); + var additionalDigits = toInteger((_options$additionalDi = options === null || options === void 0 ? void 0 : options.additionalDigits) !== null && _options$additionalDi !== void 0 ? _options$additionalDi : 2); + if (additionalDigits !== 2 && additionalDigits !== 1 && additionalDigits !== 0) { + throw new RangeError('additionalDigits must be 0, 1 or 2'); + } + if (!(typeof argument === 'string' || Object.prototype.toString.call(argument) === '[object String]')) { + return new Date(NaN); + } + var dateStrings = splitDateString(argument); + var date; + if (dateStrings.date) { + var parseYearResult = parseYear(dateStrings.date, additionalDigits); + date = parseDate(parseYearResult.restDateString, parseYearResult.year); + } + if (!date || isNaN(date.getTime())) { + return new Date(NaN); + } + var timestamp = date.getTime(); + var time = 0; + var offset; + if (dateStrings.time) { + time = parseTime(dateStrings.time); + if (isNaN(time)) { + return new Date(NaN); + } + } + if (dateStrings.timezone) { + offset = parseTimezone(dateStrings.timezone); + if (isNaN(offset)) { + return new Date(NaN); + } + } else { + var dirtyDate = new Date(timestamp + time); + // js parsed string assuming it's in UTC timezone + // but we need it to be parsed in our timezone + // so we use utc values to build date in our timezone. + // Year values from 0 to 99 map to the years 1900 to 1999 + // so set year explicitly with setFullYear. + var result = new Date(0); + result.setFullYear(dirtyDate.getUTCFullYear(), dirtyDate.getUTCMonth(), dirtyDate.getUTCDate()); + result.setHours(dirtyDate.getUTCHours(), dirtyDate.getUTCMinutes(), dirtyDate.getUTCSeconds(), dirtyDate.getUTCMilliseconds()); + return result; + } + return new Date(timestamp + time + offset); +} +var patterns = { + dateTimeDelimiter: /[T ]/, + timeZoneDelimiter: /[Z ]/i, + timezone: /([Z+-].*)$/ +}; +var dateRegex = /^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/; +var timeRegex = /^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/; +var timezoneRegex = /^([+-])(\d{2})(?::?(\d{2}))?$/; +function splitDateString(dateString) { + var dateStrings = {}; + var array = dateString.split(patterns.dateTimeDelimiter); + var timeString; + + // The regex match should only return at maximum two array elements. + // [date], [time], or [date, time]. + if (array.length > 2) { + return dateStrings; + } + if (/:/.test(array[0])) { + timeString = array[0]; + } else { + dateStrings.date = array[0]; + timeString = array[1]; + if (patterns.timeZoneDelimiter.test(dateStrings.date)) { + dateStrings.date = dateString.split(patterns.timeZoneDelimiter)[0]; + timeString = dateString.substr(dateStrings.date.length, dateString.length); + } + } + if (timeString) { + var token = patterns.timezone.exec(timeString); + if (token) { + dateStrings.time = timeString.replace(token[1], ''); + dateStrings.timezone = token[1]; + } else { + dateStrings.time = timeString; + } + } + return dateStrings; +} +function parseYear(dateString, additionalDigits) { + var regex = new RegExp('^(?:(\\d{4}|[+-]\\d{' + (4 + additionalDigits) + '})|(\\d{2}|[+-]\\d{' + (2 + additionalDigits) + '})$)'); + var captures = dateString.match(regex); + // Invalid ISO-formatted year + if (!captures) return { + year: NaN, + restDateString: '' + }; + var year = captures[1] ? parseInt(captures[1]) : null; + var century = captures[2] ? parseInt(captures[2]) : null; + + // either year or century is null, not both + return { + year: century === null ? year : century * 100, + restDateString: dateString.slice((captures[1] || captures[2]).length) + }; +} +function parseDate(dateString, year) { + // Invalid ISO-formatted year + if (year === null) return new Date(NaN); + var captures = dateString.match(dateRegex); + // Invalid ISO-formatted string + if (!captures) return new Date(NaN); + var isWeekDate = !!captures[4]; + var dayOfYear = parseDateUnit(captures[1]); + var month = parseDateUnit(captures[2]) - 1; + var day = parseDateUnit(captures[3]); + var week = parseDateUnit(captures[4]); + var dayOfWeek = parseDateUnit(captures[5]) - 1; + if (isWeekDate) { + if (!validateWeekDate(year, week, dayOfWeek)) { + return new Date(NaN); + } + return dayOfISOWeekYear(year, week, dayOfWeek); + } else { + var date = new Date(0); + if (!validateDate(year, month, day) || !validateDayOfYearDate(year, dayOfYear)) { + return new Date(NaN); + } + date.setUTCFullYear(year, month, Math.max(dayOfYear, day)); + return date; + } +} +function parseDateUnit(value) { + return value ? parseInt(value) : 1; +} +function parseTime(timeString) { + var captures = timeString.match(timeRegex); + if (!captures) return NaN; // Invalid ISO-formatted time + + var hours = parseTimeUnit(captures[1]); + var minutes = parseTimeUnit(captures[2]); + var seconds = parseTimeUnit(captures[3]); + if (!validateTime(hours, minutes, seconds)) { + return NaN; + } + return hours * millisecondsInHour + minutes * millisecondsInMinute + seconds * 1000; +} +function parseTimeUnit(value) { + return value && parseFloat(value.replace(',', '.')) || 0; +} +function parseTimezone(timezoneString) { + if (timezoneString === 'Z') return 0; + var captures = timezoneString.match(timezoneRegex); + if (!captures) return 0; + var sign = captures[1] === '+' ? -1 : 1; + var hours = parseInt(captures[2]); + var minutes = captures[3] && parseInt(captures[3]) || 0; + if (!validateTimezone(hours, minutes)) { + return NaN; + } + return sign * (hours * millisecondsInHour + minutes * millisecondsInMinute); +} +function dayOfISOWeekYear(isoWeekYear, week, day) { + var date = new Date(0); + date.setUTCFullYear(isoWeekYear, 0, 4); + var fourthOfJanuaryDay = date.getUTCDay() || 7; + var diff = (week - 1) * 7 + day + 1 - fourthOfJanuaryDay; + date.setUTCDate(date.getUTCDate() + diff); + return date; +} + +// Validation functions + +// February is null to handle the leap year (using ||) +var daysInMonths = [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +function isLeapYearIndex(year) { + return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0; +} +function validateDate(year, month, date) { + return month >= 0 && month <= 11 && date >= 1 && date <= (daysInMonths[month] || (isLeapYearIndex(year) ? 29 : 28)); +} +function validateDayOfYearDate(year, dayOfYear) { + return dayOfYear >= 1 && dayOfYear <= (isLeapYearIndex(year) ? 366 : 365); +} +function validateWeekDate(_year, week, day) { + return week >= 1 && week <= 53 && day >= 0 && day <= 6; +} +function validateTime(hours, minutes, seconds) { + if (hours === 24) { + return minutes === 0 && seconds === 0; + } + return seconds >= 0 && seconds < 60 && minutes >= 0 && minutes < 60 && hours >= 0 && hours < 25; +} +function validateTimezone(_hours, minutes) { + return minutes >= 0 && minutes <= 59; +} + +function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + + _setPrototypeOf$1(subClass, superClass); +} + +function _setPrototypeOf$1(o, p) { + _setPrototypeOf$1 = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + + return _setPrototypeOf$1(o, p); +} + +function _objectWithoutPropertiesLoose$1(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; + + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; + } + + return target; +} + +function _assertThisInitialized$1(self) { + if (self === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return self; +}/** + * Check whether some DOM node is our Component's node. + */ +function isNodeFound(current, componentNode, ignoreClass) { + if (current === componentNode) { + return true; + } // SVG elements do not technically reside in the rendered DOM, so + // they do not have classList directly, but they offer a link to their + // corresponding element, which can have classList. This extra check is for + // that case. + // See: http://www.w3.org/TR/SVG11/struct.html#InterfaceSVGUseElement + // Discussion: https://github.com/Pomax/react-onclickoutside/pull/17 + + + if (current.correspondingElement) { + return current.correspondingElement.classList.contains(ignoreClass); + } + + return current.classList.contains(ignoreClass); +} +/** + * Try to find our node in a hierarchy of nodes, returning the document + * node as highest node if our node is not found in the path up. + */ + +function findHighest(current, componentNode, ignoreClass) { + if (current === componentNode) { + return true; + } // If source=local then this event came from 'somewhere' + // inside and should be ignored. We could handle this with + // a layered approach, too, but that requires going back to + // thinking in terms of Dom node nesting, running counter + // to React's 'you shouldn't care about the DOM' philosophy. + // Also cover shadowRoot node by checking current.host + + + while (current.parentNode || current.host) { + // Only check normal node without shadowRoot + if (current.parentNode && isNodeFound(current, componentNode, ignoreClass)) { + return true; + } + + current = current.parentNode || current.host; + } + + return current; +} +/** + * Check if the browser scrollbar was clicked + */ + +function clickedScrollbar(evt) { + return document.documentElement.clientWidth <= evt.clientX || document.documentElement.clientHeight <= evt.clientY; +}// ideally will get replaced with external dep +// when rafrex/detect-passive-events#4 and rafrex/detect-passive-events#5 get merged in +var testPassiveEventSupport = function testPassiveEventSupport() { + if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') { + return; + } + + var passive = false; + var options = Object.defineProperty({}, 'passive', { + get: function get() { + passive = true; + } + }); + + var noop = function noop() {}; + + window.addEventListener('testPassiveEventSupport', noop, options); + window.removeEventListener('testPassiveEventSupport', noop, options); + return passive; +};function autoInc(seed) { + if (seed === void 0) { + seed = 0; + } + + return function () { + return ++seed; + }; +} + +var uid = autoInc();var passiveEventSupport; +var handlersMap = {}; +var enabledInstances = {}; +var touchEvents = ['touchstart', 'touchmove']; +var IGNORE_CLASS_NAME = 'ignore-react-onclickoutside'; +/** + * Options for addEventHandler and removeEventHandler + */ + +function getEventHandlerOptions(instance, eventName) { + var handlerOptions = {}; + var isTouchEvent = touchEvents.indexOf(eventName) !== -1; + + if (isTouchEvent && passiveEventSupport) { + handlerOptions.passive = !instance.props.preventDefault; + } + + return handlerOptions; +} +/** + * This function generates the HOC function that you'll use + * in order to impart onOutsideClick listening to an + * arbitrary component. It gets called at the end of the + * bootstrapping code to yield an instance of the + * onClickOutsideHOC function defined inside setupHOC(). + */ + + +function onClickOutsideHOC(WrappedComponent, config) { + var _class, _temp; + + var componentName = WrappedComponent.displayName || WrappedComponent.name || 'Component'; + return _temp = _class = /*#__PURE__*/function (_Component) { + _inheritsLoose(onClickOutside, _Component); + + function onClickOutside(props) { + var _this; + + _this = _Component.call(this, props) || this; + + _this.__outsideClickHandler = function (event) { + if (typeof _this.__clickOutsideHandlerProp === 'function') { + _this.__clickOutsideHandlerProp(event); + + return; + } + + var instance = _this.getInstance(); + + if (typeof instance.props.handleClickOutside === 'function') { + instance.props.handleClickOutside(event); + return; + } + + if (typeof instance.handleClickOutside === 'function') { + instance.handleClickOutside(event); + return; + } + + throw new Error("WrappedComponent: " + componentName + " lacks a handleClickOutside(event) function for processing outside click events."); + }; + + _this.__getComponentNode = function () { + var instance = _this.getInstance(); + + if (config && typeof config.setClickOutsideRef === 'function') { + return config.setClickOutsideRef()(instance); + } + + if (typeof instance.setClickOutsideRef === 'function') { + return instance.setClickOutsideRef(); + } + + return reactDomExports.findDOMNode(instance); + }; + + _this.enableOnClickOutside = function () { + if (typeof document === 'undefined' || enabledInstances[_this._uid]) { + return; + } + + if (typeof passiveEventSupport === 'undefined') { + passiveEventSupport = testPassiveEventSupport(); + } + + enabledInstances[_this._uid] = true; + var events = _this.props.eventTypes; + + if (!events.forEach) { + events = [events]; + } + + handlersMap[_this._uid] = function (event) { + if (_this.componentNode === null) return; + + if (_this.props.preventDefault) { + event.preventDefault(); + } + + if (_this.props.stopPropagation) { + event.stopPropagation(); + } + + if (_this.props.excludeScrollbar && clickedScrollbar(event)) return; + var current = event.composed && event.composedPath && event.composedPath().shift() || event.target; + + if (findHighest(current, _this.componentNode, _this.props.outsideClickIgnoreClass) !== document) { + return; + } + + _this.__outsideClickHandler(event); + }; + + events.forEach(function (eventName) { + document.addEventListener(eventName, handlersMap[_this._uid], getEventHandlerOptions(_assertThisInitialized$1(_this), eventName)); + }); + }; + + _this.disableOnClickOutside = function () { + delete enabledInstances[_this._uid]; + var fn = handlersMap[_this._uid]; + + if (fn && typeof document !== 'undefined') { + var events = _this.props.eventTypes; + + if (!events.forEach) { + events = [events]; + } + + events.forEach(function (eventName) { + return document.removeEventListener(eventName, fn, getEventHandlerOptions(_assertThisInitialized$1(_this), eventName)); + }); + delete handlersMap[_this._uid]; + } + }; + + _this.getRef = function (ref) { + return _this.instanceRef = ref; + }; + + _this._uid = uid(); + return _this; + } + /** + * Access the WrappedComponent's instance. + */ + + + var _proto = onClickOutside.prototype; + + _proto.getInstance = function getInstance() { + if (WrappedComponent.prototype && !WrappedComponent.prototype.isReactComponent) { + return this; + } + + var ref = this.instanceRef; + return ref.getInstance ? ref.getInstance() : ref; + }; + + /** + * Add click listeners to the current document, + * linked to this component's state. + */ + _proto.componentDidMount = function componentDidMount() { + // If we are in an environment without a DOM such + // as shallow rendering or snapshots then we exit + // early to prevent any unhandled errors being thrown. + if (typeof document === 'undefined' || !document.createElement) { + return; + } + + var instance = this.getInstance(); + + if (config && typeof config.handleClickOutside === 'function') { + this.__clickOutsideHandlerProp = config.handleClickOutside(instance); + + if (typeof this.__clickOutsideHandlerProp !== 'function') { + throw new Error("WrappedComponent: " + componentName + " lacks a function for processing outside click events specified by the handleClickOutside config option."); + } + } + + this.componentNode = this.__getComponentNode(); // return early so we dont initiate onClickOutside + + if (this.props.disableOnClickOutside) return; + this.enableOnClickOutside(); + }; + + _proto.componentDidUpdate = function componentDidUpdate() { + this.componentNode = this.__getComponentNode(); + } + /** + * Remove all document's event listeners for this component + */ + ; + + _proto.componentWillUnmount = function componentWillUnmount() { + this.disableOnClickOutside(); + } + /** + * Can be called to explicitly enable event listening + * for clicks and touches outside of this element. + */ + ; + + /** + * Pass-through render + */ + _proto.render = function render() { + // eslint-disable-next-line no-unused-vars + var _this$props = this.props; + _this$props.excludeScrollbar; + var props = _objectWithoutPropertiesLoose$1(_this$props, ["excludeScrollbar"]); + + if (WrappedComponent.prototype && WrappedComponent.prototype.isReactComponent) { + props.ref = this.getRef; + } else { + props.wrappedRef = this.getRef; + } + + props.disableOnClickOutside = this.disableOnClickOutside; + props.enableOnClickOutside = this.enableOnClickOutside; + return reactExports.createElement(WrappedComponent, props); + }; + + return onClickOutside; + }(reactExports.Component), _class.displayName = "OnClickOutside(" + componentName + ")", _class.defaultProps = { + eventTypes: ['mousedown', 'touchstart'], + excludeScrollbar: config && config.excludeScrollbar || false, + outsideClickIgnoreClass: IGNORE_CLASS_NAME, + preventDefault: false, + stopPropagation: false + }, _class.getClass = function () { + return WrappedComponent.getClass ? WrappedComponent.getClass() : WrappedComponent; + }, _temp; +} + +var ManagerReferenceNodeContext = reactExports.createContext(); +var ManagerReferenceNodeSetterContext = reactExports.createContext(); +function Manager(_ref) { + var children = _ref.children; + + var _React$useState = reactExports.useState(null), + referenceNode = _React$useState[0], + setReferenceNode = _React$useState[1]; + + var hasUnmounted = reactExports.useRef(false); + reactExports.useEffect(function () { + return function () { + hasUnmounted.current = true; + }; + }, []); + var handleSetReferenceNode = reactExports.useCallback(function (node) { + if (!hasUnmounted.current) { + setReferenceNode(node); + } + }, []); + return /*#__PURE__*/reactExports.createElement(ManagerReferenceNodeContext.Provider, { + value: referenceNode + }, /*#__PURE__*/reactExports.createElement(ManagerReferenceNodeSetterContext.Provider, { + value: handleSetReferenceNode + }, children)); +} + +/** + * Takes an argument and if it's an array, returns the first item in the array, + * otherwise returns the argument. Used for Preact compatibility. + */ +var unwrapArray = function unwrapArray(arg) { + return Array.isArray(arg) ? arg[0] : arg; +}; +/** + * Takes a maybe-undefined function and arbitrary args and invokes the function + * only if it is defined. + */ + +var safeInvoke = function safeInvoke(fn) { + if (typeof fn === 'function') { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + return fn.apply(void 0, args); + } +}; +/** + * Sets a ref using either a ref callback or a ref object + */ + +var setRef = function setRef(ref, node) { + // if its a function call it + if (typeof ref === 'function') { + return safeInvoke(ref, node); + } // otherwise we should treat it as a ref object + else if (ref != null) { + ref.current = node; + } +}; +/** + * Simple ponyfill for Object.fromEntries + */ + +var fromEntries = function fromEntries(entries) { + return entries.reduce(function (acc, _ref) { + var key = _ref[0], + value = _ref[1]; + acc[key] = value; + return acc; + }, {}); +}; +/** + * Small wrapper around `useLayoutEffect` to get rid of the warning on SSR envs + */ + +var useIsomorphicLayoutEffect = typeof window !== 'undefined' && window.document && window.document.createElement ? reactExports.useLayoutEffect : reactExports.useEffect; + +var top = 'top'; +var bottom = 'bottom'; +var right = 'right'; +var left = 'left'; +var auto = 'auto'; +var basePlacements = [top, bottom, right, left]; +var start = 'start'; +var end = 'end'; +var clippingParents = 'clippingParents'; +var viewport = 'viewport'; +var popper = 'popper'; +var reference = 'reference'; +var variationPlacements = /*#__PURE__*/basePlacements.reduce(function (acc, placement) { + return acc.concat([placement + "-" + start, placement + "-" + end]); +}, []); +var placements = /*#__PURE__*/[].concat(basePlacements, [auto]).reduce(function (acc, placement) { + return acc.concat([placement, placement + "-" + start, placement + "-" + end]); +}, []); // modifiers that need to read the DOM + +var beforeRead = 'beforeRead'; +var read = 'read'; +var afterRead = 'afterRead'; // pure-logic modifiers + +var beforeMain = 'beforeMain'; +var main = 'main'; +var afterMain = 'afterMain'; // modifier with the purpose to write to the DOM (or write into a framework state) + +var beforeWrite = 'beforeWrite'; +var write = 'write'; +var afterWrite = 'afterWrite'; +var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite]; + +function getNodeName(element) { + return element ? (element.nodeName || '').toLowerCase() : null; +} + +function getWindow(node) { + if (node == null) { + return window; + } + + if (node.toString() !== '[object Window]') { + var ownerDocument = node.ownerDocument; + return ownerDocument ? ownerDocument.defaultView || window : window; + } + + return node; +} + +function isElement(node) { + var OwnElement = getWindow(node).Element; + return node instanceof OwnElement || node instanceof Element; +} + +function isHTMLElement(node) { + var OwnElement = getWindow(node).HTMLElement; + return node instanceof OwnElement || node instanceof HTMLElement; +} + +function isShadowRoot(node) { + // IE 11 has no ShadowRoot + if (typeof ShadowRoot === 'undefined') { + return false; + } + + var OwnElement = getWindow(node).ShadowRoot; + return node instanceof OwnElement || node instanceof ShadowRoot; +} + +// and applies them to the HTMLElements such as popper and arrow + +function applyStyles(_ref) { + var state = _ref.state; + Object.keys(state.elements).forEach(function (name) { + var style = state.styles[name] || {}; + var attributes = state.attributes[name] || {}; + var element = state.elements[name]; // arrow is optional + virtual elements + + if (!isHTMLElement(element) || !getNodeName(element)) { + return; + } // Flow doesn't support to extend this property, but it's the most + // effective way to apply styles to an HTMLElement + // $FlowFixMe[cannot-write] + + + Object.assign(element.style, style); + Object.keys(attributes).forEach(function (name) { + var value = attributes[name]; + + if (value === false) { + element.removeAttribute(name); + } else { + element.setAttribute(name, value === true ? '' : value); + } + }); + }); +} + +function effect$2(_ref2) { + var state = _ref2.state; + var initialStyles = { + popper: { + position: state.options.strategy, + left: '0', + top: '0', + margin: '0' + }, + arrow: { + position: 'absolute' + }, + reference: {} + }; + Object.assign(state.elements.popper.style, initialStyles.popper); + state.styles = initialStyles; + + if (state.elements.arrow) { + Object.assign(state.elements.arrow.style, initialStyles.arrow); + } + + return function () { + Object.keys(state.elements).forEach(function (name) { + var element = state.elements[name]; + var attributes = state.attributes[name] || {}; + var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]); // Set all values to an empty string to unset them + + var style = styleProperties.reduce(function (style, property) { + style[property] = ''; + return style; + }, {}); // arrow is optional + virtual elements + + if (!isHTMLElement(element) || !getNodeName(element)) { + return; + } + + Object.assign(element.style, style); + Object.keys(attributes).forEach(function (attribute) { + element.removeAttribute(attribute); + }); + }); + }; +} // eslint-disable-next-line import/no-unused-modules + + +var applyStyles$1 = { + name: 'applyStyles', + enabled: true, + phase: 'write', + fn: applyStyles, + effect: effect$2, + requires: ['computeStyles'] +}; + +function getBasePlacement(placement) { + return placement.split('-')[0]; +} + +var max = Math.max; +var min = Math.min; +var round = Math.round; + +function getUAString() { + var uaData = navigator.userAgentData; + + if (uaData != null && uaData.brands && Array.isArray(uaData.brands)) { + return uaData.brands.map(function (item) { + return item.brand + "/" + item.version; + }).join(' '); + } + + return navigator.userAgent; +} + +function isLayoutViewport() { + return !/^((?!chrome|android).)*safari/i.test(getUAString()); +} + +function getBoundingClientRect(element, includeScale, isFixedStrategy) { + if (includeScale === void 0) { + includeScale = false; + } + + if (isFixedStrategy === void 0) { + isFixedStrategy = false; + } + + var clientRect = element.getBoundingClientRect(); + var scaleX = 1; + var scaleY = 1; + + if (includeScale && isHTMLElement(element)) { + scaleX = element.offsetWidth > 0 ? round(clientRect.width) / element.offsetWidth || 1 : 1; + scaleY = element.offsetHeight > 0 ? round(clientRect.height) / element.offsetHeight || 1 : 1; + } + + var _ref = isElement(element) ? getWindow(element) : window, + visualViewport = _ref.visualViewport; + + var addVisualOffsets = !isLayoutViewport() && isFixedStrategy; + var x = (clientRect.left + (addVisualOffsets && visualViewport ? visualViewport.offsetLeft : 0)) / scaleX; + var y = (clientRect.top + (addVisualOffsets && visualViewport ? visualViewport.offsetTop : 0)) / scaleY; + var width = clientRect.width / scaleX; + var height = clientRect.height / scaleY; + return { + width: width, + height: height, + top: y, + right: x + width, + bottom: y + height, + left: x, + x: x, + y: y + }; +} + +// means it doesn't take into account transforms. + +function getLayoutRect(element) { + var clientRect = getBoundingClientRect(element); // Use the clientRect sizes if it's not been transformed. + // Fixes https://github.com/popperjs/popper-core/issues/1223 + + var width = element.offsetWidth; + var height = element.offsetHeight; + + if (Math.abs(clientRect.width - width) <= 1) { + width = clientRect.width; + } + + if (Math.abs(clientRect.height - height) <= 1) { + height = clientRect.height; + } + + return { + x: element.offsetLeft, + y: element.offsetTop, + width: width, + height: height + }; +} + +function contains(parent, child) { + var rootNode = child.getRootNode && child.getRootNode(); // First, attempt with faster native method + + if (parent.contains(child)) { + return true; + } // then fallback to custom implementation with Shadow DOM support + else if (rootNode && isShadowRoot(rootNode)) { + var next = child; + + do { + if (next && parent.isSameNode(next)) { + return true; + } // $FlowFixMe[prop-missing]: need a better way to handle this... + + + next = next.parentNode || next.host; + } while (next); + } // Give up, the result is false + + + return false; +} + +function getComputedStyle$1(element) { + return getWindow(element).getComputedStyle(element); +} + +function isTableElement(element) { + return ['table', 'td', 'th'].indexOf(getNodeName(element)) >= 0; +} + +function getDocumentElement(element) { + // $FlowFixMe[incompatible-return]: assume body is always available + return ((isElement(element) ? element.ownerDocument : // $FlowFixMe[prop-missing] + element.document) || window.document).documentElement; +} + +function getParentNode(element) { + if (getNodeName(element) === 'html') { + return element; + } + + return (// this is a quicker (but less type safe) way to save quite some bytes from the bundle + // $FlowFixMe[incompatible-return] + // $FlowFixMe[prop-missing] + element.assignedSlot || // step into the shadow DOM of the parent of a slotted node + element.parentNode || ( // DOM Element detected + isShadowRoot(element) ? element.host : null) || // ShadowRoot detected + // $FlowFixMe[incompatible-call]: HTMLElement is a Node + getDocumentElement(element) // fallback + + ); +} + +function getTrueOffsetParent(element) { + if (!isHTMLElement(element) || // https://github.com/popperjs/popper-core/issues/837 + getComputedStyle$1(element).position === 'fixed') { + return null; + } + + return element.offsetParent; +} // `.offsetParent` reports `null` for fixed elements, while absolute elements +// return the containing block + + +function getContainingBlock(element) { + var isFirefox = /firefox/i.test(getUAString()); + var isIE = /Trident/i.test(getUAString()); + + if (isIE && isHTMLElement(element)) { + // In IE 9, 10 and 11 fixed elements containing block is always established by the viewport + var elementCss = getComputedStyle$1(element); + + if (elementCss.position === 'fixed') { + return null; + } + } + + var currentNode = getParentNode(element); + + if (isShadowRoot(currentNode)) { + currentNode = currentNode.host; + } + + while (isHTMLElement(currentNode) && ['html', 'body'].indexOf(getNodeName(currentNode)) < 0) { + var css = getComputedStyle$1(currentNode); // This is non-exhaustive but covers the most common CSS properties that + // create a containing block. + // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block + + if (css.transform !== 'none' || css.perspective !== 'none' || css.contain === 'paint' || ['transform', 'perspective'].indexOf(css.willChange) !== -1 || isFirefox && css.willChange === 'filter' || isFirefox && css.filter && css.filter !== 'none') { + return currentNode; + } else { + currentNode = currentNode.parentNode; + } + } + + return null; +} // Gets the closest ancestor positioned element. Handles some edge cases, +// such as table ancestors and cross browser bugs. + + +function getOffsetParent(element) { + var window = getWindow(element); + var offsetParent = getTrueOffsetParent(element); + + while (offsetParent && isTableElement(offsetParent) && getComputedStyle$1(offsetParent).position === 'static') { + offsetParent = getTrueOffsetParent(offsetParent); + } + + if (offsetParent && (getNodeName(offsetParent) === 'html' || getNodeName(offsetParent) === 'body' && getComputedStyle$1(offsetParent).position === 'static')) { + return window; + } + + return offsetParent || getContainingBlock(element) || window; +} + +function getMainAxisFromPlacement(placement) { + return ['top', 'bottom'].indexOf(placement) >= 0 ? 'x' : 'y'; +} + +function within(min$1, value, max$1) { + return max(min$1, min(value, max$1)); +} +function withinMaxClamp(min, value, max) { + var v = within(min, value, max); + return v > max ? max : v; +} + +function getFreshSideObject() { + return { + top: 0, + right: 0, + bottom: 0, + left: 0 + }; +} + +function mergePaddingObject(paddingObject) { + return Object.assign({}, getFreshSideObject(), paddingObject); +} + +function expandToHashMap(value, keys) { + return keys.reduce(function (hashMap, key) { + hashMap[key] = value; + return hashMap; + }, {}); +} + +var toPaddingObject = function toPaddingObject(padding, state) { + padding = typeof padding === 'function' ? padding(Object.assign({}, state.rects, { + placement: state.placement + })) : padding; + return mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements)); +}; + +function arrow(_ref) { + var _state$modifiersData$; + + var state = _ref.state, + name = _ref.name, + options = _ref.options; + var arrowElement = state.elements.arrow; + var popperOffsets = state.modifiersData.popperOffsets; + var basePlacement = getBasePlacement(state.placement); + var axis = getMainAxisFromPlacement(basePlacement); + var isVertical = [left, right].indexOf(basePlacement) >= 0; + var len = isVertical ? 'height' : 'width'; + + if (!arrowElement || !popperOffsets) { + return; + } + + var paddingObject = toPaddingObject(options.padding, state); + var arrowRect = getLayoutRect(arrowElement); + var minProp = axis === 'y' ? top : left; + var maxProp = axis === 'y' ? bottom : right; + var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets[axis] - state.rects.popper[len]; + var startDiff = popperOffsets[axis] - state.rects.reference[axis]; + var arrowOffsetParent = getOffsetParent(arrowElement); + var clientSize = arrowOffsetParent ? axis === 'y' ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0; + var centerToReference = endDiff / 2 - startDiff / 2; // Make sure the arrow doesn't overflow the popper if the center point is + // outside of the popper bounds + + var min = paddingObject[minProp]; + var max = clientSize - arrowRect[len] - paddingObject[maxProp]; + var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference; + var offset = within(min, center, max); // Prevents breaking syntax highlighting... + + var axisProp = axis; + state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset, _state$modifiersData$.centerOffset = offset - center, _state$modifiersData$); +} + +function effect$1(_ref2) { + var state = _ref2.state, + options = _ref2.options; + var _options$element = options.element, + arrowElement = _options$element === void 0 ? '[data-popper-arrow]' : _options$element; + + if (arrowElement == null) { + return; + } // CSS selector + + + if (typeof arrowElement === 'string') { + arrowElement = state.elements.popper.querySelector(arrowElement); + + if (!arrowElement) { + return; + } + } + + if (!contains(state.elements.popper, arrowElement)) { + + return; + } + + state.elements.arrow = arrowElement; +} // eslint-disable-next-line import/no-unused-modules + + +var arrow$1 = { + name: 'arrow', + enabled: true, + phase: 'main', + fn: arrow, + effect: effect$1, + requires: ['popperOffsets'], + requiresIfExists: ['preventOverflow'] +}; + +function getVariation(placement) { + return placement.split('-')[1]; +} + +var unsetSides = { + top: 'auto', + right: 'auto', + bottom: 'auto', + left: 'auto' +}; // Round the offsets to the nearest suitable subpixel based on the DPR. +// Zooming can change the DPR, but it seems to report a value that will +// cleanly divide the values into the appropriate subpixels. + +function roundOffsetsByDPR(_ref, win) { + var x = _ref.x, + y = _ref.y; + var dpr = win.devicePixelRatio || 1; + return { + x: round(x * dpr) / dpr || 0, + y: round(y * dpr) / dpr || 0 + }; +} + +function mapToStyles(_ref2) { + var _Object$assign2; + + var popper = _ref2.popper, + popperRect = _ref2.popperRect, + placement = _ref2.placement, + variation = _ref2.variation, + offsets = _ref2.offsets, + position = _ref2.position, + gpuAcceleration = _ref2.gpuAcceleration, + adaptive = _ref2.adaptive, + roundOffsets = _ref2.roundOffsets, + isFixed = _ref2.isFixed; + var _offsets$x = offsets.x, + x = _offsets$x === void 0 ? 0 : _offsets$x, + _offsets$y = offsets.y, + y = _offsets$y === void 0 ? 0 : _offsets$y; + + var _ref3 = typeof roundOffsets === 'function' ? roundOffsets({ + x: x, + y: y + }) : { + x: x, + y: y + }; + + x = _ref3.x; + y = _ref3.y; + var hasX = offsets.hasOwnProperty('x'); + var hasY = offsets.hasOwnProperty('y'); + var sideX = left; + var sideY = top; + var win = window; + + if (adaptive) { + var offsetParent = getOffsetParent(popper); + var heightProp = 'clientHeight'; + var widthProp = 'clientWidth'; + + if (offsetParent === getWindow(popper)) { + offsetParent = getDocumentElement(popper); + + if (getComputedStyle$1(offsetParent).position !== 'static' && position === 'absolute') { + heightProp = 'scrollHeight'; + widthProp = 'scrollWidth'; + } + } // $FlowFixMe[incompatible-cast]: force type refinement, we compare offsetParent with window above, but Flow doesn't detect it + + + offsetParent = offsetParent; + + if (placement === top || (placement === left || placement === right) && variation === end) { + sideY = bottom; + var offsetY = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.height : // $FlowFixMe[prop-missing] + offsetParent[heightProp]; + y -= offsetY - popperRect.height; + y *= gpuAcceleration ? 1 : -1; + } + + if (placement === left || (placement === top || placement === bottom) && variation === end) { + sideX = right; + var offsetX = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.width : // $FlowFixMe[prop-missing] + offsetParent[widthProp]; + x -= offsetX - popperRect.width; + x *= gpuAcceleration ? 1 : -1; + } + } + + var commonStyles = Object.assign({ + position: position + }, adaptive && unsetSides); + + var _ref4 = roundOffsets === true ? roundOffsetsByDPR({ + x: x, + y: y + }, getWindow(popper)) : { + x: x, + y: y + }; + + x = _ref4.x; + y = _ref4.y; + + if (gpuAcceleration) { + var _Object$assign; + + return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? '0' : '', _Object$assign[sideX] = hasX ? '0' : '', _Object$assign.transform = (win.devicePixelRatio || 1) <= 1 ? "translate(" + x + "px, " + y + "px)" : "translate3d(" + x + "px, " + y + "px, 0)", _Object$assign)); + } + + return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + "px" : '', _Object$assign2[sideX] = hasX ? x + "px" : '', _Object$assign2.transform = '', _Object$assign2)); +} + +function computeStyles(_ref5) { + var state = _ref5.state, + options = _ref5.options; + var _options$gpuAccelerat = options.gpuAcceleration, + gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat, + _options$adaptive = options.adaptive, + adaptive = _options$adaptive === void 0 ? true : _options$adaptive, + _options$roundOffsets = options.roundOffsets, + roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets; + + var commonStyles = { + placement: getBasePlacement(state.placement), + variation: getVariation(state.placement), + popper: state.elements.popper, + popperRect: state.rects.popper, + gpuAcceleration: gpuAcceleration, + isFixed: state.options.strategy === 'fixed' + }; + + if (state.modifiersData.popperOffsets != null) { + state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(Object.assign({}, commonStyles, { + offsets: state.modifiersData.popperOffsets, + position: state.options.strategy, + adaptive: adaptive, + roundOffsets: roundOffsets + }))); + } + + if (state.modifiersData.arrow != null) { + state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, { + offsets: state.modifiersData.arrow, + position: 'absolute', + adaptive: false, + roundOffsets: roundOffsets + }))); + } + + state.attributes.popper = Object.assign({}, state.attributes.popper, { + 'data-popper-placement': state.placement + }); +} // eslint-disable-next-line import/no-unused-modules + + +var computeStyles$1 = { + name: 'computeStyles', + enabled: true, + phase: 'beforeWrite', + fn: computeStyles, + data: {} +}; + +var passive = { + passive: true +}; + +function effect(_ref) { + var state = _ref.state, + instance = _ref.instance, + options = _ref.options; + var _options$scroll = options.scroll, + scroll = _options$scroll === void 0 ? true : _options$scroll, + _options$resize = options.resize, + resize = _options$resize === void 0 ? true : _options$resize; + var window = getWindow(state.elements.popper); + var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper); + + if (scroll) { + scrollParents.forEach(function (scrollParent) { + scrollParent.addEventListener('scroll', instance.update, passive); + }); + } + + if (resize) { + window.addEventListener('resize', instance.update, passive); + } + + return function () { + if (scroll) { + scrollParents.forEach(function (scrollParent) { + scrollParent.removeEventListener('scroll', instance.update, passive); + }); + } + + if (resize) { + window.removeEventListener('resize', instance.update, passive); + } + }; +} // eslint-disable-next-line import/no-unused-modules + + +var eventListeners = { + name: 'eventListeners', + enabled: true, + phase: 'write', + fn: function fn() {}, + effect: effect, + data: {} +}; + +var hash$1 = { + left: 'right', + right: 'left', + bottom: 'top', + top: 'bottom' +}; +function getOppositePlacement(placement) { + return placement.replace(/left|right|bottom|top/g, function (matched) { + return hash$1[matched]; + }); +} + +var hash = { + start: 'end', + end: 'start' +}; +function getOppositeVariationPlacement(placement) { + return placement.replace(/start|end/g, function (matched) { + return hash[matched]; + }); +} + +function getWindowScroll(node) { + var win = getWindow(node); + var scrollLeft = win.pageXOffset; + var scrollTop = win.pageYOffset; + return { + scrollLeft: scrollLeft, + scrollTop: scrollTop + }; +} + +function getWindowScrollBarX(element) { + // If has a CSS width greater than the viewport, then this will be + // incorrect for RTL. + // Popper 1 is broken in this case and never had a bug report so let's assume + // it's not an issue. I don't think anyone ever specifies width on + // anyway. + // Browsers where the left scrollbar doesn't cause an issue report `0` for + // this (e.g. Edge 2019, IE11, Safari) + return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft; +} + +function getViewportRect(element, strategy) { + var win = getWindow(element); + var html = getDocumentElement(element); + var visualViewport = win.visualViewport; + var width = html.clientWidth; + var height = html.clientHeight; + var x = 0; + var y = 0; + + if (visualViewport) { + width = visualViewport.width; + height = visualViewport.height; + var layoutViewport = isLayoutViewport(); + + if (layoutViewport || !layoutViewport && strategy === 'fixed') { + x = visualViewport.offsetLeft; + y = visualViewport.offsetTop; + } + } + + return { + width: width, + height: height, + x: x + getWindowScrollBarX(element), + y: y + }; +} + +// of the `` and `` rect bounds if horizontally scrollable + +function getDocumentRect(element) { + var _element$ownerDocumen; + + var html = getDocumentElement(element); + var winScroll = getWindowScroll(element); + var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body; + var width = max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0); + var height = max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0); + var x = -winScroll.scrollLeft + getWindowScrollBarX(element); + var y = -winScroll.scrollTop; + + if (getComputedStyle$1(body || html).direction === 'rtl') { + x += max(html.clientWidth, body ? body.clientWidth : 0) - width; + } + + return { + width: width, + height: height, + x: x, + y: y + }; +} + +function isScrollParent(element) { + // Firefox wants us to check `-x` and `-y` variations as well + var _getComputedStyle = getComputedStyle$1(element), + overflow = _getComputedStyle.overflow, + overflowX = _getComputedStyle.overflowX, + overflowY = _getComputedStyle.overflowY; + + return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX); +} + +function getScrollParent(node) { + if (['html', 'body', '#document'].indexOf(getNodeName(node)) >= 0) { + // $FlowFixMe[incompatible-return]: assume body is always available + return node.ownerDocument.body; + } + + if (isHTMLElement(node) && isScrollParent(node)) { + return node; + } + + return getScrollParent(getParentNode(node)); +} + +/* +given a DOM element, return the list of all scroll parents, up the list of ancesors +until we get to the top window object. This list is what we attach scroll listeners +to, because if any of these parent elements scroll, we'll need to re-calculate the +reference element's position. +*/ + +function listScrollParents(element, list) { + var _element$ownerDocumen; + + if (list === void 0) { + list = []; + } + + var scrollParent = getScrollParent(element); + var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body); + var win = getWindow(scrollParent); + var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent; + var updatedList = list.concat(target); + return isBody ? updatedList : // $FlowFixMe[incompatible-call]: isBody tells us target will be an HTMLElement here + updatedList.concat(listScrollParents(getParentNode(target))); +} + +function rectToClientRect(rect) { + return Object.assign({}, rect, { + left: rect.x, + top: rect.y, + right: rect.x + rect.width, + bottom: rect.y + rect.height + }); +} + +function getInnerBoundingClientRect(element, strategy) { + var rect = getBoundingClientRect(element, false, strategy === 'fixed'); + rect.top = rect.top + element.clientTop; + rect.left = rect.left + element.clientLeft; + rect.bottom = rect.top + element.clientHeight; + rect.right = rect.left + element.clientWidth; + rect.width = element.clientWidth; + rect.height = element.clientHeight; + rect.x = rect.left; + rect.y = rect.top; + return rect; +} + +function getClientRectFromMixedType(element, clippingParent, strategy) { + return clippingParent === viewport ? rectToClientRect(getViewportRect(element, strategy)) : isElement(clippingParent) ? getInnerBoundingClientRect(clippingParent, strategy) : rectToClientRect(getDocumentRect(getDocumentElement(element))); +} // A "clipping parent" is an overflowable container with the characteristic of +// clipping (or hiding) overflowing elements with a position different from +// `initial` + + +function getClippingParents(element) { + var clippingParents = listScrollParents(getParentNode(element)); + var canEscapeClipping = ['absolute', 'fixed'].indexOf(getComputedStyle$1(element).position) >= 0; + var clipperElement = canEscapeClipping && isHTMLElement(element) ? getOffsetParent(element) : element; + + if (!isElement(clipperElement)) { + return []; + } // $FlowFixMe[incompatible-return]: https://github.com/facebook/flow/issues/1414 + + + return clippingParents.filter(function (clippingParent) { + return isElement(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== 'body'; + }); +} // Gets the maximum area that the element is visible in due to any number of +// clipping parents + + +function getClippingRect(element, boundary, rootBoundary, strategy) { + var mainClippingParents = boundary === 'clippingParents' ? getClippingParents(element) : [].concat(boundary); + var clippingParents = [].concat(mainClippingParents, [rootBoundary]); + var firstClippingParent = clippingParents[0]; + var clippingRect = clippingParents.reduce(function (accRect, clippingParent) { + var rect = getClientRectFromMixedType(element, clippingParent, strategy); + accRect.top = max(rect.top, accRect.top); + accRect.right = min(rect.right, accRect.right); + accRect.bottom = min(rect.bottom, accRect.bottom); + accRect.left = max(rect.left, accRect.left); + return accRect; + }, getClientRectFromMixedType(element, firstClippingParent, strategy)); + clippingRect.width = clippingRect.right - clippingRect.left; + clippingRect.height = clippingRect.bottom - clippingRect.top; + clippingRect.x = clippingRect.left; + clippingRect.y = clippingRect.top; + return clippingRect; +} + +function computeOffsets(_ref) { + var reference = _ref.reference, + element = _ref.element, + placement = _ref.placement; + var basePlacement = placement ? getBasePlacement(placement) : null; + var variation = placement ? getVariation(placement) : null; + var commonX = reference.x + reference.width / 2 - element.width / 2; + var commonY = reference.y + reference.height / 2 - element.height / 2; + var offsets; + + switch (basePlacement) { + case top: + offsets = { + x: commonX, + y: reference.y - element.height + }; + break; + + case bottom: + offsets = { + x: commonX, + y: reference.y + reference.height + }; + break; + + case right: + offsets = { + x: reference.x + reference.width, + y: commonY + }; + break; + + case left: + offsets = { + x: reference.x - element.width, + y: commonY + }; + break; + + default: + offsets = { + x: reference.x, + y: reference.y + }; + } + + var mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null; + + if (mainAxis != null) { + var len = mainAxis === 'y' ? 'height' : 'width'; + + switch (variation) { + case start: + offsets[mainAxis] = offsets[mainAxis] - (reference[len] / 2 - element[len] / 2); + break; + + case end: + offsets[mainAxis] = offsets[mainAxis] + (reference[len] / 2 - element[len] / 2); + break; + } + } + + return offsets; +} + +function detectOverflow(state, options) { + if (options === void 0) { + options = {}; + } + + var _options = options, + _options$placement = _options.placement, + placement = _options$placement === void 0 ? state.placement : _options$placement, + _options$strategy = _options.strategy, + strategy = _options$strategy === void 0 ? state.strategy : _options$strategy, + _options$boundary = _options.boundary, + boundary = _options$boundary === void 0 ? clippingParents : _options$boundary, + _options$rootBoundary = _options.rootBoundary, + rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary, + _options$elementConte = _options.elementContext, + elementContext = _options$elementConte === void 0 ? popper : _options$elementConte, + _options$altBoundary = _options.altBoundary, + altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary, + _options$padding = _options.padding, + padding = _options$padding === void 0 ? 0 : _options$padding; + var paddingObject = mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements)); + var altContext = elementContext === popper ? reference : popper; + var popperRect = state.rects.popper; + var element = state.elements[altBoundary ? altContext : elementContext]; + var clippingClientRect = getClippingRect(isElement(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary, strategy); + var referenceClientRect = getBoundingClientRect(state.elements.reference); + var popperOffsets = computeOffsets({ + reference: referenceClientRect, + element: popperRect, + strategy: 'absolute', + placement: placement + }); + var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets)); + var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect; // positive = overflowing the clipping rect + // 0 or negative = within the clipping rect + + var overflowOffsets = { + top: clippingClientRect.top - elementClientRect.top + paddingObject.top, + bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom, + left: clippingClientRect.left - elementClientRect.left + paddingObject.left, + right: elementClientRect.right - clippingClientRect.right + paddingObject.right + }; + var offsetData = state.modifiersData.offset; // Offsets can be applied only to the popper element + + if (elementContext === popper && offsetData) { + var offset = offsetData[placement]; + Object.keys(overflowOffsets).forEach(function (key) { + var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1; + var axis = [top, bottom].indexOf(key) >= 0 ? 'y' : 'x'; + overflowOffsets[key] += offset[axis] * multiply; + }); + } + + return overflowOffsets; +} + +function computeAutoPlacement(state, options) { + if (options === void 0) { + options = {}; + } + + var _options = options, + placement = _options.placement, + boundary = _options.boundary, + rootBoundary = _options.rootBoundary, + padding = _options.padding, + flipVariations = _options.flipVariations, + _options$allowedAutoP = _options.allowedAutoPlacements, + allowedAutoPlacements = _options$allowedAutoP === void 0 ? placements : _options$allowedAutoP; + var variation = getVariation(placement); + var placements$1 = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function (placement) { + return getVariation(placement) === variation; + }) : basePlacements; + var allowedPlacements = placements$1.filter(function (placement) { + return allowedAutoPlacements.indexOf(placement) >= 0; + }); + + if (allowedPlacements.length === 0) { + allowedPlacements = placements$1; + } // $FlowFixMe[incompatible-type]: Flow seems to have problems with two array unions... + + + var overflows = allowedPlacements.reduce(function (acc, placement) { + acc[placement] = detectOverflow(state, { + placement: placement, + boundary: boundary, + rootBoundary: rootBoundary, + padding: padding + })[getBasePlacement(placement)]; + return acc; + }, {}); + return Object.keys(overflows).sort(function (a, b) { + return overflows[a] - overflows[b]; + }); +} + +function getExpandedFallbackPlacements(placement) { + if (getBasePlacement(placement) === auto) { + return []; + } + + var oppositePlacement = getOppositePlacement(placement); + return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)]; +} + +function flip(_ref) { + var state = _ref.state, + options = _ref.options, + name = _ref.name; + + if (state.modifiersData[name]._skip) { + return; + } + + var _options$mainAxis = options.mainAxis, + checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, + _options$altAxis = options.altAxis, + checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis, + specifiedFallbackPlacements = options.fallbackPlacements, + padding = options.padding, + boundary = options.boundary, + rootBoundary = options.rootBoundary, + altBoundary = options.altBoundary, + _options$flipVariatio = options.flipVariations, + flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio, + allowedAutoPlacements = options.allowedAutoPlacements; + var preferredPlacement = state.options.placement; + var basePlacement = getBasePlacement(preferredPlacement); + var isBasePlacement = basePlacement === preferredPlacement; + var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement)); + var placements = [preferredPlacement].concat(fallbackPlacements).reduce(function (acc, placement) { + return acc.concat(getBasePlacement(placement) === auto ? computeAutoPlacement(state, { + placement: placement, + boundary: boundary, + rootBoundary: rootBoundary, + padding: padding, + flipVariations: flipVariations, + allowedAutoPlacements: allowedAutoPlacements + }) : placement); + }, []); + var referenceRect = state.rects.reference; + var popperRect = state.rects.popper; + var checksMap = new Map(); + var makeFallbackChecks = true; + var firstFittingPlacement = placements[0]; + + for (var i = 0; i < placements.length; i++) { + var placement = placements[i]; + + var _basePlacement = getBasePlacement(placement); + + var isStartVariation = getVariation(placement) === start; + var isVertical = [top, bottom].indexOf(_basePlacement) >= 0; + var len = isVertical ? 'width' : 'height'; + var overflow = detectOverflow(state, { + placement: placement, + boundary: boundary, + rootBoundary: rootBoundary, + altBoundary: altBoundary, + padding: padding + }); + var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : top; + + if (referenceRect[len] > popperRect[len]) { + mainVariationSide = getOppositePlacement(mainVariationSide); + } + + var altVariationSide = getOppositePlacement(mainVariationSide); + var checks = []; + + if (checkMainAxis) { + checks.push(overflow[_basePlacement] <= 0); + } + + if (checkAltAxis) { + checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0); + } + + if (checks.every(function (check) { + return check; + })) { + firstFittingPlacement = placement; + makeFallbackChecks = false; + break; + } + + checksMap.set(placement, checks); + } + + if (makeFallbackChecks) { + // `2` may be desired in some cases – research later + var numberOfChecks = flipVariations ? 3 : 1; + + var _loop = function _loop(_i) { + var fittingPlacement = placements.find(function (placement) { + var checks = checksMap.get(placement); + + if (checks) { + return checks.slice(0, _i).every(function (check) { + return check; + }); + } + }); + + if (fittingPlacement) { + firstFittingPlacement = fittingPlacement; + return "break"; + } + }; + + for (var _i = numberOfChecks; _i > 0; _i--) { + var _ret = _loop(_i); + + if (_ret === "break") break; + } + } + + if (state.placement !== firstFittingPlacement) { + state.modifiersData[name]._skip = true; + state.placement = firstFittingPlacement; + state.reset = true; + } +} // eslint-disable-next-line import/no-unused-modules + + +var flip$1 = { + name: 'flip', + enabled: true, + phase: 'main', + fn: flip, + requiresIfExists: ['offset'], + data: { + _skip: false + } +}; + +function getSideOffsets(overflow, rect, preventedOffsets) { + if (preventedOffsets === void 0) { + preventedOffsets = { + x: 0, + y: 0 + }; + } + + return { + top: overflow.top - rect.height - preventedOffsets.y, + right: overflow.right - rect.width + preventedOffsets.x, + bottom: overflow.bottom - rect.height + preventedOffsets.y, + left: overflow.left - rect.width - preventedOffsets.x + }; +} + +function isAnySideFullyClipped(overflow) { + return [top, right, bottom, left].some(function (side) { + return overflow[side] >= 0; + }); +} + +function hide(_ref) { + var state = _ref.state, + name = _ref.name; + var referenceRect = state.rects.reference; + var popperRect = state.rects.popper; + var preventedOffsets = state.modifiersData.preventOverflow; + var referenceOverflow = detectOverflow(state, { + elementContext: 'reference' + }); + var popperAltOverflow = detectOverflow(state, { + altBoundary: true + }); + var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect); + var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets); + var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets); + var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets); + state.modifiersData[name] = { + referenceClippingOffsets: referenceClippingOffsets, + popperEscapeOffsets: popperEscapeOffsets, + isReferenceHidden: isReferenceHidden, + hasPopperEscaped: hasPopperEscaped + }; + state.attributes.popper = Object.assign({}, state.attributes.popper, { + 'data-popper-reference-hidden': isReferenceHidden, + 'data-popper-escaped': hasPopperEscaped + }); +} // eslint-disable-next-line import/no-unused-modules + + +var hide$1 = { + name: 'hide', + enabled: true, + phase: 'main', + requiresIfExists: ['preventOverflow'], + fn: hide +}; + +function distanceAndSkiddingToXY(placement, rects, offset) { + var basePlacement = getBasePlacement(placement); + var invertDistance = [left, top].indexOf(basePlacement) >= 0 ? -1 : 1; + + var _ref = typeof offset === 'function' ? offset(Object.assign({}, rects, { + placement: placement + })) : offset, + skidding = _ref[0], + distance = _ref[1]; + + skidding = skidding || 0; + distance = (distance || 0) * invertDistance; + return [left, right].indexOf(basePlacement) >= 0 ? { + x: distance, + y: skidding + } : { + x: skidding, + y: distance + }; +} + +function offset(_ref2) { + var state = _ref2.state, + options = _ref2.options, + name = _ref2.name; + var _options$offset = options.offset, + offset = _options$offset === void 0 ? [0, 0] : _options$offset; + var data = placements.reduce(function (acc, placement) { + acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset); + return acc; + }, {}); + var _data$state$placement = data[state.placement], + x = _data$state$placement.x, + y = _data$state$placement.y; + + if (state.modifiersData.popperOffsets != null) { + state.modifiersData.popperOffsets.x += x; + state.modifiersData.popperOffsets.y += y; + } + + state.modifiersData[name] = data; +} // eslint-disable-next-line import/no-unused-modules + + +var offset$1 = { + name: 'offset', + enabled: true, + phase: 'main', + requires: ['popperOffsets'], + fn: offset +}; + +function popperOffsets(_ref) { + var state = _ref.state, + name = _ref.name; + // Offsets are the actual position the popper needs to have to be + // properly positioned near its reference element + // This is the most basic placement, and will be adjusted by + // the modifiers in the next step + state.modifiersData[name] = computeOffsets({ + reference: state.rects.reference, + element: state.rects.popper, + strategy: 'absolute', + placement: state.placement + }); +} // eslint-disable-next-line import/no-unused-modules + + +var popperOffsets$1 = { + name: 'popperOffsets', + enabled: true, + phase: 'read', + fn: popperOffsets, + data: {} +}; + +function getAltAxis(axis) { + return axis === 'x' ? 'y' : 'x'; +} + +function preventOverflow(_ref) { + var state = _ref.state, + options = _ref.options, + name = _ref.name; + var _options$mainAxis = options.mainAxis, + checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, + _options$altAxis = options.altAxis, + checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis, + boundary = options.boundary, + rootBoundary = options.rootBoundary, + altBoundary = options.altBoundary, + padding = options.padding, + _options$tether = options.tether, + tether = _options$tether === void 0 ? true : _options$tether, + _options$tetherOffset = options.tetherOffset, + tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset; + var overflow = detectOverflow(state, { + boundary: boundary, + rootBoundary: rootBoundary, + padding: padding, + altBoundary: altBoundary + }); + var basePlacement = getBasePlacement(state.placement); + var variation = getVariation(state.placement); + var isBasePlacement = !variation; + var mainAxis = getMainAxisFromPlacement(basePlacement); + var altAxis = getAltAxis(mainAxis); + var popperOffsets = state.modifiersData.popperOffsets; + var referenceRect = state.rects.reference; + var popperRect = state.rects.popper; + var tetherOffsetValue = typeof tetherOffset === 'function' ? tetherOffset(Object.assign({}, state.rects, { + placement: state.placement + })) : tetherOffset; + var normalizedTetherOffsetValue = typeof tetherOffsetValue === 'number' ? { + mainAxis: tetherOffsetValue, + altAxis: tetherOffsetValue + } : Object.assign({ + mainAxis: 0, + altAxis: 0 + }, tetherOffsetValue); + var offsetModifierState = state.modifiersData.offset ? state.modifiersData.offset[state.placement] : null; + var data = { + x: 0, + y: 0 + }; + + if (!popperOffsets) { + return; + } + + if (checkMainAxis) { + var _offsetModifierState$; + + var mainSide = mainAxis === 'y' ? top : left; + var altSide = mainAxis === 'y' ? bottom : right; + var len = mainAxis === 'y' ? 'height' : 'width'; + var offset = popperOffsets[mainAxis]; + var min$1 = offset + overflow[mainSide]; + var max$1 = offset - overflow[altSide]; + var additive = tether ? -popperRect[len] / 2 : 0; + var minLen = variation === start ? referenceRect[len] : popperRect[len]; + var maxLen = variation === start ? -popperRect[len] : -referenceRect[len]; // We need to include the arrow in the calculation so the arrow doesn't go + // outside the reference bounds + + var arrowElement = state.elements.arrow; + var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : { + width: 0, + height: 0 + }; + var arrowPaddingObject = state.modifiersData['arrow#persistent'] ? state.modifiersData['arrow#persistent'].padding : getFreshSideObject(); + var arrowPaddingMin = arrowPaddingObject[mainSide]; + var arrowPaddingMax = arrowPaddingObject[altSide]; // If the reference length is smaller than the arrow length, we don't want + // to include its full size in the calculation. If the reference is small + // and near the edge of a boundary, the popper can overflow even if the + // reference is not overflowing as well (e.g. virtual elements with no + // width or height) + + var arrowLen = within(0, referenceRect[len], arrowRect[len]); + var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis : minLen - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis; + var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis : maxLen + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis; + var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow); + var clientOffset = arrowOffsetParent ? mainAxis === 'y' ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0; + var offsetModifierValue = (_offsetModifierState$ = offsetModifierState == null ? void 0 : offsetModifierState[mainAxis]) != null ? _offsetModifierState$ : 0; + var tetherMin = offset + minOffset - offsetModifierValue - clientOffset; + var tetherMax = offset + maxOffset - offsetModifierValue; + var preventedOffset = within(tether ? min(min$1, tetherMin) : min$1, offset, tether ? max(max$1, tetherMax) : max$1); + popperOffsets[mainAxis] = preventedOffset; + data[mainAxis] = preventedOffset - offset; + } + + if (checkAltAxis) { + var _offsetModifierState$2; + + var _mainSide = mainAxis === 'x' ? top : left; + + var _altSide = mainAxis === 'x' ? bottom : right; + + var _offset = popperOffsets[altAxis]; + + var _len = altAxis === 'y' ? 'height' : 'width'; + + var _min = _offset + overflow[_mainSide]; + + var _max = _offset - overflow[_altSide]; + + var isOriginSide = [top, left].indexOf(basePlacement) !== -1; + + var _offsetModifierValue = (_offsetModifierState$2 = offsetModifierState == null ? void 0 : offsetModifierState[altAxis]) != null ? _offsetModifierState$2 : 0; + + var _tetherMin = isOriginSide ? _min : _offset - referenceRect[_len] - popperRect[_len] - _offsetModifierValue + normalizedTetherOffsetValue.altAxis; + + var _tetherMax = isOriginSide ? _offset + referenceRect[_len] + popperRect[_len] - _offsetModifierValue - normalizedTetherOffsetValue.altAxis : _max; + + var _preventedOffset = tether && isOriginSide ? withinMaxClamp(_tetherMin, _offset, _tetherMax) : within(tether ? _tetherMin : _min, _offset, tether ? _tetherMax : _max); + + popperOffsets[altAxis] = _preventedOffset; + data[altAxis] = _preventedOffset - _offset; + } + + state.modifiersData[name] = data; +} // eslint-disable-next-line import/no-unused-modules + + +var preventOverflow$1 = { + name: 'preventOverflow', + enabled: true, + phase: 'main', + fn: preventOverflow, + requiresIfExists: ['offset'] +}; + +function getHTMLElementScroll(element) { + return { + scrollLeft: element.scrollLeft, + scrollTop: element.scrollTop + }; +} + +function getNodeScroll(node) { + if (node === getWindow(node) || !isHTMLElement(node)) { + return getWindowScroll(node); + } else { + return getHTMLElementScroll(node); + } +} + +function isElementScaled(element) { + var rect = element.getBoundingClientRect(); + var scaleX = round(rect.width) / element.offsetWidth || 1; + var scaleY = round(rect.height) / element.offsetHeight || 1; + return scaleX !== 1 || scaleY !== 1; +} // Returns the composite rect of an element relative to its offsetParent. +// Composite means it takes into account transforms as well as layout. + + +function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) { + if (isFixed === void 0) { + isFixed = false; + } + + var isOffsetParentAnElement = isHTMLElement(offsetParent); + var offsetParentIsScaled = isHTMLElement(offsetParent) && isElementScaled(offsetParent); + var documentElement = getDocumentElement(offsetParent); + var rect = getBoundingClientRect(elementOrVirtualElement, offsetParentIsScaled, isFixed); + var scroll = { + scrollLeft: 0, + scrollTop: 0 + }; + var offsets = { + x: 0, + y: 0 + }; + + if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) { + if (getNodeName(offsetParent) !== 'body' || // https://github.com/popperjs/popper-core/issues/1078 + isScrollParent(documentElement)) { + scroll = getNodeScroll(offsetParent); + } + + if (isHTMLElement(offsetParent)) { + offsets = getBoundingClientRect(offsetParent, true); + offsets.x += offsetParent.clientLeft; + offsets.y += offsetParent.clientTop; + } else if (documentElement) { + offsets.x = getWindowScrollBarX(documentElement); + } + } + + return { + x: rect.left + scroll.scrollLeft - offsets.x, + y: rect.top + scroll.scrollTop - offsets.y, + width: rect.width, + height: rect.height + }; +} + +function order(modifiers) { + var map = new Map(); + var visited = new Set(); + var result = []; + modifiers.forEach(function (modifier) { + map.set(modifier.name, modifier); + }); // On visiting object, check for its dependencies and visit them recursively + + function sort(modifier) { + visited.add(modifier.name); + var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []); + requires.forEach(function (dep) { + if (!visited.has(dep)) { + var depModifier = map.get(dep); + + if (depModifier) { + sort(depModifier); + } + } + }); + result.push(modifier); + } + + modifiers.forEach(function (modifier) { + if (!visited.has(modifier.name)) { + // check for visited object + sort(modifier); + } + }); + return result; +} + +function orderModifiers(modifiers) { + // order based on dependencies + var orderedModifiers = order(modifiers); // order based on phase + + return modifierPhases.reduce(function (acc, phase) { + return acc.concat(orderedModifiers.filter(function (modifier) { + return modifier.phase === phase; + })); + }, []); +} + +function debounce(fn) { + var pending; + return function () { + if (!pending) { + pending = new Promise(function (resolve) { + Promise.resolve().then(function () { + pending = undefined; + resolve(fn()); + }); + }); + } + + return pending; + }; +} + +function mergeByName(modifiers) { + var merged = modifiers.reduce(function (merged, current) { + var existing = merged[current.name]; + merged[current.name] = existing ? Object.assign({}, existing, current, { + options: Object.assign({}, existing.options, current.options), + data: Object.assign({}, existing.data, current.data) + }) : current; + return merged; + }, {}); // IE11 does not support Object.values + + return Object.keys(merged).map(function (key) { + return merged[key]; + }); +} + +var DEFAULT_OPTIONS = { + placement: 'bottom', + modifiers: [], + strategy: 'absolute' +}; + +function areValidElements() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + return !args.some(function (element) { + return !(element && typeof element.getBoundingClientRect === 'function'); + }); +} + +function popperGenerator(generatorOptions) { + if (generatorOptions === void 0) { + generatorOptions = {}; + } + + var _generatorOptions = generatorOptions, + _generatorOptions$def = _generatorOptions.defaultModifiers, + defaultModifiers = _generatorOptions$def === void 0 ? [] : _generatorOptions$def, + _generatorOptions$def2 = _generatorOptions.defaultOptions, + defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2; + return function createPopper(reference, popper, options) { + if (options === void 0) { + options = defaultOptions; + } + + var state = { + placement: 'bottom', + orderedModifiers: [], + options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions), + modifiersData: {}, + elements: { + reference: reference, + popper: popper + }, + attributes: {}, + styles: {} + }; + var effectCleanupFns = []; + var isDestroyed = false; + var instance = { + state: state, + setOptions: function setOptions(setOptionsAction) { + var options = typeof setOptionsAction === 'function' ? setOptionsAction(state.options) : setOptionsAction; + cleanupModifierEffects(); + state.options = Object.assign({}, defaultOptions, state.options, options); + state.scrollParents = { + reference: isElement(reference) ? listScrollParents(reference) : reference.contextElement ? listScrollParents(reference.contextElement) : [], + popper: listScrollParents(popper) + }; // Orders the modifiers based on their dependencies and `phase` + // properties + + var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers, state.options.modifiers))); // Strip out disabled modifiers + + state.orderedModifiers = orderedModifiers.filter(function (m) { + return m.enabled; + }); // Validate the provided modifiers so that the consumer will get warned + + runModifierEffects(); + return instance.update(); + }, + // Sync update – it will always be executed, even if not necessary. This + // is useful for low frequency updates where sync behavior simplifies the + // logic. + // For high frequency updates (e.g. `resize` and `scroll` events), always + // prefer the async Popper#update method + forceUpdate: function forceUpdate() { + if (isDestroyed) { + return; + } + + var _state$elements = state.elements, + reference = _state$elements.reference, + popper = _state$elements.popper; // Don't proceed if `reference` or `popper` are not valid elements + // anymore + + if (!areValidElements(reference, popper)) { + + return; + } // Store the reference and popper rects to be read by modifiers + + + state.rects = { + reference: getCompositeRect(reference, getOffsetParent(popper), state.options.strategy === 'fixed'), + popper: getLayoutRect(popper) + }; // Modifiers have the ability to reset the current update cycle. The + // most common use case for this is the `flip` modifier changing the + // placement, which then needs to re-run all the modifiers, because the + // logic was previously ran for the previous placement and is therefore + // stale/incorrect + + state.reset = false; + state.placement = state.options.placement; // On each update cycle, the `modifiersData` property for each modifier + // is filled with the initial data specified by the modifier. This means + // it doesn't persist and is fresh on each update. + // To ensure persistent data, use `${name}#persistent` + + state.orderedModifiers.forEach(function (modifier) { + return state.modifiersData[modifier.name] = Object.assign({}, modifier.data); + }); + + for (var index = 0; index < state.orderedModifiers.length; index++) { + + if (state.reset === true) { + state.reset = false; + index = -1; + continue; + } + + var _state$orderedModifie = state.orderedModifiers[index], + fn = _state$orderedModifie.fn, + _state$orderedModifie2 = _state$orderedModifie.options, + _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2, + name = _state$orderedModifie.name; + + if (typeof fn === 'function') { + state = fn({ + state: state, + options: _options, + name: name, + instance: instance + }) || state; + } + } + }, + // Async and optimistically optimized update – it will not be executed if + // not necessary (debounced to run at most once-per-tick) + update: debounce(function () { + return new Promise(function (resolve) { + instance.forceUpdate(); + resolve(state); + }); + }), + destroy: function destroy() { + cleanupModifierEffects(); + isDestroyed = true; + } + }; + + if (!areValidElements(reference, popper)) { + + return instance; + } + + instance.setOptions(options).then(function (state) { + if (!isDestroyed && options.onFirstUpdate) { + options.onFirstUpdate(state); + } + }); // Modifiers have the ability to execute arbitrary code before the first + // update cycle runs. They will be executed in the same order as the update + // cycle. This is useful when a modifier adds some persistent data that + // other modifiers need to use, but the modifier is run after the dependent + // one. + + function runModifierEffects() { + state.orderedModifiers.forEach(function (_ref3) { + var name = _ref3.name, + _ref3$options = _ref3.options, + options = _ref3$options === void 0 ? {} : _ref3$options, + effect = _ref3.effect; + + if (typeof effect === 'function') { + var cleanupFn = effect({ + state: state, + name: name, + instance: instance, + options: options + }); + + var noopFn = function noopFn() {}; + + effectCleanupFns.push(cleanupFn || noopFn); + } + }); + } + + function cleanupModifierEffects() { + effectCleanupFns.forEach(function (fn) { + return fn(); + }); + effectCleanupFns = []; + } + + return instance; + }; +} + +var defaultModifiers = [eventListeners, popperOffsets$1, computeStyles$1, applyStyles$1, offset$1, flip$1, preventOverflow$1, arrow$1, hide$1]; +var createPopper = /*#__PURE__*/popperGenerator({ + defaultModifiers: defaultModifiers +}); // eslint-disable-next-line import/no-unused-modules + +/* global Map:readonly, Set:readonly, ArrayBuffer:readonly */ + +var hasElementType = typeof Element !== 'undefined'; +var hasMap = typeof Map === 'function'; +var hasSet = typeof Set === 'function'; +var hasArrayBuffer = typeof ArrayBuffer === 'function' && !!ArrayBuffer.isView; + +// Note: We **don't** need `envHasBigInt64Array` in fde es6/index.js + +function equal(a, b) { + // START: fast-deep-equal es6/index.js 3.1.3 + if (a === b) return true; + + if (a && b && typeof a == 'object' && typeof b == 'object') { + if (a.constructor !== b.constructor) return false; + + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) + if (!equal(a[i], b[i])) return false; + return true; + } + + // START: Modifications: + // 1. Extra `has &&` helpers in initial condition allow es6 code + // to co-exist with es5. + // 2. Replace `for of` with es5 compliant iteration using `for`. + // Basically, take: + // + // ```js + // for (i of a.entries()) + // if (!b.has(i[0])) return false; + // ``` + // + // ... and convert to: + // + // ```js + // it = a.entries(); + // while (!(i = it.next()).done) + // if (!b.has(i.value[0])) return false; + // ``` + // + // **Note**: `i` access switches to `i.value`. + var it; + if (hasMap && (a instanceof Map) && (b instanceof Map)) { + if (a.size !== b.size) return false; + it = a.entries(); + while (!(i = it.next()).done) + if (!b.has(i.value[0])) return false; + it = a.entries(); + while (!(i = it.next()).done) + if (!equal(i.value[1], b.get(i.value[0]))) return false; + return true; + } + + if (hasSet && (a instanceof Set) && (b instanceof Set)) { + if (a.size !== b.size) return false; + it = a.entries(); + while (!(i = it.next()).done) + if (!b.has(i.value[0])) return false; + return true; + } + // END: Modifications + + if (hasArrayBuffer && ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) + if (a[i] !== b[i]) return false; + return true; + } + + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + // START: Modifications: + // Apply guards for `Object.create(null)` handling. See: + // - https://github.com/FormidableLabs/react-fast-compare/issues/64 + // - https://github.com/epoberezkin/fast-deep-equal/issues/49 + if (a.valueOf !== Object.prototype.valueOf && typeof a.valueOf === 'function' && typeof b.valueOf === 'function') return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString && typeof a.toString === 'function' && typeof b.toString === 'function') return a.toString() === b.toString(); + // END: Modifications + + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + + for (i = length; i-- !== 0;) + if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + // END: fast-deep-equal + + // START: react-fast-compare + // custom handling for DOM elements + if (hasElementType && a instanceof Element) return false; + + // custom handling for React/Preact + for (i = length; i-- !== 0;) { + if ((keys[i] === '_owner' || keys[i] === '__v' || keys[i] === '__o') && a.$$typeof) { + // React-specific: avoid traversing React elements' _owner + // Preact-specific: avoid traversing Preact elements' __v and __o + // __v = $_original / $_vnode + // __o = $_owner + // These properties contain circular references and are not needed when + // comparing the actual elements (and not their owners) + // .$$typeof and ._store on just reasonable markers of elements + + continue; + } + + // all other properties should be traversed as usual + if (!equal(a[keys[i]], b[keys[i]])) return false; + } + // END: react-fast-compare + + // START: fast-deep-equal + return true; + } + + return a !== a && b !== b; +} +// end fast-deep-equal + +var reactFastCompare = function isEqual(a, b) { + try { + return equal(a, b); + } catch (error) { + if (((error.message || '').match(/stack|recursion/i))) { + // warn on circular references, don't crash + // browsers give this different errors name and messages: + // chrome/safari: "RangeError", "Maximum call stack size exceeded" + // firefox: "InternalError", too much recursion" + // edge: "Error", "Out of stack space" + console.warn('react-fast-compare cannot handle circular refs'); + return false; + } + // some other error. we should definitely know about these + throw error; + } +}; + +var isEqual = /*@__PURE__*/getDefaultExportFromCjs(reactFastCompare); + +var EMPTY_MODIFIERS$1 = []; +var usePopper = function usePopper(referenceElement, popperElement, options) { + if (options === void 0) { + options = {}; + } + + var prevOptions = reactExports.useRef(null); + var optionsWithDefaults = { + onFirstUpdate: options.onFirstUpdate, + placement: options.placement || 'bottom', + strategy: options.strategy || 'absolute', + modifiers: options.modifiers || EMPTY_MODIFIERS$1 + }; + + var _React$useState = reactExports.useState({ + styles: { + popper: { + position: optionsWithDefaults.strategy, + left: '0', + top: '0' + }, + arrow: { + position: 'absolute' + } + }, + attributes: {} + }), + state = _React$useState[0], + setState = _React$useState[1]; + + var updateStateModifier = reactExports.useMemo(function () { + return { + name: 'updateState', + enabled: true, + phase: 'write', + fn: function fn(_ref) { + var state = _ref.state; + var elements = Object.keys(state.elements); + reactDomExports.flushSync(function () { + setState({ + styles: fromEntries(elements.map(function (element) { + return [element, state.styles[element] || {}]; + })), + attributes: fromEntries(elements.map(function (element) { + return [element, state.attributes[element]]; + })) + }); + }); + }, + requires: ['computeStyles'] + }; + }, []); + var popperOptions = reactExports.useMemo(function () { + var newOptions = { + onFirstUpdate: optionsWithDefaults.onFirstUpdate, + placement: optionsWithDefaults.placement, + strategy: optionsWithDefaults.strategy, + modifiers: [].concat(optionsWithDefaults.modifiers, [updateStateModifier, { + name: 'applyStyles', + enabled: false + }]) + }; + + if (isEqual(prevOptions.current, newOptions)) { + return prevOptions.current || newOptions; + } else { + prevOptions.current = newOptions; + return newOptions; + } + }, [optionsWithDefaults.onFirstUpdate, optionsWithDefaults.placement, optionsWithDefaults.strategy, optionsWithDefaults.modifiers, updateStateModifier]); + var popperInstanceRef = reactExports.useRef(); + useIsomorphicLayoutEffect(function () { + if (popperInstanceRef.current) { + popperInstanceRef.current.setOptions(popperOptions); + } + }, [popperOptions]); + useIsomorphicLayoutEffect(function () { + if (referenceElement == null || popperElement == null) { + return; + } + + var createPopper$1 = options.createPopper || createPopper; + var popperInstance = createPopper$1(referenceElement, popperElement, popperOptions); + popperInstanceRef.current = popperInstance; + return function () { + popperInstance.destroy(); + popperInstanceRef.current = null; + }; + }, [referenceElement, popperElement, options.createPopper]); + return { + state: popperInstanceRef.current ? popperInstanceRef.current.state : null, + styles: state.styles, + attributes: state.attributes, + update: popperInstanceRef.current ? popperInstanceRef.current.update : null, + forceUpdate: popperInstanceRef.current ? popperInstanceRef.current.forceUpdate : null + }; +}; + +var NOOP = function NOOP() { + return void 0; +}; + +var NOOP_PROMISE = function NOOP_PROMISE() { + return Promise.resolve(null); +}; + +var EMPTY_MODIFIERS = []; +function Popper(_ref) { + var _ref$placement = _ref.placement, + placement = _ref$placement === void 0 ? 'bottom' : _ref$placement, + _ref$strategy = _ref.strategy, + strategy = _ref$strategy === void 0 ? 'absolute' : _ref$strategy, + _ref$modifiers = _ref.modifiers, + modifiers = _ref$modifiers === void 0 ? EMPTY_MODIFIERS : _ref$modifiers, + referenceElement = _ref.referenceElement, + onFirstUpdate = _ref.onFirstUpdate, + innerRef = _ref.innerRef, + children = _ref.children; + var referenceNode = reactExports.useContext(ManagerReferenceNodeContext); + + var _React$useState = reactExports.useState(null), + popperElement = _React$useState[0], + setPopperElement = _React$useState[1]; + + var _React$useState2 = reactExports.useState(null), + arrowElement = _React$useState2[0], + setArrowElement = _React$useState2[1]; + + reactExports.useEffect(function () { + setRef(innerRef, popperElement); + }, [innerRef, popperElement]); + var options = reactExports.useMemo(function () { + return { + placement: placement, + strategy: strategy, + onFirstUpdate: onFirstUpdate, + modifiers: [].concat(modifiers, [{ + name: 'arrow', + enabled: arrowElement != null, + options: { + element: arrowElement + } + }]) + }; + }, [placement, strategy, onFirstUpdate, modifiers, arrowElement]); + + var _usePopper = usePopper(referenceElement || referenceNode, popperElement, options), + state = _usePopper.state, + styles = _usePopper.styles, + forceUpdate = _usePopper.forceUpdate, + update = _usePopper.update; + + var childrenProps = reactExports.useMemo(function () { + return { + ref: setPopperElement, + style: styles.popper, + placement: state ? state.placement : placement, + hasPopperEscaped: state && state.modifiersData.hide ? state.modifiersData.hide.hasPopperEscaped : null, + isReferenceHidden: state && state.modifiersData.hide ? state.modifiersData.hide.isReferenceHidden : null, + arrowProps: { + style: styles.arrow, + ref: setArrowElement + }, + forceUpdate: forceUpdate || NOOP, + update: update || NOOP_PROMISE + }; + }, [setPopperElement, setArrowElement, placement, state, styles, update, forceUpdate]); + return unwrapArray(children)(childrenProps); +} + +/** + * Copyright (c) 2014-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +var warning = function() {}; + +var warning_1 = warning; + +var warning$1 = /*@__PURE__*/getDefaultExportFromCjs(warning_1); + +function Reference(_ref) { + var children = _ref.children, + innerRef = _ref.innerRef; + var setReferenceNode = reactExports.useContext(ManagerReferenceNodeSetterContext); + var refHandler = reactExports.useCallback(function (node) { + setRef(innerRef, node); + safeInvoke(setReferenceNode, node); + }, [innerRef, setReferenceNode]); // ran on unmount + // eslint-disable-next-line react-hooks/exhaustive-deps + + reactExports.useEffect(function () { + return function () { + return setRef(innerRef, null); + }; + }, []); + reactExports.useEffect(function () { + warning$1(Boolean(setReferenceNode), '`Reference` should not be used outside of a `Manager` component.'); + }, [setReferenceNode]); + return unwrapArray(children)({ + ref: refHandler + }); +} + +/** + * @name set + * @category Common Helpers + * @summary Set date values to a given date. + * + * @description + * Set date values to a given date. + * + * Sets time values to date from object `values`. + * A value is not set if it is undefined or null or doesn't exist in `values`. + * + * Note about bundle size: `set` does not internally use `setX` functions from date-fns but instead opts + * to use native `Date#setX` methods. If you use this function, you may not want to include the + * other `setX` functions that date-fns provides if you are concerned about the bundle size. + * + * @param {Date|Number} date - the date to be changed + * @param {Object} values - an object with options + * @param {Number} [values.year] - the number of years to be set + * @param {Number} [values.month] - the number of months to be set + * @param {Number} [values.date] - the number of days to be set + * @param {Number} [values.hours] - the number of hours to be set + * @param {Number} [values.minutes] - the number of minutes to be set + * @param {Number} [values.seconds] - the number of seconds to be set + * @param {Number} [values.milliseconds] - the number of milliseconds to be set + * @returns {Date} the new date with options set + * @throws {TypeError} 2 arguments required + * @throws {RangeError} `values` must be an object + * + * @example + * // Transform 1 September 2014 into 20 October 2015 in a single line: + * const result = set(new Date(2014, 8, 20), { year: 2015, month: 9, date: 20 }) + * //=> Tue Oct 20 2015 00:00:00 + * + * @example + * // Set 12 PM to 1 September 2014 01:23:45 to 1 September 2014 12:00:00: + * const result = set(new Date(2014, 8, 1, 1, 23, 45), { hours: 12 }) + * //=> Mon Sep 01 2014 12:23:45 + */ +function set(dirtyDate, values) { + requiredArgs(2, arguments); + if (_typeof$1(values) !== 'object' || values === null) { + throw new RangeError('values parameter must be an object'); + } + var date = toDate(dirtyDate); + + // Check if date is Invalid Date because Date.prototype.setFullYear ignores the value of Invalid Date + if (isNaN(date.getTime())) { + return new Date(NaN); + } + if (values.year != null) { + date.setFullYear(values.year); + } + if (values.month != null) { + date = setMonth(date, values.month); + } + if (values.date != null) { + date.setDate(toInteger(values.date)); + } + if (values.hours != null) { + date.setHours(toInteger(values.hours)); + } + if (values.minutes != null) { + date.setMinutes(toInteger(values.minutes)); + } + if (values.seconds != null) { + date.setSeconds(toInteger(values.seconds)); + } + if (values.milliseconds != null) { + date.setMilliseconds(toInteger(values.milliseconds)); + } + return date; +} + +function le(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n);}return r}function de(e){for(var t=1;te.length)&&(t=e.length);for(var r=0,n=new Array(t);r0&&(a=parse$1(e,t.slice(0,e.length),new Date)),Te(a)||(a=new Date(e))),Te(a)&&i?a:null)}function Te(e,t){return t=t||new Date("1/1/1000"),isValid(e)&&!isBefore(e,t)}function Ie(e,t,r){if("en"===r)return format$1(e,t,{awareOfUnicodeTokens:!0});var n=et(r);return r&&!n&&console.warn('A locale object was not found for the provided string ["'.concat(r,'"].')),!n&&Ze()&&et(Ze())&&(n=et(Ze())),format$1(e,t,{locale:n||null,awareOfUnicodeTokens:!0})}function Le(e,t){var r=t.dateFormat,n=t.locale;return e&&Ie(e,Array.isArray(r)?r[0]:r,n)||""}function Re(e,t){var r=t.hour,n=void 0===r?0:r,o=t.minute,a=void 0===o?0:o,s=t.second;return setHours(setMinutes(setSeconds(e,void 0===s?0:s),a),n)}function Fe(e,t){var r=t&&et(t)||Ze()&&et(Ze());return getISOWeek(e,r?{locale:r}:null)}function Ae(e,t){return Ie(e,"ddd",t)}function Ke(e){return startOfDay(e)}function Be(e,t,r){var n=et(t||Ze());return startOfWeek(e,{locale:n,weekStartsOn:r})}function We(e){return startOfMonth(e)}function He(e){return startOfYear(e)}function je(e){return startOfQuarter(e)}function Qe(){return startOfDay(Ye())}function Ve(e,t){return e&&t?isSameYear(e,t):!e&&!t}function qe(e,t){return e&&t?isSameMonth(e,t):!e&&!t}function Ue(e,t){return e&&t?isSameQuarter(e,t):!e&&!t}function ze(e,t){return e&&t?isSameDay(e,t):!e&&!t}function $e(e,t){return e&&t?isEqual$1(e,t):!e&&!t}function Ge(e,t,r){var n,o=startOfDay(t),a=endOfDay(r);try{n=isWithinInterval(e,{start:o,end:a});}catch(e){n=!1;}return n}function Ze(){return ("undefined"!=typeof window?window:globalThis).__localeId__}function et(e){if("string"==typeof e){var t="undefined"!=typeof window?window:globalThis;return t.__localeData__?t.__localeData__[e]:null}return e}function tt(e,t){return Ie(setMonth(Ye(),e),"LLLL",t)}function rt(e,t){return Ie(setMonth(Ye(),e),"LLL",t)}function nt(e,t){return Ie(setQuarter(Ye(),e),"QQQ",t)}function ot(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.minDate,n=t.maxDate,o=t.excludeDates,a=t.excludeDateIntervals,s=t.includeDates,i=t.includeDateIntervals,p=t.filterDate;return dt(e,{minDate:r,maxDate:n})||o&&o.some((function(t){return ze(e,t)}))||a&&a.some((function(t){var r=t.start,n=t.end;return isWithinInterval(e,{start:r,end:n})}))||s&&!s.some((function(t){return ze(e,t)}))||i&&!i.some((function(t){var r=t.start,n=t.end;return isWithinInterval(e,{start:r,end:n})}))||p&&!p(Ye(e))||!1}function at(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.excludeDates,n=t.excludeDateIntervals;return n&&n.length>0?n.some((function(t){var r=t.start,n=t.end;return isWithinInterval(e,{start:r,end:n})})):r&&r.some((function(t){return ze(e,t)}))||!1}function st(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.minDate,n=t.maxDate,o=t.excludeDates,a=t.includeDates,s=t.filterDate;return dt(e,{minDate:startOfMonth(r),maxDate:endOfMonth(n)})||o&&o.some((function(t){return qe(e,t)}))||a&&!a.some((function(t){return qe(e,t)}))||s&&!s(Ye(e))||!1}function it(e,t,r,n){var o=getYear(e),a=getMonth(e),s=getYear(t),i=getMonth(t),p=getYear(n);return o===s&&o===p?a<=r&&r<=i:o=r||po:void 0}function pt(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.minDate,n=t.maxDate,o=t.excludeDates,a=t.includeDates,s=t.filterDate;return dt(e,{minDate:r,maxDate:n})||o&&o.some((function(t){return Ue(e,t)}))||a&&!a.some((function(t){return Ue(e,t)}))||s&&!s(Ye(e))||!1}function ct(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.minDate,n=t.maxDate,o=t.excludeDates,a=t.includeDates,s=t.filterDate,i=new Date(e,0,1);return dt(i,{minDate:startOfYear(r),maxDate:endOfYear(n)})||o&&o.some((function(e){return Ve(i,e)}))||a&&!a.some((function(e){return Ve(i,e)}))||s&&!s(Ye(i))||!1}function lt(e,t,r,n){var o=getYear(e),a=getQuarter(e),s=getYear(t),i=getQuarter(t),p=getYear(n);return o===s&&o===p?a<=r&&r<=i:o=r||po:void 0}function dt(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.minDate,n=t.maxDate;return r&&differenceInCalendarDays(e,r)<0||n&&differenceInCalendarDays(e,n)>0}function ut(e,t){return t.some((function(t){return getHours(t)===getHours(e)&&getMinutes(t)===getMinutes(e)}))}function ht(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.excludeTimes,n=t.includeTimes,o=t.filterTime;return r&&ut(e,r)||n&&!ut(e,n)||o&&!o(e)||!1}function mt(e,t){var r=t.minTime,n=t.maxTime;if(!r||!n)throw new Error("Both minTime and maxTime props required");var o,a=Ye(),s=setHours(setMinutes(a,getMinutes(e)),getHours(e)),i=setHours(setMinutes(a,getMinutes(r)),getHours(r)),p=setHours(setMinutes(a,getMinutes(n)),getHours(n));try{o=!isWithinInterval(s,{start:i,end:p});}catch(e){o=!1;}return o}function ft(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.minDate,n=t.includeDates,o=subMonths(e,1);return r&&differenceInCalendarMonths(r,o)>0||n&&n.every((function(e){return differenceInCalendarMonths(e,o)>0}))||!1}function yt(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.maxDate,n=t.includeDates,o=addMonths(e,1);return r&&differenceInCalendarMonths(o,r)>0||n&&n.every((function(e){return differenceInCalendarMonths(o,e)>0}))||!1}function vt(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.minDate,n=t.includeDates,o=subYears(e,1);return r&&differenceInCalendarYears(r,o)>0||n&&n.every((function(e){return differenceInCalendarYears(e,o)>0}))||!1}function Dt(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.maxDate,n=t.includeDates,o=addYears(e,1);return r&&differenceInCalendarYears(o,r)>0||n&&n.every((function(e){return differenceInCalendarYears(o,e)>0}))||!1}function wt(e){var t=e.minDate,r=e.includeDates;if(r&&t){var n=r.filter((function(e){return differenceInCalendarDays(e,t)>=0}));return min$1(n)}return r?min$1(r):t}function gt(e){var t=e.maxDate,r=e.includeDates;if(r&&t){var n=r.filter((function(e){return differenceInCalendarDays(e,t)<=0}));return max$1(n)}return r?max$1(r):t}function kt(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"react-datepicker__day--highlighted",r=new Map,o=0,a=e.length;o1&&void 0!==arguments[1]?arguments[1]:12,r=Math.ceil(getYear(e)/t)*t,n=r-(t-1);return {startPeriod:n,endPeriod:r}}function _t(e,t,r,n){for(var o=[],a=0;a<2*t+1;a++){var s=e+t-a,i=!0;r&&(i=getYear(r)<=s),n&&i&&(i=getYear(n)>=s),i&&o.push(s);}return o}var Mt=onClickOutsideHOC(function(n){De(a,React.Component);var o=Se(a);function a(r){var n;he(this,a),ye(ke(n=o.call(this,r)),"renderOptions",(function(){var t=n.props.year,r=n.state.yearsList.map((function(r){return React.createElement("div",{className:t===r?"react-datepicker__year-option react-datepicker__year-option--selected_year":"react-datepicker__year-option",key:r,onClick:n.onChange.bind(ke(n),r),"aria-selected":t===r?"true":void 0},t===r?React.createElement("span",{className:"react-datepicker__year-option--selected"},"✓"):"",r)})),o=n.props.minDate?getYear(n.props.minDate):null,a=n.props.maxDate?getYear(n.props.maxDate):null;return a&&n.state.yearsList.find((function(e){return e===a}))||r.unshift(React.createElement("div",{className:"react-datepicker__year-option",key:"upcoming",onClick:n.incrementYears},React.createElement("a",{className:"react-datepicker__navigation react-datepicker__navigation--years react-datepicker__navigation--years-upcoming"}))),o&&n.state.yearsList.find((function(e){return e===o}))||r.push(React.createElement("div",{className:"react-datepicker__year-option",key:"previous",onClick:n.decrementYears},React.createElement("a",{className:"react-datepicker__navigation react-datepicker__navigation--years react-datepicker__navigation--years-previous"}))),r})),ye(ke(n),"onChange",(function(e){n.props.onChange(e);})),ye(ke(n),"handleClickOutside",(function(){n.props.onCancel();})),ye(ke(n),"shiftYears",(function(e){var t=n.state.yearsList.map((function(t){return t+e}));n.setState({yearsList:t});})),ye(ke(n),"incrementYears",(function(){return n.shiftYears(1)})),ye(ke(n),"decrementYears",(function(){return n.shiftYears(-1)}));var s=r.yearDropdownItemNumber,i=r.scrollableYearDropdown,p=s||(i?10:5);return n.state={yearsList:_t(n.props.year,p,n.props.minDate,n.props.maxDate)},n.dropdownRef=reactExports.createRef(),n}return fe(a,[{key:"componentDidMount",value:function(){var e=this.dropdownRef.current;if(e){var t=e.children?Array.from(e.children):null,r=t?t.find((function(e){return e.ariaSelected})):null;e.scrollTop=r?r.offsetTop+(r.clientHeight-e.clientHeight)/2:(e.scrollHeight-e.clientHeight)/2;}}},{key:"render",value:function(){var t=r({"react-datepicker__year-dropdown":!0,"react-datepicker__year-dropdown--scrollable":this.props.scrollableYearDropdown});return React.createElement("div",{className:t,ref:this.dropdownRef},this.renderOptions())}}]),a}()),Pt=function(t){De(n,React.Component);var r=Se(n);function n(){var t;he(this,n);for(var o=arguments.length,a=new Array(o),s=0;s0&&void 0!==arguments[0]?arguments[0]:{},r=!1;0===t.getTabIndex()&&!e.isInputFocused&&t.isSameDay(t.props.preSelection)&&(document.activeElement&&document.activeElement!==document.body||(r=!0),t.props.inline&&!t.props.shouldFocusDayInline&&(r=!1),t.props.containerRef&&t.props.containerRef.current&&t.props.containerRef.current.contains(document.activeElement)&&document.activeElement.classList.contains("react-datepicker__day")&&(r=!0)),r&&t.dayEl.current.focus({preventScroll:!0});})),ye(ke(t),"renderDayContents",(function(){return t.props.monthShowsDuplicateDaysEnd&&t.isAfterMonth()||t.props.monthShowsDuplicateDaysStart&&t.isBeforeMonth()?null:t.props.renderDayContents?t.props.renderDayContents(getDate(t.props.day),t.props.day):getDate(t.props.day)})),ye(ke(t),"render",(function(){return React.createElement("div",{ref:t.dayEl,className:t.getClassNames(t.props.day),onKeyDown:t.handleOnKeyDown,onClick:t.handleClick,onMouseEnter:t.handleMouseEnter,tabIndex:t.getTabIndex(),"aria-label":t.getAriaLabel(),role:"option","aria-disabled":t.isDisabled(),"aria-current":t.isCurrentDay()?"date":void 0,"aria-selected":t.isSelected()},t.renderDayContents())})),t}return fe(o,[{key:"componentDidMount",value:function(){this.handleFocusDay();}},{key:"componentDidUpdate",value:function(e){this.handleFocusDay(e);}}]),o}(),It=function(t){De(o,React.Component);var n=Se(o);function o(){var e;he(this,o);for(var t=arguments.length,r=new Array(t),a=0;a=6,p=!n&&!t.isWeekInMonth(s);if(i||p){if(!t.props.peekNextMonth)break;a=!0;}}return r})),ye(ke(t),"onMonthClick",(function(e,r){t.handleDayClick(We(setMonth(t.props.day,r)),e);})),ye(ke(t),"handleMonthNavigation",(function(e,r){t.isDisabled(r)||t.isExcluded(r)||(t.props.setPreSelection(r),t.MONTH_REFS[e].current&&t.MONTH_REFS[e].current.focus());})),ye(ke(t),"onMonthKeyDown",(function(e,r){e.preventDefault();var n=e.key;if(!t.props.disabledKeyboardNavigation)switch(n){case"Enter":t.onMonthClick(e,r),t.props.setPreSelection(t.props.selected);break;case"ArrowRight":t.handleMonthNavigation(11===r?0:r+1,addMonths(t.props.preSelection,1));break;case"ArrowLeft":t.handleMonthNavigation(0===r?11:r-1,subMonths(t.props.preSelection,1));break;case"ArrowUp":t.handleMonthNavigation(r>=0&&r<=2?r+9:r-3,subMonths(t.props.preSelection,3));break;case"ArrowDown":t.handleMonthNavigation(r>=9&&r<=11?r-9:r+3,addMonths(t.props.preSelection,3));}})),ye(ke(t),"onQuarterClick",(function(e,r){t.handleDayClick(je(setQuarter(t.props.day,r)),e);})),ye(ke(t),"handleQuarterNavigation",(function(e,r){t.isDisabled(r)||t.isExcluded(r)||(t.props.setPreSelection(r),t.QUARTER_REFS[e-1].current&&t.QUARTER_REFS[e-1].current.focus());})),ye(ke(t),"onQuarterKeyDown",(function(e,r){var n=e.key;if(!t.props.disabledKeyboardNavigation)switch(n){case"Enter":t.onQuarterClick(e,r),t.props.setPreSelection(t.props.selected);break;case"ArrowRight":t.handleQuarterNavigation(4===r?1:r+1,addQuarters(t.props.preSelection,1));break;case"ArrowLeft":t.handleQuarterNavigation(1===r?4:r-1,subQuarters(t.props.preSelection,1));}})),ye(ke(t),"getMonthClassNames",(function(e){var n=t.props,o=n.day,a=n.startDate,s=n.endDate,i=n.selected,p=n.minDate,c=n.maxDate,l=n.preSelection,d=n.monthClassName,u=n.excludeDates,h=n.includeDates,m=d?d(setMonth(o,e)):void 0,f=setMonth(o,e);return r("react-datepicker__month-text","react-datepicker__month-".concat(e),m,{"react-datepicker__month--disabled":(p||c||u||h)&&st(f,t.props),"react-datepicker__month--selected":t.isSelectedMonth(o,e,i),"react-datepicker__month-text--keyboard-selected":!t.props.disabledKeyboardNavigation&&getMonth(l)===e,"react-datepicker__month--in-range":it(a,s,e,o),"react-datepicker__month--range-start":t.isRangeStartMonth(e),"react-datepicker__month--range-end":t.isRangeEndMonth(e),"react-datepicker__month-text--today":t.isCurrentMonth(o,e)})})),ye(ke(t),"getTabIndex",(function(e){var r=getMonth(t.props.preSelection);return t.props.disabledKeyboardNavigation||e!==r?"-1":"0"})),ye(ke(t),"getQuarterTabIndex",(function(e){var r=getQuarter(t.props.preSelection);return t.props.disabledKeyboardNavigation||e!==r?"-1":"0"})),ye(ke(t),"getAriaLabel",(function(e){var r=t.props,n=r.chooseDayAriaLabelPrefix,o=void 0===n?"Choose":n,a=r.disabledDayAriaLabelPrefix,s=void 0===a?"Not available":a,i=r.day,p=setMonth(i,e),c=t.isDisabled(p)||t.isExcluded(p)?s:o;return "".concat(c," ").concat(Ie(p,"MMMM yyyy"))})),ye(ke(t),"getQuarterClassNames",(function(e){var n=t.props,o=n.day,a=n.startDate,s=n.endDate,i=n.selected,p=n.minDate,c=n.maxDate,l=n.preSelection;return r("react-datepicker__quarter-text","react-datepicker__quarter-".concat(e),{"react-datepicker__quarter--disabled":(p||c)&&pt(setQuarter(o,e),t.props),"react-datepicker__quarter--selected":t.isSelectedQuarter(o,e,i),"react-datepicker__quarter-text--keyboard-selected":getQuarter(l)===e,"react-datepicker__quarter--in-range":lt(a,s,e,o),"react-datepicker__quarter--range-start":t.isRangeStartQuarter(e),"react-datepicker__quarter--range-end":t.isRangeEndQuarter(e)})})),ye(ke(t),"renderMonths",(function(){var r=t.props,n=r.showFullMonthYearPicker,o=r.showTwoColumnMonthYearPicker,a=r.showFourColumnMonthYearPicker,s=r.locale,i=r.day,p=r.selected;return (a?[[0,1,2,3],[4,5,6,7],[8,9,10,11]]:o?[[0,1],[2,3],[4,5],[6,7],[8,9],[10,11]]:[[0,1,2],[3,4,5],[6,7,8],[9,10,11]]).map((function(r,o){return React.createElement("div",{className:"react-datepicker__month-wrapper",key:o},r.map((function(r,o){return React.createElement("div",{ref:t.MONTH_REFS[r],key:o,onClick:function(e){t.onMonthClick(e,r);},onKeyDown:function(e){t.onMonthKeyDown(e,r);},tabIndex:t.getTabIndex(r),className:t.getMonthClassNames(r),role:"option","aria-label":t.getAriaLabel(r),"aria-current":t.isCurrentMonth(i,r)?"date":void 0,"aria-selected":t.isSelectedMonth(i,r,p)},n?tt(r,s):rt(r,s))})))}))})),ye(ke(t),"renderQuarters",(function(){var r=t.props,n=r.day,o=r.selected;return React.createElement("div",{className:"react-datepicker__quarter-wrapper"},[1,2,3,4].map((function(r,a){return React.createElement("div",{key:a,ref:t.QUARTER_REFS[a],role:"option",onClick:function(e){t.onQuarterClick(e,r);},onKeyDown:function(e){t.onQuarterKeyDown(e,r);},className:t.getQuarterClassNames(r),"aria-selected":t.isSelectedQuarter(n,r,o),tabIndex:t.getQuarterTabIndex(r),"aria-current":t.isCurrentQuarter(n,r)?"date":void 0},nt(r,t.props.locale))})))})),ye(ke(t),"getClassNames",(function(){var e=t.props;e.day;var n=e.selectingDate,o=e.selectsStart,a=e.selectsEnd,s=e.showMonthYearPicker,i=e.showQuarterYearPicker;return r("react-datepicker__month",{"react-datepicker__month--selecting-range":n&&(o||a)},{"react-datepicker__monthPicker":s},{"react-datepicker__quarterPicker":i})})),t}return fe(o,[{key:"render",value:function(){var t=this.props,r=t.showMonthYearPicker,n=t.showQuarterYearPicker,o=t.day,a=t.ariaLabelPrefix,s=void 0===a?"month ":a;return React.createElement("div",{className:this.getClassNames(),onMouseLeave:this.handleMouseLeave,"aria-label":"".concat(s," ").concat(Ie(o,"yyyy-MM")),role:"listbox"},r?this.renderMonths():n?this.renderQuarters():this.renderWeeks())}}]),o}(),Ft=function(t){De(n,React.Component);var r=Se(n);function n(){var t;he(this,n);for(var o=arguments.length,a=new Array(o),i=0;i0&&void 0!==arguments[0]?arguments[0]:{}).className||"").split(/\s+/);return Wt.some((function(t){return e.indexOf(t)>=0}))})(e.target)&&a.props.onDropdownFocus();})),ye(ke(a),"getDateInView",(function(){var e=a.props,t=e.preSelection,r=e.selected,n=e.openToDate,o=wt(a.props),s=gt(a.props),i=Ye(),p=n||r||t;return p||(o&&isBefore(i,o)?o:s&&isAfter(i,s)?s:i)})),ye(ke(a),"increaseMonth",(function(){a.setState((function(e){var t=e.date;return {date:addMonths(t,1)}}),(function(){return a.handleMonthChange(a.state.date)}));})),ye(ke(a),"decreaseMonth",(function(){a.setState((function(e){var t=e.date;return {date:subMonths(t,1)}}),(function(){return a.handleMonthChange(a.state.date)}));})),ye(ke(a),"handleDayClick",(function(e,t,r){a.props.onSelect(e,t,r),a.props.setPreSelection&&a.props.setPreSelection(e);})),ye(ke(a),"handleDayMouseEnter",(function(e){a.setState({selectingDate:e}),a.props.onDayMouseEnter&&a.props.onDayMouseEnter(e);})),ye(ke(a),"handleMonthMouseLeave",(function(){a.setState({selectingDate:null}),a.props.onMonthMouseLeave&&a.props.onMonthMouseLeave();})),ye(ke(a),"handleYearChange",(function(e){a.props.onYearChange&&(a.props.onYearChange(e),a.setState({isRenderAriaLiveMessage:!0})),a.props.adjustDateOnChange&&(a.props.onSelect&&a.props.onSelect(e),a.props.setOpen&&a.props.setOpen(!0)),a.props.setPreSelection&&a.props.setPreSelection(e);})),ye(ke(a),"handleMonthChange",(function(e){a.props.onMonthChange&&(a.props.onMonthChange(e),a.setState({isRenderAriaLiveMessage:!0})),a.props.adjustDateOnChange&&(a.props.onSelect&&a.props.onSelect(e),a.props.setOpen&&a.props.setOpen(!0)),a.props.setPreSelection&&a.props.setPreSelection(e);})),ye(ke(a),"handleMonthYearChange",(function(e){a.handleYearChange(e),a.handleMonthChange(e);})),ye(ke(a),"changeYear",(function(e){a.setState((function(t){var r=t.date;return {date:setYear(r,e)}}),(function(){return a.handleYearChange(a.state.date)}));})),ye(ke(a),"changeMonth",(function(e){a.setState((function(t){var r=t.date;return {date:setMonth(r,e)}}),(function(){return a.handleMonthChange(a.state.date)}));})),ye(ke(a),"changeMonthYear",(function(e){a.setState((function(t){var r=t.date;return {date:setYear(setMonth(r,getMonth(e)),getYear(e))}}),(function(){return a.handleMonthYearChange(a.state.date)}));})),ye(ke(a),"header",(function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:a.state.date,n=Be(t,a.props.locale,a.props.calendarStartDay),o=[];return a.props.showWeekNumbers&&o.push(React.createElement("div",{key:"W",className:"react-datepicker__day-name"},a.props.weekLabel||"#")),o.concat([0,1,2,3,4,5,6].map((function(t){var o=addDays(n,t),s=a.formatWeekday(o,a.props.locale),i=a.props.weekDayClassName?a.props.weekDayClassName(o):void 0;return React.createElement("div",{key:t,className:r("react-datepicker__day-name",i)},s)})))})),ye(ke(a),"formatWeekday",(function(e,t){return a.props.formatWeekDay?function(e,t,r){return t(Ie(e,"EEEE",r))}(e,a.props.formatWeekDay,t):a.props.useWeekdaysShort?function(e,t){return Ie(e,"EEE",t)}(e,t):function(e,t){return Ie(e,"EEEEEE",t)}(e,t)})),ye(ke(a),"decreaseYear",(function(){a.setState((function(e){var t=e.date;return {date:subYears(t,a.props.showYearPicker?a.props.yearItemNumber:1)}}),(function(){return a.handleYearChange(a.state.date)}));})),ye(ke(a),"renderPreviousButton",(function(){if(!a.props.renderCustomHeader){var t;switch(!0){case a.props.showMonthYearPicker:t=vt(a.state.date,a.props);break;case a.props.showYearPicker:t=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.minDate,n=t.yearItemNumber,o=void 0===n?12:n,a=Ct(He(subYears(e,o)),o).endPeriod,s=r&&getYear(r);return s&&s>a||!1}(a.state.date,a.props);break;default:t=ft(a.state.date,a.props);}if((a.props.forceShowMonthNavigation||a.props.showDisabledMonthNavigation||!t)&&!a.props.showTimeSelectOnly){var r=["react-datepicker__navigation","react-datepicker__navigation--previous"],n=a.decreaseMonth;(a.props.showMonthYearPicker||a.props.showQuarterYearPicker||a.props.showYearPicker)&&(n=a.decreaseYear),t&&a.props.showDisabledMonthNavigation&&(r.push("react-datepicker__navigation--previous--disabled"),n=null);var o=a.props.showMonthYearPicker||a.props.showQuarterYearPicker||a.props.showYearPicker,s=a.props,i=s.previousMonthButtonLabel,p=s.previousYearButtonLabel,c=a.props,l=c.previousMonthAriaLabel,d=void 0===l?"string"==typeof i?i:"Previous Month":l,u=c.previousYearAriaLabel,h=void 0===u?"string"==typeof p?p:"Previous Year":u;return React.createElement("button",{type:"button",className:r.join(" "),onClick:n,onKeyDown:a.props.handleOnKeyDown,"aria-label":o?h:d},React.createElement("span",{className:["react-datepicker__navigation-icon","react-datepicker__navigation-icon--previous"].join(" ")},o?a.props.previousYearButtonLabel:a.props.previousMonthButtonLabel))}}})),ye(ke(a),"increaseYear",(function(){a.setState((function(e){var t=e.date;return {date:addYears(t,a.props.showYearPicker?a.props.yearItemNumber:1)}}),(function(){return a.handleYearChange(a.state.date)}));})),ye(ke(a),"renderNextButton",(function(){if(!a.props.renderCustomHeader){var t;switch(!0){case a.props.showMonthYearPicker:t=Dt(a.state.date,a.props);break;case a.props.showYearPicker:t=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.maxDate,n=t.yearItemNumber,o=void 0===n?12:n,a=Ct(addYears(e,o),o).startPeriod,s=r&&getYear(r);return s&&s0&&void 0!==arguments[0]?arguments[0]:a.state.date,r=["react-datepicker__current-month"];return a.props.showYearDropdown&&r.push("react-datepicker__current-month--hasYearDropdown"),a.props.showMonthDropdown&&r.push("react-datepicker__current-month--hasMonthDropdown"),a.props.showMonthYearDropdown&&r.push("react-datepicker__current-month--hasMonthYearDropdown"),React.createElement("div",{className:r.join(" ")},Ie(t,a.props.dateFormat,a.props.locale))})),ye(ke(a),"renderYearDropdown",(function(){var t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(a.props.showYearDropdown&&!t)return React.createElement(Pt,{adjustDateOnChange:a.props.adjustDateOnChange,date:a.state.date,onSelect:a.props.onSelect,setOpen:a.props.setOpen,dropdownMode:a.props.dropdownMode,onChange:a.changeYear,minDate:a.props.minDate,maxDate:a.props.maxDate,year:getYear(a.state.date),scrollableYearDropdown:a.props.scrollableYearDropdown,yearDropdownItemNumber:a.props.yearDropdownItemNumber})})),ye(ke(a),"renderMonthDropdown",(function(){var t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(a.props.showMonthDropdown&&!t)return React.createElement(Nt,{dropdownMode:a.props.dropdownMode,locale:a.props.locale,onChange:a.changeMonth,month:getMonth(a.state.date),useShortMonthInDropdown:a.props.useShortMonthInDropdown})})),ye(ke(a),"renderMonthYearDropdown",(function(){var t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(a.props.showMonthYearDropdown&&!t)return React.createElement(Ot,{dropdownMode:a.props.dropdownMode,locale:a.props.locale,dateFormat:a.props.dateFormat,onChange:a.changeMonthYear,minDate:a.props.minDate,maxDate:a.props.maxDate,date:a.state.date,scrollableMonthYearDropdown:a.props.scrollableMonthYearDropdown})})),ye(ke(a),"handleTodayButtonClick",(function(e){a.props.onSelect(Qe(),e),a.props.setPreSelection&&a.props.setPreSelection(Qe());})),ye(ke(a),"renderTodayButton",(function(){if(a.props.todayButton&&!a.props.showTimeSelectOnly)return React.createElement("div",{className:"react-datepicker__today-button",onClick:function(e){return a.handleTodayButtonClick(e)}},a.props.todayButton)})),ye(ke(a),"renderDefaultHeader",(function(t){var r=t.monthDate,n=t.i;return React.createElement("div",{className:"react-datepicker__header ".concat(a.props.showTimeSelect?"react-datepicker__header--has-time-select":"")},a.renderCurrentMonth(r),React.createElement("div",{className:"react-datepicker__header__dropdown react-datepicker__header__dropdown--".concat(a.props.dropdownMode),onFocus:a.handleDropdownFocus},a.renderMonthDropdown(0!==n),a.renderMonthYearDropdown(0!==n),a.renderYearDropdown(0!==n)),React.createElement("div",{className:"react-datepicker__day-names"},a.header(r)))})),ye(ke(a),"renderCustomHeader",(function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=t.monthDate,n=t.i;if(a.props.showTimeSelect&&!a.state.monthContainer||a.props.showTimeSelectOnly)return null;var o=ft(a.state.date,a.props),s=yt(a.state.date,a.props),i=vt(a.state.date,a.props),p=Dt(a.state.date,a.props),c=!a.props.showMonthYearPicker&&!a.props.showQuarterYearPicker&&!a.props.showYearPicker;return React.createElement("div",{className:"react-datepicker__header react-datepicker__header--custom",onFocus:a.props.onDropdownFocus},a.props.renderCustomHeader(de(de({},a.state),{},{customHeaderCount:n,monthDate:r,changeMonth:a.changeMonth,changeYear:a.changeYear,decreaseMonth:a.decreaseMonth,increaseMonth:a.increaseMonth,decreaseYear:a.decreaseYear,increaseYear:a.increaseYear,prevMonthButtonDisabled:o,nextMonthButtonDisabled:s,prevYearButtonDisabled:i,nextYearButtonDisabled:p})),c&&React.createElement("div",{className:"react-datepicker__day-names"},a.header(r)))})),ye(ke(a),"renderYearHeader",(function(){var t=a.state.date,r=a.props,n=r.showYearPicker,o=Ct(t,r.yearItemNumber),s=o.startPeriod,i=o.endPeriod;return React.createElement("div",{className:"react-datepicker__header react-datepicker-year-header"},n?"".concat(s," - ").concat(i):getYear(t))})),ye(ke(a),"renderHeader",(function(e){switch(!0){case void 0!==a.props.renderCustomHeader:return a.renderCustomHeader(e);case a.props.showMonthYearPicker||a.props.showQuarterYearPicker||a.props.showYearPicker:return a.renderYearHeader(e);default:return a.renderDefaultHeader(e)}})),ye(ke(a),"renderMonths",(function(){if(!a.props.showTimeSelectOnly&&!a.props.showYearPicker){for(var t=[],r=a.props.showPreviousMonths?a.props.monthsShown-1:0,n=subMonths(a.state.date,r),o=0;o0;t.push(React.createElement("div",{key:p,ref:function(e){a.monthContainer=e;},className:"react-datepicker__month-container"},a.renderHeader({monthDate:i,i:o}),React.createElement(Rt,{chooseDayAriaLabelPrefix:a.props.chooseDayAriaLabelPrefix,disabledDayAriaLabelPrefix:a.props.disabledDayAriaLabelPrefix,weekAriaLabelPrefix:a.props.weekAriaLabelPrefix,ariaLabelPrefix:a.props.monthAriaLabelPrefix,onChange:a.changeMonthYear,day:i,dayClassName:a.props.dayClassName,calendarStartDay:a.props.calendarStartDay,monthClassName:a.props.monthClassName,onDayClick:a.handleDayClick,handleOnKeyDown:a.props.handleOnDayKeyDown,onDayMouseEnter:a.handleDayMouseEnter,onMouseLeave:a.handleMonthMouseLeave,onWeekSelect:a.props.onWeekSelect,orderInDisplay:o,formatWeekNumber:a.props.formatWeekNumber,locale:a.props.locale,minDate:a.props.minDate,maxDate:a.props.maxDate,excludeDates:a.props.excludeDates,excludeDateIntervals:a.props.excludeDateIntervals,highlightDates:a.props.highlightDates,selectingDate:a.state.selectingDate,includeDates:a.props.includeDates,includeDateIntervals:a.props.includeDateIntervals,inline:a.props.inline,shouldFocusDayInline:a.props.shouldFocusDayInline,fixedHeight:a.props.fixedHeight,filterDate:a.props.filterDate,preSelection:a.props.preSelection,setPreSelection:a.props.setPreSelection,selected:a.props.selected,selectsStart:a.props.selectsStart,selectsEnd:a.props.selectsEnd,selectsRange:a.props.selectsRange,selectsDisabledDaysInRange:a.props.selectsDisabledDaysInRange,showWeekNumbers:a.props.showWeekNumbers,startDate:a.props.startDate,endDate:a.props.endDate,peekNextMonth:a.props.peekNextMonth,setOpen:a.props.setOpen,shouldCloseOnSelect:a.props.shouldCloseOnSelect,renderDayContents:a.props.renderDayContents,disabledKeyboardNavigation:a.props.disabledKeyboardNavigation,showMonthYearPicker:a.props.showMonthYearPicker,showFullMonthYearPicker:a.props.showFullMonthYearPicker,showTwoColumnMonthYearPicker:a.props.showTwoColumnMonthYearPicker,showFourColumnMonthYearPicker:a.props.showFourColumnMonthYearPicker,showYearPicker:a.props.showYearPicker,showQuarterYearPicker:a.props.showQuarterYearPicker,isInputFocused:a.props.isInputFocused,containerRef:a.containerRef,monthShowsDuplicateDaysEnd:c,monthShowsDuplicateDaysStart:d})));}return t}})),ye(ke(a),"renderYears",(function(){if(!a.props.showTimeSelectOnly)return a.props.showYearPicker?React.createElement("div",{className:"react-datepicker__year--container"},a.renderHeader(),React.createElement(At,ve({onDayClick:a.handleDayClick,date:a.state.date},a.props))):void 0})),ye(ke(a),"renderTimeSection",(function(){if(a.props.showTimeSelect&&(a.state.monthContainer||a.props.showTimeSelectOnly))return React.createElement(Ft,{selected:a.props.selected,openToDate:a.props.openToDate,onChange:a.props.onTimeChange,timeClassName:a.props.timeClassName,format:a.props.timeFormat,includeTimes:a.props.includeTimes,intervals:a.props.timeIntervals,minTime:a.props.minTime,maxTime:a.props.maxTime,excludeTimes:a.props.excludeTimes,filterTime:a.props.filterTime,timeCaption:a.props.timeCaption,todayButton:a.props.todayButton,showMonthDropdown:a.props.showMonthDropdown,showMonthYearDropdown:a.props.showMonthYearDropdown,showYearDropdown:a.props.showYearDropdown,withPortal:a.props.withPortal,monthRef:a.state.monthContainer,injectTimes:a.props.injectTimes,locale:a.props.locale,handleOnKeyDown:a.props.handleOnKeyDown,showTimeSelectOnly:a.props.showTimeSelectOnly})})),ye(ke(a),"renderInputTimeSection",(function(){var t=new Date(a.props.selected),r=Te(t)&&Boolean(a.props.selected)?"".concat(St(t.getHours()),":").concat(St(t.getMinutes())):"";if(a.props.showTimeInput)return React.createElement(Kt,{date:t,timeString:r,timeInputLabel:a.props.timeInputLabel,onChange:a.props.onTimeChange,customTimeInput:a.props.customTimeInput})})),ye(ke(a),"renderAriaLiveRegion",(function(){var t,r=Ct(a.state.date,a.props.yearItemNumber),n=r.startPeriod,o=r.endPeriod;return t=a.props.showYearPicker?"".concat(n," - ").concat(o):a.props.showMonthYearPicker||a.props.showQuarterYearPicker?getYear(a.state.date):"".concat(tt(getMonth(a.state.date),a.props.locale)," ").concat(getYear(a.state.date)),React.createElement("span",{role:"alert","aria-live":"polite",className:"react-datepicker__aria-live"},a.state.isRenderAriaLiveMessage&&t)})),ye(ke(a),"renderChildren",(function(){if(a.props.children)return React.createElement("div",{className:"react-datepicker__children-container"},a.props.children)})),a.containerRef=React.createRef(),a.state={date:a.getDateInView(),selectingDate:null,monthContainer:null,isRenderAriaLiveMessage:!1},a}return fe(o,[{key:"componentDidMount",value:function(){var e=this;this.props.showTimeSelect&&(this.assignMonthContainer=void e.setState({monthContainer:e.monthContainer}));}},{key:"componentDidUpdate",value:function(e){!this.props.preSelection||ze(this.props.preSelection,e.preSelection)&&this.props.monthSelectedIn===e.monthSelectedIn?this.props.openToDate&&!ze(this.props.openToDate,e.openToDate)&&this.setState({date:this.props.openToDate}):this.setState({date:this.props.preSelection});}},{key:"render",value:function(){var t=this.props.container||Bt;return React.createElement("div",{ref:this.containerRef},React.createElement(t,{className:r("react-datepicker",this.props.className,{"react-datepicker--time-only":this.props.showTimeSelectOnly}),showPopperArrow:this.props.showPopperArrow,arrowProps:this.props.arrowProps},this.renderAriaLiveRegion(),this.renderPreviousButton(),this.renderNextButton(),this.renderMonths(),this.renderYears(),this.renderTodayButton(),this.renderTimeSection(),this.renderInputTimeSection(),this.renderChildren()))}}],[{key:"defaultProps",get:function(){return {onDropdownFocus:function(){},monthsShown:1,monthSelectedIn:0,forceShowMonthNavigation:!1,timeCaption:"Time",previousYearButtonLabel:"Previous Year",nextYearButtonLabel:"Next Year",previousMonthButtonLabel:"Previous Month",nextMonthButtonLabel:"Next Month",customTimeInput:null,yearItemNumber:12}}}]),o}(),jt=function(t){De(n,React.Component);var r=Se(n);function n(e){var t;return he(this,n),(t=r.call(this,e)).el=document.createElement("div"),t}return fe(n,[{key:"componentDidMount",value:function(){this.portalRoot=(this.props.portalHost||document).getElementById(this.props.portalId),this.portalRoot||(this.portalRoot=document.createElement("div"),this.portalRoot.setAttribute("id",this.props.portalId),(this.props.portalHost||document.body).appendChild(this.portalRoot)),this.portalRoot.appendChild(this.el);}},{key:"componentWillUnmount",value:function(){this.portalRoot.removeChild(this.el);}},{key:"render",value:function(){return ReactDOM.createPortal(this.props.children,this.el)}}]),n}(),Qt=function(e){return !e.disabled&&-1!==e.tabIndex},Vt=function(t){De(n,React.Component);var r=Se(n);function n(t){var o;return he(this,n),ye(ke(o=r.call(this,t)),"getTabChildren",(function(){return Array.prototype.slice.call(o.tabLoopRef.current.querySelectorAll("[tabindex], a, button, input, select, textarea"),1,-1).filter(Qt)})),ye(ke(o),"handleFocusStart",(function(e){var t=o.getTabChildren();t&&t.length>1&&t[t.length-1].focus();})),ye(ke(o),"handleFocusEnd",(function(e){var t=o.getTabChildren();t&&t.length>1&&t[0].focus();})),o.tabLoopRef=React.createRef(),o}return fe(n,[{key:"render",value:function(){return this.props.enableTabLoop?React.createElement("div",{className:"react-datepicker__tab-loop",ref:this.tabLoopRef},React.createElement("div",{className:"react-datepicker__tab-loop__start",tabIndex:"0",onFocus:this.handleFocusStart}),this.props.children,React.createElement("div",{className:"react-datepicker__tab-loop__end",tabIndex:"0",onFocus:this.handleFocusEnd})):this.props.children}}],[{key:"defaultProps",get:function(){return {enableTabLoop:!0}}}]),n}(),qt=function(t){De(o,React.Component);var n=Se(o);function o(){return he(this,o),n.apply(this,arguments)}return fe(o,[{key:"render",value:function(){var t,n=this.props,o=n.className,a=n.wrapperClassName,s=n.hidePopper,i=n.popperComponent,p=n.popperModifiers,c=n.popperPlacement,l=n.popperProps,d=n.targetComponent,u=n.enableTabLoop,h=n.popperOnKeyDown,m=n.portalId,f=n.portalHost;if(!s){var y=r("react-datepicker-popper",o);t=React.createElement(Popper,ve({modifiers:p,placement:c},l),(function(t){var r=t.ref,n=t.style,o=t.placement,a=t.arrowProps;return React.createElement(Vt,{enableTabLoop:u},React.createElement("div",{ref:r,style:n,className:y,"data-placement":o,onKeyDown:h},React.cloneElement(i,{arrowProps:a})))}));}this.props.popperContainer&&(t=React.createElement(this.props.popperContainer,{},t)),m&&!s&&(t=React.createElement(jt,{portalId:m,portalHost:f},t));var v=r("react-datepicker-wrapper",a);return React.createElement(Manager,{className:"react-datepicker-manager"},React.createElement(Reference,null,(function(t){var r=t.ref;return React.createElement("div",{ref:r,className:v},d)})),t)}}],[{key:"defaultProps",get:function(){return {hidePopper:!0,popperModifiers:[],popperProps:{},popperPlacement:"bottom-start"}}}]),o}(),Ut=onClickOutsideHOC(Ht);var zt=function(t){De(a,React.Component);var o=Se(a);function a(t){var s;return he(this,a),ye(ke(s=o.call(this,t)),"getPreSelection",(function(){return s.props.openToDate?s.props.openToDate:s.props.selectsEnd&&s.props.startDate?s.props.startDate:s.props.selectsStart&&s.props.endDate?s.props.endDate:Ye()})),ye(ke(s),"calcInitialState",(function(){var e,t=s.getPreSelection(),r=wt(s.props),n=gt(s.props),o=r&&isBefore(t,startOfDay(r))?r:n&&isAfter(t,endOfDay(n))?n:t;return {open:s.props.startOpen||!1,preventFocus:!1,preSelection:null!==(e=s.props.selectsRange?s.props.startDate:s.props.selected)&&void 0!==e?e:o,highlightDates:kt(s.props.highlightDates),focused:!1,shouldFocusDayInline:!1,isRenderAriaLiveMessage:!1}})),ye(ke(s),"clearPreventFocusTimeout",(function(){s.preventFocusTimeout&&clearTimeout(s.preventFocusTimeout);})),ye(ke(s),"setFocus",(function(){s.input&&s.input.focus&&s.input.focus({preventScroll:!0});})),ye(ke(s),"setBlur",(function(){s.input&&s.input.blur&&s.input.blur(),s.cancelFocusInput();})),ye(ke(s),"setOpen",(function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];s.setState({open:e,preSelection:e&&s.state.open?s.state.preSelection:s.calcInitialState().preSelection,lastPreSelectChange:Gt},(function(){e||s.setState((function(e){return {focused:!!t&&e.focused}}),(function(){!t&&s.setBlur(),s.setState({inputValue:null});}));}));})),ye(ke(s),"inputOk",(function(){return isDate(s.state.preSelection)})),ye(ke(s),"isCalendarOpen",(function(){return void 0===s.props.open?s.state.open&&!s.props.disabled&&!s.props.readOnly:s.props.open})),ye(ke(s),"handleFocus",(function(e){s.state.preventFocus||(s.props.onFocus(e),s.props.preventOpenOnFocus||s.props.readOnly||s.setOpen(!0)),s.setState({focused:!0});})),ye(ke(s),"cancelFocusInput",(function(){clearTimeout(s.inputFocusTimeout),s.inputFocusTimeout=null;})),ye(ke(s),"deferFocusInput",(function(){s.cancelFocusInput(),s.inputFocusTimeout=setTimeout((function(){return s.setFocus()}),1);})),ye(ke(s),"handleDropdownFocus",(function(){s.cancelFocusInput();})),ye(ke(s),"handleBlur",(function(e){(!s.state.open||s.props.withPortal||s.props.showTimeInput)&&s.props.onBlur(e),s.setState({focused:!1});})),ye(ke(s),"handleCalendarClickOutside",(function(e){s.props.inline||s.setOpen(!1),s.props.onClickOutside(e),s.props.withPortal&&e.preventDefault();})),ye(ke(s),"handleChange",(function(){for(var e=arguments.length,t=new Array(e),r=0;r=0||(r[n]=e[n]);return r}function u(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var o=n.call(e,t||"default");if("object"!=typeof o)return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return ("string"===t?String:Number)(e)}(e,"string");return "symbol"==typeof t?t:String(t)}t=t&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t;var l={init:"init"},s=function(e){var t=e.value;return void 0===t?"":t},a=function(){return t.createElement(t.Fragment,null," ")},c={Cell:s,width:150,minWidth:0,maxWidth:Number.MAX_SAFE_INTEGER};function d(){for(var e=arguments.length,t=new Array(e),n=0;n(i="number"==typeof i?i:1/0)){var u=r;r=i,i=u;}return e.filter((function(e){return t.some((function(t){var n=e.values[t];return n>=r&&n<=i}))}))};Ce.autoRemove=function(e){return !e||"number"!=typeof e[0]&&"number"!=typeof e[1]};var xe=Object.freeze({__proto__:null,text:ge,exactText:ve,exactTextCase:me,includes:he,includesAll:ye,includesSome:we,includesValue:Re,exact:be,equals:Se,between:Ce});l.resetFilters="resetFilters",l.setFilter="setFilter",l.setAllFilters="setAllFilters";var Pe=function(e){e.stateReducers.push(Be),e.useInstance.push(Ee);};function Be(e,t,n,o){if(t.type===l.init)return r({filters:[]},e);if(t.type===l.resetFilters)return r({},e,{filters:o.initialState.filters||[]});if(t.type===l.setFilter){var i=t.columnId,u=t.filterValue,s=o.allColumns,a=o.filterTypes,c=s.find((function(e){return e.id===i}));if(!c)throw new Error("React-Table: Could not find a column with id: "+i);var d=k(c.filter,a||{},xe),f=e.filters.find((function(e){return e.id===i})),p=m(u,f&&f.value);return H(d.autoRemove,p,c)?r({},e,{filters:e.filters.filter((function(e){return e.id!==i}))}):r({},e,f?{filters:e.filters.map((function(e){return e.id===i?{id:i,value:p}:e}))}:{filters:[].concat(e.filters,[{id:i,value:p}])})}if(t.type===l.setAllFilters){var g=t.filters,v=o.allColumns,h=o.filterTypes;return r({},e,{filters:m(g,e.filters).filter((function(e){var t=v.find((function(t){return t.id===e.id}));return !H(k(t.filter,h||{},xe).autoRemove,e.value,t)}))})}}function Ee(e){var n=e.data,o=e.rows,r=e.flatRows,i=e.rowsById,u=e.allColumns,s=e.filterTypes,a=e.manualFilters,c=e.defaultCanFilter,d=void 0!==c&&c,f=e.disableFilters,p=e.state.filters,g=e.dispatch,v=e.autoResetFilters,m=void 0===v||v,y=t.useCallback((function(e,t){g({type:l.setFilter,columnId:e,filterValue:t});}),[g]),R=t.useCallback((function(e){g({type:l.setAllFilters,filters:e});}),[g]);u.forEach((function(e){var t=e.id,n=e.accessor,o=e.defaultCanFilter,r=e.disableFilters;e.canFilter=n?I(!0!==r&&void 0,!0!==f&&void 0,!0):I(o,d,!1),e.setFilter=function(t){return y(e.id,t)};var i=p.find((function(e){return e.id===t}));e.filterValue=i&&i.value;}));var b=t.useMemo((function(){if(a||!p.length)return [o,r,i];var e=[],t={};return [function n(o,r){void 0===r&&(r=0);var i=o;return (i=p.reduce((function(e,t){var n=t.id,o=t.value,i=u.find((function(e){return e.id===n}));if(!i)return e;0===r&&(i.preFilteredRows=e);var l=k(i.filter,s||{},xe);return l?(i.filteredRows=l(e,[n],o),i.filteredRows):(console.warn("Could not find a valid 'column.filter' for column with the ID: "+i.id+"."),e)}),o)).forEach((function(o){e.push(o),t[o.id]=o,o.subRows&&(o.subRows=o.subRows&&o.subRows.length>0?n(o.subRows,r+1):o.subRows);})),i}(o),e,t]}),[a,p,o,r,i,u,s]),S=b[0],C=b[1],x=b[2];t.useMemo((function(){u.filter((function(e){return !p.find((function(t){return t.id===e.id}))})).forEach((function(e){e.preFilteredRows=S,e.filteredRows=S;}));}),[S,p,u]);var P=h(m);w((function(){P()&&g({type:l.resetFilters});}),[g,a?null:n]),Object.assign(e,{preFilteredRows:o,preFilteredFlatRows:r,preFilteredRowsById:i,filteredRows:S,filteredFlatRows:C,filteredRowsById:x,rows:S,flatRows:C,rowsById:x,setFilter:y,setAllFilters:R});}Pe.pluginName="useFilters",l.resetGlobalFilter="resetGlobalFilter",l.setGlobalFilter="setGlobalFilter";var Ie=function(e){e.stateReducers.push(Fe),e.useInstance.push(Ge);};function Fe(e,t,n,o){if(t.type===l.resetGlobalFilter)return r({},e,{globalFilter:o.initialState.globalFilter||void 0});if(t.type===l.setGlobalFilter){var u=t.filterValue,s=o.userFilterTypes,a=k(o.globalFilter,s||{},xe),c=m(u,e.globalFilter);if(H(a.autoRemove,c)){e.globalFilter;return i(e,["globalFilter"])}return r({},e,{globalFilter:c})}}function Ge(e){var n=e.data,o=e.rows,r=e.flatRows,i=e.rowsById,u=e.allColumns,s=e.filterTypes,a=e.globalFilter,c=e.manualGlobalFilter,d=e.state.globalFilter,f=e.dispatch,p=e.autoResetGlobalFilter,g=void 0===p||p,v=e.disableGlobalFilter,m=t.useCallback((function(e){f({type:l.setGlobalFilter,filterValue:e});}),[f]),y=t.useMemo((function(){if(c||void 0===d)return [o,r,i];var e=[],t={},n=k(a,s||{},xe);if(!n)return console.warn("Could not find a valid 'globalFilter' option."),o;u.forEach((function(e){var t=e.disableGlobalFilter;e.canFilter=I(!0!==t&&void 0,!0!==v&&void 0,!0);}));var l=u.filter((function(e){return !0===e.canFilter}));return [function o(r){return (r=n(r,l.map((function(e){return e.id})),d)).forEach((function(n){e.push(n),t[n.id]=n,n.subRows=n.subRows&&n.subRows.length?o(n.subRows):n.subRows;})),r}(o),e,t]}),[c,d,a,s,u,o,r,i,v]),R=y[0],b=y[1],S=y[2],C=h(g);w((function(){C()&&f({type:l.resetGlobalFilter});}),[f,c?null:n]),Object.assign(e,{preGlobalFilteredRows:o,preGlobalFilteredFlatRows:r,preGlobalFilteredRowsById:i,globalFilteredRows:R,globalFilteredFlatRows:b,globalFilteredRowsById:S,rows:R,flatRows:b,rowsById:S,setGlobalFilter:m,disableGlobalFilter:v});}function Ae(e,t){return t.reduce((function(e,t){return e+("number"==typeof t?t:0)}),0)}Ie.pluginName="useGlobalFilter";var ke=Object.freeze({__proto__:null,sum:Ae,min:function(e){var t=e[0]||0;return e.forEach((function(e){"number"==typeof e&&(t=Math.min(t,e));})),t},max:function(e){var t=e[0]||0;return e.forEach((function(e){"number"==typeof e&&(t=Math.max(t,e));})),t},minMax:function(e){var t=e[0]||0,n=e[0]||0;return e.forEach((function(e){"number"==typeof e&&(t=Math.min(t,e),n=Math.max(n,e));})),t+".."+n},average:function(e){return Ae(0,e)/e.length},median:function(e){if(!e.length)return null;var t=Math.floor(e.length/2),n=[].concat(e).sort((function(e,t){return e-t}));return e.length%2!=0?n[t]:(n[t-1]+n[t])/2},unique:function(e){return Array.from(new Set(e).values())},uniqueCount:function(e){return new Set(e).size},count:function(e){return e.length}}),He=[],We={};l.resetGroupBy="resetGroupBy",l.setGroupBy="setGroupBy",l.toggleGroupBy="toggleGroupBy";var ze=function(e){e.getGroupByToggleProps=[Te],e.stateReducers.push(Oe),e.visibleColumnsDeps.push((function(e,t){var n=t.instance;return [].concat(e,[n.state.groupBy])})),e.visibleColumns.push(Me),e.useInstance.push(Le),e.prepareRow.push(Ne);};ze.pluginName="useGroupBy";var Te=function(e,t){var n=t.header;return [e,{onClick:n.canGroupBy?function(e){e.persist(),n.toggleGroupBy();}:void 0,style:{cursor:n.canGroupBy?"pointer":void 0},title:"Toggle GroupBy"}]};function Oe(e,t,n,o){if(t.type===l.init)return r({groupBy:[]},e);if(t.type===l.resetGroupBy)return r({},e,{groupBy:o.initialState.groupBy||[]});if(t.type===l.setGroupBy)return r({},e,{groupBy:t.value});if(t.type===l.toggleGroupBy){var i=t.columnId,u=t.value,s=void 0!==u?u:!e.groupBy.includes(i);return r({},e,s?{groupBy:[].concat(e.groupBy,[i])}:{groupBy:e.groupBy.filter((function(e){return e!==i}))})}}function Me(e,t){var n=t.instance.state.groupBy,o=n.map((function(t){return e.find((function(e){return e.id===t}))})).filter(Boolean),r=e.filter((function(e){return !n.includes(e.id)}));return (e=[].concat(o,r)).forEach((function(e){e.isGrouped=n.includes(e.id),e.groupedIndex=n.indexOf(e.id);})),e}var je={};function Le(e){var n=e.data,o=e.rows,i=e.flatRows,u=e.rowsById,s=e.allColumns,a=e.flatHeaders,c=e.groupByFn,d=void 0===c?De:c,p=e.manualGroupBy,g=e.aggregations,m=void 0===g?je:g,y=e.plugins,R=e.state.groupBy,b=e.dispatch,S=e.autoResetGroupBy,C=void 0===S||S,x=e.disableGroupBy,P=e.defaultCanGroupBy,B=e.getHooks;v(y,["useColumnOrder","useFilters"],"useGroupBy");var E=h(e);s.forEach((function(t){var n=t.accessor,o=t.defaultGroupBy,r=t.disableGroupBy;t.canGroupBy=n?I(t.canGroupBy,!0!==r&&void 0,!0!==x&&void 0,!0):I(t.canGroupBy,o,P,!1),t.canGroupBy&&(t.toggleGroupBy=function(){return e.toggleGroupBy(t.id)}),t.Aggregated=t.Aggregated||t.Cell;}));var F=t.useCallback((function(e,t){b({type:l.toggleGroupBy,columnId:e,value:t});}),[b]),A=t.useCallback((function(e){b({type:l.setGroupBy,value:e});}),[b]);a.forEach((function(e){e.getGroupByToggleProps=f(B().getGroupByToggleProps,{instance:E(),header:e});}));var k=t.useMemo((function(){if(p||!R.length)return [o,i,u,He,We,i,u];var e=R.filter((function(e){return s.find((function(t){return t.id===e}))})),t=[],n={},l=[],a={},c=[],f={},g=function o(i,u,p){if(void 0===u&&(u=0),u===e.length)return i.map((function(e){return r({},e,{depth:u})}));var g=e[u],v=d(i,g);return Object.entries(v).map((function(r,i){var d=r[0],v=r[1],h=g+":"+d,y=o(v,u+1,h=p?p+">"+h:h),w=u?G(v,"leafRows"):v,R=function(t,n,o){var r={};return s.forEach((function(i){if(e.includes(i.id))r[i.id]=n[0]?n[0].values[i.id]:null;else {var u="function"==typeof i.aggregate?i.aggregate:m[i.aggregate]||ke[i.aggregate];if(u){var l=n.map((function(e){return e.values[i.id]})),s=t.map((function(e){var t=e.values[i.id];if(!o&&i.aggregateValue){var n="function"==typeof i.aggregateValue?i.aggregateValue:m[i.aggregateValue]||ke[i.aggregateValue];if(!n)throw console.info({column:i}),new Error("React Table: Invalid column.aggregateValue option for column listed above");t=n(t,e,i);}return t}));r[i.id]=u(s,l);}else {if(i.aggregate)throw console.info({column:i}),new Error("React Table: Invalid column.aggregate option for column listed above");r[i.id]=null;}}})),r}(w,v,u),b={id:h,isGrouped:!0,groupByID:g,groupByVal:d,values:R,subRows:y,leafRows:w,depth:u,index:i};return y.forEach((function(e){t.push(e),n[e.id]=e,e.isGrouped?(l.push(e),a[e.id]=e):(c.push(e),f[e.id]=e);})),b}))}(o);return g.forEach((function(e){t.push(e),n[e.id]=e,e.isGrouped?(l.push(e),a[e.id]=e):(c.push(e),f[e.id]=e);})),[g,t,n,l,a,c,f]}),[p,R,o,i,u,s,m,d]),H=k[0],W=k[1],z=k[2],T=k[3],O=k[4],M=k[5],j=k[6],L=h(C);w((function(){L()&&b({type:l.resetGroupBy});}),[b,p?null:n]),Object.assign(e,{preGroupedRows:o,preGroupedFlatRow:i,preGroupedRowsById:u,groupedRows:H,groupedFlatRows:W,groupedRowsById:z,onlyGroupedFlatRows:T,onlyGroupedRowsById:O,nonGroupedFlatRows:M,nonGroupedRowsById:j,rows:H,flatRows:W,rowsById:z,toggleGroupBy:F,setGroupBy:A});}function Ne(e){e.allCells.forEach((function(t){var n;t.isGrouped=t.column.isGrouped&&t.column.id===e.groupByID,t.isPlaceholder=!t.isGrouped&&t.column.isGrouped,t.isAggregated=!t.isGrouped&&!t.isPlaceholder&&(null==(n=e.subRows)?void 0:n.length);}));}function De(e,t){return e.reduce((function(e,n,o){var r=""+n.values[t];return e[r]=Array.isArray(e[r])?e[r]:[],e[r].push(n),e}),{})}var Ve=/([0-9]+)/gm;function _e(e,t){return e===t?0:e>t?1:-1}function Xe(e,t,n){return [e.values[n],t.values[n]]}function qe(e){return "number"==typeof e?isNaN(e)||e===1/0||e===-1/0?"":String(e):"string"==typeof e?e:""}var Ke=Object.freeze({__proto__:null,alphanumeric:function(e,t,n){var o=Xe(e,t,n),r=o[0],i=o[1];for(r=qe(r),i=qe(i),r=r.split(Ve).filter(Boolean),i=i.split(Ve).filter(Boolean);r.length&&i.length;){var u=r.shift(),l=i.shift(),s=parseInt(u,10),a=parseInt(l,10),c=[s,a].sort();if(isNaN(c[0])){if(u>l)return 1;if(l>u)return -1}else {if(isNaN(c[1]))return isNaN(s)?-1:1;if(s>a)return 1;if(a>s)return -1}}return r.length-i.length},datetime:function(e,t,n){var o=Xe(e,t,n),r=o[0],i=o[1];return _e(r=r.getTime(),i=i.getTime())},basic:function(e,t,n){var o=Xe(e,t,n);return _e(o[0],o[1])},string:function(e,t,n){var o=Xe(e,t,n),r=o[0],i=o[1];for(r=r.split("").filter(Boolean),i=i.split("").filter(Boolean);r.length&&i.length;){var u=r.shift(),l=i.shift(),s=u.toLowerCase(),a=l.toLowerCase();if(s>a)return 1;if(a>s)return -1;if(u>l)return 1;if(l>u)return -1}return r.length-i.length},number:function(e,t,n){var o=Xe(e,t,n),r=o[0],i=o[1],u=/[^0-9.]/gi;return _e(r=Number(String(r).replace(u,"")),i=Number(String(i).replace(u,"")))}});l.resetSortBy="resetSortBy",l.setSortBy="setSortBy",l.toggleSortBy="toggleSortBy",l.clearSortBy="clearSortBy",c.sortType="alphanumeric",c.sortDescFirst=!1;var Ue=function(e){e.getSortByToggleProps=[$e],e.stateReducers.push(Je),e.useInstance.push(Ye);};Ue.pluginName="useSortBy";var $e=function(e,t){var n=t.instance,o=t.column,r=n.isMultiSortEvent,i=void 0===r?function(e){return e.shiftKey}:r;return [e,{onClick:o.canSort?function(e){e.persist(),o.toggleSortBy(void 0,!n.disableMultiSort&&i(e));}:void 0,style:{cursor:o.canSort?"pointer":void 0},title:o.canSort?"Toggle SortBy":void 0}]};function Je(e,t,n,o){if(t.type===l.init)return r({sortBy:[]},e);if(t.type===l.resetSortBy)return r({},e,{sortBy:o.initialState.sortBy||[]});if(t.type===l.clearSortBy)return r({},e,{sortBy:e.sortBy.filter((function(e){return e.id!==t.columnId}))});if(t.type===l.setSortBy)return r({},e,{sortBy:t.sortBy});if(t.type===l.toggleSortBy){var i,u=t.columnId,s=t.desc,a=t.multi,c=o.allColumns,d=o.disableMultiSort,f=o.disableSortRemove,p=o.disableMultiRemove,g=o.maxMultiSortColCount,v=void 0===g?Number.MAX_SAFE_INTEGER:g,m=e.sortBy,h=c.find((function(e){return e.id===u})).sortDescFirst,y=m.find((function(e){return e.id===u})),w=m.findIndex((function(e){return e.id===u})),R=null!=s,b=[];return "toggle"!==(i=!d&&a?y?"toggle":"add":w!==m.length-1||1!==m.length?"replace":y?"toggle":"replace")||f||R||a&&p||!(y&&y.desc&&!h||!y.desc&&h)||(i="remove"),"replace"===i?b=[{id:u,desc:R?s:h}]:"add"===i?(b=[].concat(m,[{id:u,desc:R?s:h}])).splice(0,b.length-v):"toggle"===i?b=m.map((function(e){return e.id===u?r({},e,{desc:R?s:!y.desc}):e})):"remove"===i&&(b=m.filter((function(e){return e.id!==u}))),r({},e,{sortBy:b})}}function Ye(e){var n=e.data,o=e.rows,r=e.flatRows,i=e.allColumns,u=e.orderByFn,s=void 0===u?Qe:u,a=e.sortTypes,c=e.manualSortBy,d=e.defaultCanSort,p=e.disableSortBy,g=e.flatHeaders,m=e.state.sortBy,y=e.dispatch,R=e.plugins,b=e.getHooks,S=e.autoResetSortBy,C=void 0===S||S;v(R,["useFilters","useGlobalFilter","useGroupBy","usePivotColumns"],"useSortBy");var x=t.useCallback((function(e){y({type:l.setSortBy,sortBy:e});}),[y]),P=t.useCallback((function(e,t,n){y({type:l.toggleSortBy,columnId:e,desc:t,multi:n});}),[y]),B=h(e);g.forEach((function(e){var t=e.accessor,n=e.canSort,o=e.disableSortBy,r=e.id,i=t?I(!0!==o&&void 0,!0!==p&&void 0,!0):I(d,n,!1);e.canSort=i,e.canSort&&(e.toggleSortBy=function(t,n){return P(e.id,t,n)},e.clearSortBy=function(){y({type:l.clearSortBy,columnId:e.id});}),e.getSortByToggleProps=f(b().getSortByToggleProps,{instance:B(),column:e});var u=m.find((function(e){return e.id===r}));e.isSorted=!!u,e.sortedIndex=m.findIndex((function(e){return e.id===r})),e.isSortedDesc=e.isSorted?u.desc:void 0;}));var E=t.useMemo((function(){if(c||!m.length)return [o,r];var e=[],t=m.filter((function(e){return i.find((function(t){return t.id===e.id}))}));return [function n(o){var r=s(o,t.map((function(e){var t=i.find((function(t){return t.id===e.id}));if(!t)throw new Error("React-Table: Could not find a column with id: "+e.id+" while sorting");var n=t.sortType,o=F(n)||(a||{})[n]||Ke[n];if(!o)throw new Error("React-Table: Could not find a valid sortType of '"+n+"' for column '"+e.id+"'.");return function(t,n){return o(t,n,e.id,e.desc)}})),t.map((function(e){var t=i.find((function(t){return t.id===e.id}));return t&&t.sortInverted?e.desc:!e.desc})));return r.forEach((function(t){e.push(t),t.subRows&&0!==t.subRows.length&&(t.subRows=n(t.subRows));})),r}(o),e]}),[c,m,o,r,i,s,a]),G=E[0],A=E[1],k=h(C);w((function(){k()&&y({type:l.resetSortBy});}),[c?null:n]),Object.assign(e,{preSortedRows:o,preSortedFlatRows:r,sortedRows:G,sortedFlatRows:A,rows:G,flatRows:A,setSortBy:x,toggleSortBy:P});}function Qe(e,t,n){return [].concat(e).sort((function(e,o){for(var r=0;re.pageIndex?a=-1===i?u.length>=e.pageSize:s-1),a?r({},e,{pageIndex:s}):e}if(t.type===l.setPageSize){var c=t.pageSize,d=e.pageSize*e.pageIndex;return r({},e,{pageIndex:Math.floor(d/c),pageSize:c})}}function tt(e){var n=e.rows,o=e.autoResetPage,r=void 0===o||o,i=e.manualExpandedKey,u=void 0===i?"expanded":i,s=e.plugins,a=e.pageCount,c=e.paginateExpandedRows,d=void 0===c||c,f=e.expandSubRows,p=void 0===f||f,g=e.state,m=g.pageSize,y=g.pageIndex,R=g.expanded,b=g.globalFilter,S=g.filters,C=g.groupBy,x=g.sortBy,P=e.dispatch,B=e.data,E=e.manualPagination;v(s,["useGlobalFilter","useFilters","useGroupBy","useSortBy","useExpanded"],"usePagination");var I=h(r);w((function(){I()&&P({type:l.resetPage});}),[P,E?null:B,b,S,C,x]);var F=E?a:Math.ceil(n.length/m),G=t.useMemo((function(){return F>0?[].concat(new Array(F)).fill(null).map((function(e,t){return t})):[]}),[F]),k=t.useMemo((function(){var e;if(E)e=n;else {var t=m*y,o=t+m;e=n.slice(t,o);}return d?e:A(e,{manualExpandedKey:u,expanded:R,expandSubRows:p})}),[p,R,u,E,y,m,d,n]),H=y>0,W=-1===F?k.length>=m:y-1&&i.push(r.splice(t,1)[0]);};r.length&&o.length;)u();return [].concat(i,r)}function At(e){var n=e.dispatch;e.setColumnOrder=t.useCallback((function(e){return n({type:l.setColumnOrder,columnOrder:e})}),[n]);}It.pluginName="useColumnOrder",c.canResize=!0,l.columnStartResizing="columnStartResizing",l.columnResizing="columnResizing",l.columnDoneResizing="columnDoneResizing",l.resetResize="resetResize";var kt=function(e){e.getResizerProps=[Ht],e.getHeaderProps.push({style:{position:"relative"}}),e.stateReducers.push(Wt),e.useInstance.push(Tt),e.useInstanceBeforeDimensions.push(zt);},Ht=function(e,t){var n=t.instance,o=t.header,r=n.dispatch,i=function(e,t){var n=!1;if("touchstart"===e.type){if(e.touches&&e.touches.length>1)return;n=!0;}var o,i,u=function(e){var t=[];return function e(n){n.columns&&n.columns.length&&n.columns.map(e);t.push(n);}(e),t}(t).map((function(e){return [e.id,e.totalWidth]})),s=n?Math.round(e.touches[0].clientX):e.clientX,a=function(){window.cancelAnimationFrame(o),o=null,r({type:l.columnDoneResizing});},c=function(){window.cancelAnimationFrame(o),o=null,r({type:l.columnResizing,clientX:i});},d=function(e){i=e,o||(o=window.requestAnimationFrame(c));},f={mouse:{moveEvent:"mousemove",moveHandler:function(e){return d(e.clientX)},upEvent:"mouseup",upHandler:function(e){document.removeEventListener("mousemove",f.mouse.moveHandler),document.removeEventListener("mouseup",f.mouse.upHandler),a();}},touch:{moveEvent:"touchmove",moveHandler:function(e){return e.cancelable&&(e.preventDefault(),e.stopPropagation()),d(e.touches[0].clientX),!1},upEvent:"touchend",upHandler:function(e){document.removeEventListener(f.touch.moveEvent,f.touch.moveHandler),document.removeEventListener(f.touch.upEvent,f.touch.moveHandler),a();}}},p=n?f.touch:f.mouse,g=!!function(){if("boolean"==typeof z)return z;var e=!1;try{var t={get passive(){return e=!0,!1}};window.addEventListener("test",null,t),window.removeEventListener("test",null,t);}catch(t){e=!1;}return z=e}()&&{passive:!1};document.addEventListener(p.moveEvent,p.moveHandler,g),document.addEventListener(p.upEvent,p.upHandler,g),r({type:l.columnStartResizing,columnId:t.id,columnWidth:t.totalWidth,headerIdWidths:u,clientX:s});};return [e,{onMouseDown:function(e){return e.persist()||i(e,o)},onTouchStart:function(e){return e.persist()||i(e,o)},style:{cursor:"col-resize"},draggable:!1,role:"separator"}]};function Wt(e,t){if(t.type===l.init)return r({columnResizing:{columnWidths:{}}},e);if(t.type===l.resetResize)return r({},e,{columnResizing:{columnWidths:{}}});if(t.type===l.columnStartResizing){var n=t.clientX,o=t.columnId,i=t.columnWidth,u=t.headerIdWidths;return r({},e,{columnResizing:r({},e.columnResizing,{startX:n,headerIdWidths:u,columnWidth:i,isResizingColumn:o})})}if(t.type===l.columnResizing){var s=t.clientX,a=e.columnResizing,c=a.startX,d=a.columnWidth,f=a.headerIdWidths,p=(s-c)/d,g={};return (void 0===f?[]:f).forEach((function(e){var t=e[0],n=e[1];g[t]=Math.max(n+n*p,0);})),r({},e,{columnResizing:r({},e.columnResizing,{columnWidths:r({},e.columnResizing.columnWidths,{},g)})})}return t.type===l.columnDoneResizing?r({},e,{columnResizing:r({},e.columnResizing,{startX:null,isResizingColumn:null})}):void 0}kt.pluginName="useResizeColumns";var zt=function(e){var t=e.flatHeaders,n=e.disableResizing,o=e.getHooks,r=e.state.columnResizing,i=h(e);t.forEach((function(e){var t=I(!0!==e.disableResizing&&void 0,!0!==n&&void 0,!0);e.canResize=t,e.width=r.columnWidths[e.id]||e.originalWidth||e.width,e.isResizing=r.isResizingColumn===e.id,t&&(e.getResizerProps=f(o().getResizerProps,{instance:i(),header:e}));}));};function Tt(e){var n=e.plugins,o=e.dispatch,r=e.autoResetResize,i=void 0===r||r,u=e.columns;v(n,["useAbsoluteLayout"],"useResizeColumns");var s=h(i);w((function(){s()&&o({type:l.resetResize});}),[u]);var a=t.useCallback((function(){return o({type:l.resetResize})}),[o]);Object.assign(e,{resetResizing:a});}var Ot={position:"absolute",top:0},Mt=function(e){e.getTableBodyProps.push(jt),e.getRowProps.push(jt),e.getHeaderGroupProps.push(jt),e.getFooterGroupProps.push(jt),e.getHeaderProps.push((function(e,t){var n=t.column;return [e,{style:r({},Ot,{left:n.totalLeft+"px",width:n.totalWidth+"px"})}]})),e.getCellProps.push((function(e,t){var n=t.cell;return [e,{style:r({},Ot,{left:n.column.totalLeft+"px",width:n.column.totalWidth+"px"})}]})),e.getFooterProps.push((function(e,t){var n=t.column;return [e,{style:r({},Ot,{left:n.totalLeft+"px",width:n.totalWidth+"px"})}]}));};Mt.pluginName="useAbsoluteLayout";var jt=function(e,t){return [e,{style:{position:"relative",width:t.instance.totalColumnsWidth+"px"}}]},Lt={display:"inline-block",boxSizing:"border-box"},Nt=function(e,t){return [e,{style:{display:"flex",width:t.instance.totalColumnsWidth+"px"}}]},Dt=function(e){e.getRowProps.push(Nt),e.getHeaderGroupProps.push(Nt),e.getFooterGroupProps.push(Nt),e.getHeaderProps.push((function(e,t){var n=t.column;return [e,{style:r({},Lt,{width:n.totalWidth+"px"})}]})),e.getCellProps.push((function(e,t){var n=t.cell;return [e,{style:r({},Lt,{width:n.column.totalWidth+"px"})}]})),e.getFooterProps.push((function(e,t){var n=t.column;return [e,{style:r({},Lt,{width:n.totalWidth+"px"})}]}));};function Vt(e){e.getTableProps.push(_t),e.getRowProps.push(Xt),e.getHeaderGroupProps.push(Xt),e.getFooterGroupProps.push(Xt),e.getHeaderProps.push(qt),e.getCellProps.push(Kt),e.getFooterProps.push(Ut);}Dt.pluginName="useBlockLayout",Vt.pluginName="useFlexLayout";var _t=function(e,t){return [e,{style:{minWidth:t.instance.totalColumnsMinWidth+"px"}}]},Xt=function(e,t){return [e,{style:{display:"flex",flex:"1 0 auto",minWidth:t.instance.totalColumnsMinWidth+"px"}}]},qt=function(e,t){var n=t.column;return [e,{style:{boxSizing:"border-box",flex:n.totalFlexWidth?n.totalFlexWidth+" 0 auto":void 0,minWidth:n.totalMinWidth+"px",width:n.totalWidth+"px"}}]},Kt=function(e,t){var n=t.cell;return [e,{style:{boxSizing:"border-box",flex:n.column.totalFlexWidth+" 0 auto",minWidth:n.column.totalMinWidth+"px",width:n.column.totalWidth+"px"}}]},Ut=function(e,t){var n=t.column;return [e,{style:{boxSizing:"border-box",flex:n.totalFlexWidth?n.totalFlexWidth+" 0 auto":void 0,minWidth:n.totalMinWidth+"px",width:n.totalWidth+"px"}}]};function $t(e){e.stateReducers.push(Zt),e.getTableProps.push(Jt),e.getHeaderProps.push(Yt),e.getRowProps.push(Qt);}l.columnStartResizing="columnStartResizing",l.columnResizing="columnResizing",l.columnDoneResizing="columnDoneResizing",l.resetResize="resetResize",$t.pluginName="useGridLayout";var Jt=function(e,t){var n=t.instance;return [e,{style:{display:"grid",gridTemplateColumns:n.visibleColumns.map((function(e){var t;return n.state.gridLayout.columnWidths[e.id]?n.state.gridLayout.columnWidths[e.id]+"px":(null==(t=n.state.columnResizing)?void 0:t.isResizingColumn)?n.state.gridLayout.startWidths[e.id]+"px":"number"==typeof e.width?e.width+"px":e.width})).join(" ")}}]},Yt=function(e,t){var n=t.column;return [e,{id:"header-cell-"+n.id,style:{position:"sticky",gridColumn:"span "+n.totalVisibleHeaderCount}}]},Qt=function(e,t){var n=t.row;return n.isExpanded?[e,{style:{gridColumn:"1 / "+(n.cells.length+1)}}]:[e,{}]};function Zt(e,t,n,o){if(t.type===l.init)return r({gridLayout:{columnWidths:{}}},e);if(t.type===l.resetResize)return r({},e,{gridLayout:{columnWidths:{}}});if(t.type===l.columnStartResizing){var i=t.columnId,u=t.headerIdWidths,s=en(i);if(void 0!==s){var a=o.visibleColumns.reduce((function(e,t){var n;return r({},e,((n={})[t.id]=en(t.id),n))}),{}),c=o.visibleColumns.reduce((function(e,t){var n;return r({},e,((n={})[t.id]=t.minWidth,n))}),{}),d=o.visibleColumns.reduce((function(e,t){var n;return r({},e,((n={})[t.id]=t.maxWidth,n))}),{}),f=u.map((function(e){var t=e[0];return [t,en(t)]}));return r({},e,{gridLayout:r({},e.gridLayout,{startWidths:a,minWidths:c,maxWidths:d,headerIdGridWidths:f,columnWidth:s})})}return e}if(t.type===l.columnResizing){var p=t.clientX,g=e.columnResizing.startX,v=e.gridLayout,m=v.columnWidth,h=v.minWidths,y=v.maxWidths,w=v.headerIdGridWidths,R=(p-g)/m,b={};return (void 0===w?[]:w).forEach((function(e){var t=e[0],n=e[1];b[t]=Math.min(Math.max(h[t],n+n*R),y[t]);})),r({},e,{gridLayout:r({},e.gridLayout,{columnWidths:r({},e.gridLayout.columnWidths,{},b)})})}return t.type===l.columnDoneResizing?r({},e,{gridLayout:r({},e.gridLayout,{startWidths:{},minWidths:{},maxWidths:{}})}):void 0}function en(e){var t,n=null==(t=document.getElementById("header-cell-"+e))?void 0:t.offsetWidth;if(void 0!==n)return n}e._UNSTABLE_usePivotColumns=nt,e.actions=l,e.defaultColumn=c,e.defaultGroupByFn=De,e.defaultOrderByFn=Qe,e.defaultRenderer=s,e.emptyRenderer=a,e.ensurePluginOrder=v,e.flexRender=b,e.functionalUpdate=m,e.loopHooks=g,e.makePropGetter=f,e.makeRenderer=R,e.reduceHooks=p,e.safeUseLayoutEffect=y,e.useAbsoluteLayout=Mt,e.useAsyncDebounce=function(e,n){void 0===n&&(n=0);var r=t.useRef({}),i=h(e),u=h(n);return t.useCallback(function(){var e=o(regeneratorRuntime.mark((function e(){var t,n,l,s=arguments;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:for(t=s.length,n=new Array(t),l=0;l1?n-1:0),i=1;i value === null || value === undefined; + +// eslint-disable-next-line unicorn/prefer-code-point +const strictUriEncode = string => encodeURIComponent(string).replace(/[!'()*]/g, x => `%${x.charCodeAt(0).toString(16).toUpperCase()}`); + +const encodeFragmentIdentifier = Symbol('encodeFragmentIdentifier'); + +function encoderForArrayFormat(options) { + switch (options.arrayFormat) { + case 'index': { + return key => (result, value) => { + const index = result.length; + + if ( + value === undefined + || (options.skipNull && value === null) + || (options.skipEmptyString && value === '') + ) { + return result; + } + + if (value === null) { + return [ + ...result, [encode(key, options), '[', index, ']'].join(''), + ]; + } + + return [ + ...result, + [encode(key, options), '[', encode(index, options), ']=', encode(value, options)].join(''), + ]; + }; + } + + case 'bracket': { + return key => (result, value) => { + if ( + value === undefined + || (options.skipNull && value === null) + || (options.skipEmptyString && value === '') + ) { + return result; + } + + if (value === null) { + return [ + ...result, + [encode(key, options), '[]'].join(''), + ]; + } + + return [ + ...result, + [encode(key, options), '[]=', encode(value, options)].join(''), + ]; + }; + } + + case 'colon-list-separator': { + return key => (result, value) => { + if ( + value === undefined + || (options.skipNull && value === null) + || (options.skipEmptyString && value === '') + ) { + return result; + } + + if (value === null) { + return [ + ...result, + [encode(key, options), ':list='].join(''), + ]; + } + + return [ + ...result, + [encode(key, options), ':list=', encode(value, options)].join(''), + ]; + }; + } + + case 'comma': + case 'separator': + case 'bracket-separator': { + const keyValueSep = options.arrayFormat === 'bracket-separator' + ? '[]=' + : '='; + + return key => (result, value) => { + if ( + value === undefined + || (options.skipNull && value === null) + || (options.skipEmptyString && value === '') + ) { + return result; + } + + // Translate null to an empty string so that it doesn't serialize as 'null' + value = value === null ? '' : value; + + if (result.length === 0) { + return [[encode(key, options), keyValueSep, encode(value, options)].join('')]; + } + + return [[result, encode(value, options)].join(options.arrayFormatSeparator)]; + }; + } + + default: { + return key => (result, value) => { + if ( + value === undefined + || (options.skipNull && value === null) + || (options.skipEmptyString && value === '') + ) { + return result; + } + + if (value === null) { + return [ + ...result, + encode(key, options), + ]; + } + + return [ + ...result, + [encode(key, options), '=', encode(value, options)].join(''), + ]; + }; + } + } +} + +function parserForArrayFormat(options) { + let result; + + switch (options.arrayFormat) { + case 'index': { + return (key, value, accumulator) => { + result = /\[(\d*)]$/.exec(key); + + key = key.replace(/\[\d*]$/, ''); + + if (!result) { + accumulator[key] = value; + return; + } + + if (accumulator[key] === undefined) { + accumulator[key] = {}; + } + + accumulator[key][result[1]] = value; + }; + } + + case 'bracket': { + return (key, value, accumulator) => { + result = /(\[])$/.exec(key); + key = key.replace(/\[]$/, ''); + + if (!result) { + accumulator[key] = value; + return; + } + + if (accumulator[key] === undefined) { + accumulator[key] = [value]; + return; + } + + accumulator[key] = [...accumulator[key], value]; + }; + } + + case 'colon-list-separator': { + return (key, value, accumulator) => { + result = /(:list)$/.exec(key); + key = key.replace(/:list$/, ''); + + if (!result) { + accumulator[key] = value; + return; + } + + if (accumulator[key] === undefined) { + accumulator[key] = [value]; + return; + } + + accumulator[key] = [...accumulator[key], value]; + }; + } + + case 'comma': + case 'separator': { + return (key, value, accumulator) => { + const isArray = typeof value === 'string' && value.includes(options.arrayFormatSeparator); + const isEncodedArray = (typeof value === 'string' && !isArray && decode(value, options).includes(options.arrayFormatSeparator)); + value = isEncodedArray ? decode(value, options) : value; + const newValue = isArray || isEncodedArray ? value.split(options.arrayFormatSeparator).map(item => decode(item, options)) : (value === null ? value : decode(value, options)); + accumulator[key] = newValue; + }; + } + + case 'bracket-separator': { + return (key, value, accumulator) => { + const isArray = /(\[])$/.test(key); + key = key.replace(/\[]$/, ''); + + if (!isArray) { + accumulator[key] = value ? decode(value, options) : value; + return; + } + + const arrayValue = value === null + ? [] + : value.split(options.arrayFormatSeparator).map(item => decode(item, options)); + + if (accumulator[key] === undefined) { + accumulator[key] = arrayValue; + return; + } + + accumulator[key] = [...accumulator[key], ...arrayValue]; + }; + } + + default: { + return (key, value, accumulator) => { + if (accumulator[key] === undefined) { + accumulator[key] = value; + return; + } + + accumulator[key] = [...[accumulator[key]].flat(), value]; + }; + } + } +} + +function validateArrayFormatSeparator(value) { + if (typeof value !== 'string' || value.length !== 1) { + throw new TypeError('arrayFormatSeparator must be single character string'); + } +} + +function encode(value, options) { + if (options.encode) { + return options.strict ? strictUriEncode(value) : encodeURIComponent(value); + } + + return value; +} + +function decode(value, options) { + if (options.decode) { + return decodeUriComponent(value); + } + + return value; +} + +function keysSorter(input) { + if (Array.isArray(input)) { + return input.sort(); + } + + if (typeof input === 'object') { + return keysSorter(Object.keys(input)) + .sort((a, b) => Number(a) - Number(b)) + .map(key => input[key]); + } + + return input; +} + +function removeHash(input) { + const hashStart = input.indexOf('#'); + if (hashStart !== -1) { + input = input.slice(0, hashStart); + } + + return input; +} + +function getHash(url) { + let hash = ''; + const hashStart = url.indexOf('#'); + if (hashStart !== -1) { + hash = url.slice(hashStart); + } + + return hash; +} + +function parseValue(value, options) { + if (options.parseNumbers && !Number.isNaN(Number(value)) && (typeof value === 'string' && value.trim() !== '')) { + value = Number(value); + } else if (options.parseBooleans && value !== null && (value.toLowerCase() === 'true' || value.toLowerCase() === 'false')) { + value = value.toLowerCase() === 'true'; + } + + return value; +} + +function extract(input) { + input = removeHash(input); + const queryStart = input.indexOf('?'); + if (queryStart === -1) { + return ''; + } + + return input.slice(queryStart + 1); +} + +function parse(query, options) { + options = { + decode: true, + sort: true, + arrayFormat: 'none', + arrayFormatSeparator: ',', + parseNumbers: false, + parseBooleans: false, + ...options, + }; + + validateArrayFormatSeparator(options.arrayFormatSeparator); + + const formatter = parserForArrayFormat(options); + + // Create an object with no prototype + const returnValue = Object.create(null); + + if (typeof query !== 'string') { + return returnValue; + } + + query = query.trim().replace(/^[?#&]/, ''); + + if (!query) { + return returnValue; + } + + for (const parameter of query.split('&')) { + if (parameter === '') { + continue; + } + + const parameter_ = options.decode ? parameter.replace(/\+/g, ' ') : parameter; + + let [key, value] = splitOnFirst(parameter_, '='); + + if (key === undefined) { + key = parameter_; + } + + // Missing `=` should be `null`: + // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters + value = value === undefined ? null : (['comma', 'separator', 'bracket-separator'].includes(options.arrayFormat) ? value : decode(value, options)); + formatter(decode(key, options), value, returnValue); + } + + for (const [key, value] of Object.entries(returnValue)) { + if (typeof value === 'object' && value !== null) { + for (const [key2, value2] of Object.entries(value)) { + value[key2] = parseValue(value2, options); + } + } else { + returnValue[key] = parseValue(value, options); + } + } + + if (options.sort === false) { + return returnValue; + } + + // TODO: Remove the use of `reduce`. + // eslint-disable-next-line unicorn/no-array-reduce + return (options.sort === true ? Object.keys(returnValue).sort() : Object.keys(returnValue).sort(options.sort)).reduce((result, key) => { + const value = returnValue[key]; + if (Boolean(value) && typeof value === 'object' && !Array.isArray(value)) { + // Sort object keys, not values + result[key] = keysSorter(value); + } else { + result[key] = value; + } + + return result; + }, Object.create(null)); +} + +function stringify(object, options) { + if (!object) { + return ''; + } + + options = {encode: true, + strict: true, + arrayFormat: 'none', + arrayFormatSeparator: ',', ...options}; + + validateArrayFormatSeparator(options.arrayFormatSeparator); + + const shouldFilter = key => ( + (options.skipNull && isNullOrUndefined(object[key])) + || (options.skipEmptyString && object[key] === '') + ); + + const formatter = encoderForArrayFormat(options); + + const objectCopy = {}; + + for (const [key, value] of Object.entries(object)) { + if (!shouldFilter(key)) { + objectCopy[key] = value; + } + } + + const keys = Object.keys(objectCopy); + + if (options.sort !== false) { + keys.sort(options.sort); + } + + return keys.map(key => { + const value = object[key]; + + if (value === undefined) { + return ''; + } + + if (value === null) { + return encode(key, options); + } + + if (Array.isArray(value)) { + if (value.length === 0 && options.arrayFormat === 'bracket-separator') { + return encode(key, options) + '[]'; + } + + return value + .reduce(formatter(key), []) + .join('&'); + } + + return encode(key, options) + '=' + encode(value, options); + }).filter(x => x.length > 0).join('&'); +} + +function parseUrl(url, options) { + options = { + decode: true, + ...options, + }; + + let [url_, hash] = splitOnFirst(url, '#'); + + if (url_ === undefined) { + url_ = url; + } + + return { + url: url_?.split('?')?.[0] ?? '', + query: parse(extract(url), options), + ...(options && options.parseFragmentIdentifier && hash ? {fragmentIdentifier: decode(hash, options)} : {}), + }; +} + +function stringifyUrl(object, options) { + options = { + encode: true, + strict: true, + [encodeFragmentIdentifier]: true, + ...options, + }; + + const url = removeHash(object.url).split('?')[0] || ''; + const queryFromUrl = extract(object.url); + + const query = { + ...parse(queryFromUrl, {sort: false}), + ...object.query, + }; + + let queryString = stringify(query, options); + if (queryString) { + queryString = `?${queryString}`; + } + + let hash = getHash(object.url); + if (object.fragmentIdentifier) { + const urlObjectForFragmentEncode = new URL(url); + urlObjectForFragmentEncode.hash = object.fragmentIdentifier; + hash = options[encodeFragmentIdentifier] ? urlObjectForFragmentEncode.hash : `#${object.fragmentIdentifier}`; + } + + return `${url}${queryString}${hash}`; +} + +function pick(input, filter, options) { + options = { + parseFragmentIdentifier: true, + [encodeFragmentIdentifier]: false, + ...options, + }; + + const {url, query, fragmentIdentifier} = parseUrl(input, options); + + return stringifyUrl({ + url, + query: includeKeys(query, filter), + fragmentIdentifier, + }, options); +} + +function exclude(input, filter, options) { + const exclusionFilter = Array.isArray(filter) ? key => !filter.includes(key) : (key, value) => !filter(key, value); + + return pick(input, exclusionFilter, options); +} + +var queryString = /*#__PURE__*/Object.freeze({ + __proto__: null, + exclude: exclude, + extract: extract, + parse: parse, + parseUrl: parseUrl, + pick: pick, + stringify: stringify, + stringifyUrl: stringifyUrl +}); + +var asctime = function (duration) { + var milliseconds = parseInt("".concat((duration % 1000) / 100), 10), seconds = Math.floor((duration / 1000) % 60), minutes = Math.floor((duration / (1000 * 60)) % 60), hours = Math.floor((duration / (1000 * 60 * 60)) % 24); + var hours_ = hours < 10 ? '0' + hours : hours; + var minutes_ = minutes < 10 ? '0' + minutes : minutes; + var seconds_ = seconds < 10 ? '0' + seconds : seconds; + return hours_ + ':' + minutes_ + ':' + seconds_ + '.' + milliseconds; +}; +var filter = function (iterable, condition) { + var result = []; + for (var _i = 0, iterable_1 = iterable; _i < iterable_1.length; _i++) { + var item = iterable_1[_i]; + if (condition(item)) { + result.push(item); + } + } + return result; +}; +var SETTINGS_KEY = 'minimal-history-plugin'; +var loadSettings = function () { + var parsed = queryString.parse(location.hash.substring(location.hash.split('?', 1)[0].length + 1)); + try { + var raw = JSON.parse(localStorage.getItem(SETTINGS_KEY) || '{}'); + return { + showHistoricBadges: !!(raw === null || raw === void 0 ? void 0 : raw.showHistoricBadges) || !!parsed.showHistoricBadges, + showSequenceFlow: !!(raw === null || raw === void 0 ? void 0 : raw.showSequenceFlow) || !!parsed.showSequenceFlow, + leftPaneSize: !!(raw === null || raw === void 0 ? void 0 : raw.leftPaneSize) ? raw.leftPaneSize : null, + topPaneSize: !!(raw === null || raw === void 0 ? void 0 : raw.topPaneSize) ? raw.topPaneSize : null, + }; + } + catch (e) { + return { + showHistoricBadges: false, + showSequenceFlow: false, + leftPaneSize: null, + topPaneSize: null, + }; + } +}; +var saveSettings = function (settings) { + localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings)); +}; + +var Component = {}; + +var toggleSelection = function () { + var selection = document.getSelection(); + if (!selection.rangeCount) { + return function () {}; + } + var active = document.activeElement; + + var ranges = []; + for (var i = 0; i < selection.rangeCount; i++) { + ranges.push(selection.getRangeAt(i)); + } + + switch (active.tagName.toUpperCase()) { // .toUpperCase handles XHTML + case 'INPUT': + case 'TEXTAREA': + active.blur(); + break; + + default: + active = null; + break; + } + + selection.removeAllRanges(); + return function () { + selection.type === 'Caret' && + selection.removeAllRanges(); + + if (!selection.rangeCount) { + ranges.forEach(function(range) { + selection.addRange(range); + }); + } + + active && + active.focus(); + }; +}; + +var deselectCurrent = toggleSelection; + +var clipboardToIE11Formatting = { + "text/plain": "Text", + "text/html": "Url", + "default": "Text" +}; + +var defaultMessage = "Copy to clipboard: #{key}, Enter"; + +function format(message) { + var copyKey = (/mac os x/i.test(navigator.userAgent) ? "⌘" : "Ctrl") + "+C"; + return message.replace(/#{\s*key\s*}/g, copyKey); +} + +function copy(text, options) { + var debug, + message, + reselectPrevious, + range, + selection, + mark, + success = false; + if (!options) { + options = {}; + } + debug = options.debug || false; + try { + reselectPrevious = deselectCurrent(); + + range = document.createRange(); + selection = document.getSelection(); + + mark = document.createElement("span"); + mark.textContent = text; + // avoid screen readers from reading out loud the text + mark.ariaHidden = "true"; + // reset user styles for span element + mark.style.all = "unset"; + // prevents scrolling to the end of the page + mark.style.position = "fixed"; + mark.style.top = 0; + mark.style.clip = "rect(0, 0, 0, 0)"; + // used to preserve spaces and line breaks + mark.style.whiteSpace = "pre"; + // do not inherit user-select (it may be `none`) + mark.style.webkitUserSelect = "text"; + mark.style.MozUserSelect = "text"; + mark.style.msUserSelect = "text"; + mark.style.userSelect = "text"; + mark.addEventListener("copy", function(e) { + e.stopPropagation(); + if (options.format) { + e.preventDefault(); + if (typeof e.clipboardData === "undefined") { // IE 11 + debug && console.warn("unable to use e.clipboardData"); + debug && console.warn("trying IE specific stuff"); + window.clipboardData.clearData(); + var format = clipboardToIE11Formatting[options.format] || clipboardToIE11Formatting["default"]; + window.clipboardData.setData(format, text); + } else { // all other browsers + e.clipboardData.clearData(); + e.clipboardData.setData(options.format, text); + } + } + if (options.onCopy) { + e.preventDefault(); + options.onCopy(e.clipboardData); + } + }); + + document.body.appendChild(mark); + + range.selectNodeContents(mark); + selection.addRange(range); + + var successful = document.execCommand("copy"); + if (!successful) { + throw new Error("copy command was unsuccessful"); + } + success = true; + } catch (err) { + debug && console.error("unable to copy using execCommand: ", err); + debug && console.warn("trying IE specific stuff"); + try { + window.clipboardData.setData(options.format || "text", text); + options.onCopy && options.onCopy(window.clipboardData); + success = true; + } catch (err) { + debug && console.error("unable to copy using clipboardData: ", err); + debug && console.error("falling back to prompt"); + message = format("message" in options ? options.message : defaultMessage); + window.prompt(message, text); + } + } finally { + if (selection) { + if (typeof selection.removeRange == "function") { + selection.removeRange(range); + } else { + selection.removeAllRanges(); + } + } + + if (mark) { + document.body.removeChild(mark); + } + reselectPrevious(); + } + + return success; +} + +var copyToClipboard = copy; + +function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } + +Object.defineProperty(Component, "__esModule", { + value: true +}); +Component.CopyToClipboard = void 0; + +var _react = _interopRequireDefault(reactExports); + +var _copyToClipboard = _interopRequireDefault(copyToClipboard); + +var _excluded = ["text", "onCopy", "options", "children"]; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } + +function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } + +function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +var CopyToClipboard$2 = /*#__PURE__*/function (_React$PureComponent) { + _inherits(CopyToClipboard, _React$PureComponent); + + var _super = _createSuper(CopyToClipboard); + + function CopyToClipboard() { + var _this; + + _classCallCheck(this, CopyToClipboard); + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + _this = _super.call.apply(_super, [this].concat(args)); + + _defineProperty(_assertThisInitialized(_this), "onClick", function (event) { + var _this$props = _this.props, + text = _this$props.text, + onCopy = _this$props.onCopy, + children = _this$props.children, + options = _this$props.options; + + var elem = _react["default"].Children.only(children); + + var result = (0, _copyToClipboard["default"])(text, options); + + if (onCopy) { + onCopy(text, result); + } // Bypass onClick if it was present + + + if (elem && elem.props && typeof elem.props.onClick === 'function') { + elem.props.onClick(event); + } + }); + + return _this; + } + + _createClass(CopyToClipboard, [{ + key: "render", + value: function render() { + var _this$props2 = this.props; + _this$props2.text; + _this$props2.onCopy; + _this$props2.options; + var children = _this$props2.children, + props = _objectWithoutProperties(_this$props2, _excluded); + + var elem = _react["default"].Children.only(children); + + return /*#__PURE__*/_react["default"].cloneElement(elem, _objectSpread(_objectSpread({}, props), {}, { + onClick: this.onClick + })); + } + }]); + + return CopyToClipboard; +}(_react["default"].PureComponent); + +Component.CopyToClipboard = CopyToClipboard$2; + +_defineProperty(CopyToClipboard$2, "defaultProps", { + onCopy: undefined, + options: undefined +}); + +var _require = Component, + CopyToClipboard = _require.CopyToClipboard; + +CopyToClipboard.CopyToClipboard = CopyToClipboard; +var lib = CopyToClipboard; + +var CopyToClipboard$1 = /*@__PURE__*/getDefaultExportFromCjs(lib); + +// THIS FILE IS AUTO GENERATED +function HiCheck (props) { + return GenIcon({"tag":"svg","attr":{"viewBox":"0 0 20 20","fill":"currentColor","aria-hidden":"true"},"child":[{"tag":"path","attr":{"fillRule":"evenodd","d":"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z","clipRule":"evenodd"}}]})(props); +}function HiClipboardCopy (props) { + return GenIcon({"tag":"svg","attr":{"viewBox":"0 0 20 20","fill":"currentColor","aria-hidden":"true"},"child":[{"tag":"path","attr":{"d":"M8 2a1 1 0 000 2h2a1 1 0 100-2H8z"}},{"tag":"path","attr":{"d":"M3 5a2 2 0 012-2 3 3 0 003 3h2a3 3 0 003-3 2 2 0 012 2v6h-4.586l1.293-1.293a1 1 0 00-1.414-1.414l-3 3a1 1 0 000 1.414l3 3a1 1 0 001.414-1.414L10.414 13H15v3a2 2 0 01-2 2H5a2 2 0 01-2-2V5zM15 11h2a1 1 0 110 2h-2v-2z"}}]})(props); +} + +var Clippy = function (_a) { + var value = _a.value, children = _a.children; + var _b = reactExports.useState(false), mouseOver = _b[0], setMouseOver = _b[1]; + var _c = reactExports.useState(false), copied = _c[0], setCopied = _c[1]; + return (React.createElement("span", { onMouseOver: function () { + if (!mouseOver) { + setMouseOver(true); + } + }, onMouseLeave: function () { + setMouseOver(false); + setCopied(false); + }, style: { display: 'flex', alignItems: 'center' } }, + children, + mouseOver ? (React.createElement(CopyToClipboard$1, { text: value, onCopy: function () { return setCopied(true); } }, + React.createElement("a", { href: "#", onClick: function (e) { + e.preventDefault(); + }, style: { fontSize: '120%', paddingLeft: '0.2em' } }, copied ? (React.createElement(HiCheck, { style: { color: 'green', display: 'flex' } })) : (React.createElement(HiClipboardCopy, { style: { display: 'flex' } }))))) : (React.createElement("span", { style: { fontSize: '120%', width: '1.2em' } })))); +}; + +var StatisticsTable = function (_a) { + var activities = _a.activities; + var columns = React.useMemo(function () { return [ + { + Header: 'Activity Name', + accessor: 'activityName', + Cell: function (_a) { + var value = _a.value; + return React.createElement(Clippy, { value: value }, value); + }, + }, + { + Header: 'Instances', + accessor: 'instances', + Cell: function (_a) { + var value = _a.value; + return React.createElement(Clippy, { value: value }, value); + }, + }, + { + Header: 'Total', + accessor: 'duration', + Cell: function (_a) { + var value = _a.value; + return React.createElement(Clippy, { value: value }, value); + }, + }, + { + Header: 'Average', + accessor: 'average', + Cell: function (_a) { + var value = _a.value; + return React.createElement(Clippy, { value: value }, value); + }, + }, + { + Header: 'Median', + accessor: 'median', + Cell: function (_a) { + var value = _a.value; + return React.createElement(Clippy, { value: value }, value); + }, + }, + ]; }, []); + var counter = React.useMemo(function () { + var counter = {}; + for (var _i = 0, activities_1 = activities; _i < activities_1.length; _i++) { + var activity = activities_1[_i]; + var name_1 = activity.activityName; + counter[name_1] = counter[name_1] ? counter[name_1] + 1 : 1; + } + return counter; + }, [activities]); + var _b = React.useMemo(function () { + var totals = {}; + var durations = {}; + for (var _i = 0, activities_2 = activities; _i < activities_2.length; _i++) { + var activity = activities_2[_i]; + var duration = new Date(activity.endTime).getTime() - new Date(activity.startTime).getTime(); + totals[activity.activityName] = totals[activity.activityName] + ? totals[activity.activityName] + duration + : duration; + if (!durations[activity.activityName]) { + durations[activity.activityName] = [duration]; + } + else { + durations[activity.activityName].push(duration); + } + } + return [totals, durations]; + }, [activities]), totals = _b[0], durations = _b[1]; + var activityNames = React.useMemo(function () { + var activityNames = Object.keys(durations); + activityNames.sort(function (a, b) { + if (totals[a] > totals[b]) { + return -1; + } + else if (totals[a] < totals[b]) { + return 1; + } + return 0; + }); + return activityNames; + }, [activities]); + var data = React.useMemo(function () { + return activityNames.map(function (activityName) { + durations[activityName].sort(function (a, b) { + if (a > b) { + return -1; + } + else if (a < b) { + return 1; + } + return 0; + }); + return { + activityName: activityName, + instances: counter[activityName], + duration: asctime(totals[activityName]), + average: asctime(totals[activityName] / counter[activityName]), + median: asctime(durations[activityName][Math.floor(durations[activityName].length / 2)]), + }; + }); + }, [activities]); + var tableInstance = reactTableExports.useTable({ columns: columns, data: data }, reactTableExports.useSortBy); + var getTableProps = tableInstance.getTableProps, getTableBodyProps = tableInstance.getTableBodyProps, headerGroups = tableInstance.headerGroups, rows = tableInstance.rows, prepareRow = tableInstance.prepareRow; + return (React.createElement("table", __assign$1({ className: "cam-table" }, getTableProps()), + React.createElement("thead", null, headerGroups.map(function (headerGroup) { return (React.createElement("tr", __assign$1({}, headerGroup.getHeaderGroupProps()), headerGroup.headers.map(function (column) { return ( + /* @ts-ignore */ + React.createElement("th", __assign$1({}, column.getHeaderProps(column.getSortByToggleProps())), + column.render('Header'), + React.createElement("span", { style: { position: 'absolute', fontSize: '125%' } }, + /* @ts-ignore */ + column.isSorted ? ( + /* @ts-ignore */ + column.isSortedDesc ? (React.createElement(GoChevronDown, { style: { color: '#155cb5' } })) : (React.createElement(GoChevronUp, { style: { color: '#155cb5' } }))) : (React.createElement(TiMinus, { style: { color: '#155cb5' } }))))); }))); })), + React.createElement("tbody", __assign$1({}, getTableBodyProps()), rows.map(function (row) { + prepareRow(row); + return (React.createElement("tr", __assign$1({}, row.getRowProps()), row.cells.map(function (cell) { + return React.createElement("td", __assign$1({}, cell.getCellProps()), cell.render('Cell')); + }))); + })))); +}; + +___$insertStylesToHeader(".toggle-history-view-button {\n background: #ffffff;\n border-radius: 1px;\n border: 1px solid #cccccc;\n padding: 0;\n width: 30px;\n height: 30px;\n display: flex;\n margin-bottom: 15px;\n align-items: center;\n justify-content: center;\n}\n.toggle-history-view-button:hover {\n background: #e6e6e6;\n}"); + +// THIS FILE IS AUTO GENERATED +function FaHistory (props) { + return GenIcon({"tag":"svg","attr":{"viewBox":"0 0 512 512"},"child":[{"tag":"path","attr":{"d":"M504 255.531c.253 136.64-111.18 248.372-247.82 248.468-59.015.042-113.223-20.53-155.822-54.911-11.077-8.94-11.905-25.541-1.839-35.607l11.267-11.267c8.609-8.609 22.353-9.551 31.891-1.984C173.062 425.135 212.781 440 256 440c101.705 0 184-82.311 184-184 0-101.705-82.311-184-184-184-48.814 0-93.149 18.969-126.068 49.932l50.754 50.754c10.08 10.08 2.941 27.314-11.313 27.314H24c-8.837 0-16-7.163-16-16V38.627c0-14.254 17.234-21.393 27.314-11.314l49.372 49.372C129.209 34.136 189.552 8 256 8c136.81 0 247.747 110.78 248 247.531zm-180.912 78.784l9.823-12.63c8.138-10.463 6.253-25.542-4.21-33.679L288 256.349V152c0-13.255-10.745-24-24-24h-16c-13.255 0-24 10.745-24 24v135.651l65.409 50.874c10.463 8.137 25.541 6.253 33.679-4.21z"}}]})(props); +} + +var ToggleHistoryStatisticsButton = function (_a) { + var onToggleHistoryStatistics = _a.onToggleHistoryStatistics; + var _b = reactExports.useState(loadSettings().showHistoricBadges), showHistoricBadges = _b[0], setShowHistoricBadges = _b[1]; + reactExports.useEffect(function () { + onToggleHistoryStatistics(showHistoricBadges); + saveSettings(__assign$1(__assign$1({}, loadSettings()), { showHistoricBadges: showHistoricBadges })); + }, [showHistoricBadges]); + return (React.createElement("button", { className: "toggle-history-view-button", title: !showHistoricBadges ? 'Show history instance statistics' : 'Hide history instance statistics', "aria-label": !showHistoricBadges ? 'Show history instance statistics' : 'Hide history instance statistics', onClick: function () { return setShowHistoricBadges(!showHistoricBadges); } }, + React.createElement(FaHistory, { style: { opacity: !showHistoricBadges ? '0.33' : '1.0', fontSize: '133%' } }))); +}; + +var headers = function (api) { + return { + Accept: 'application/json', + 'Content-Type': 'application/json', + 'X-XSRF-TOKEN': api.CSRFToken, + }; +}; +var get = function (api, path, params) { return __awaiter(void 0, void 0, void 0, function () { + var query, res, _a, _b, _c, _d, _e, _f, _g; + return __generator(this, function (_h) { + switch (_h.label) { + case 0: + // XXX: Workaround a possible bug where engine api has been parsed wrong + if (api.engine.match(/\/#\//)) { + api.engine = api.engine.split('/#/')[0].replace(/.*\//g, ''); + api.engineApi = api.baseApi + '/engine/' + api.engine; + } + params = params || {}; + if (['/history/activity-instance', '/history/variable-instance', '/history/decision-instance'].includes(path) && + !(params === null || params === void 0 ? void 0 : params.maxResults)) { + params.maxResults = '1000'; + } + query = new URLSearchParams(params).toString(); + if (!query) return [3 /*break*/, 2]; + return [4 /*yield*/, fetch("".concat(api.engineApi).concat(path, "?").concat(query), { + method: 'get', + headers: headers(api), + })]; + case 1: + _a = _h.sent(); + return [3 /*break*/, 4]; + case 2: return [4 /*yield*/, fetch("".concat(api.engineApi).concat(path), { + method: 'get', + headers: headers(api), + })]; + case 3: + _a = _h.sent(); + _h.label = 4; + case 4: + res = _a; + if (!(res.status === 200 && (res.headers.get('Content-Type') || '').startsWith('application/json'))) return [3 /*break*/, 6]; + return [4 /*yield*/, res.json()]; + case 5: return [2 /*return*/, _h.sent()]; + case 6: + if (!(res.headers.get('Content-Type') || '').startsWith('application/json')) return [3 /*break*/, 8]; + _c = (_b = console).debug; + _d = [res.status, path]; + return [4 /*yield*/, res.json()]; + case 7: + _c.apply(_b, _d.concat([_h.sent()])); + return [3 /*break*/, 10]; + case 8: + _f = (_e = console).debug; + _g = [res.status, path]; + return [4 /*yield*/, res.text()]; + case 9: + _f.apply(_e, _g.concat([_h.sent()])); + _h.label = 10; + case 10: return [2 /*return*/, []]; + } + }); +}); }; + +var DefinitionFilterAutoCompleteHandler = /** @class */ (function (_super) { + __extends(DefinitionFilterAutoCompleteHandler, _super); + function DefinitionFilterAutoCompleteHandler() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this.query = ''; + return _this; + } + DefinitionFilterAutoCompleteHandler.prototype.setQuery = function (query) { + this.query = query; + }; + DefinitionFilterAutoCompleteHandler.prototype.needCategories = function () { + var _this = this; + return _super.prototype.needCategories.call(this).filter(function (value) { return !_this.query.includes(value); }); + }; + DefinitionFilterAutoCompleteHandler.prototype.needOperators = function (parsedCategory) { + if (parsedCategory === 'started') { + return ['after']; + } + if (parsedCategory === 'finished') { + return ['before']; + } + if (parsedCategory === 'maxResults') { + return ['is']; + } + return []; + }; + DefinitionFilterAutoCompleteHandler.prototype.needValues = function (parsedCategory, parsedOperator) { + if (parsedOperator === 'after' || parsedOperator === 'before') { + return [{ customType: 'date' }]; + } + return _super.prototype.needValues.call(this, parsedCategory, parsedOperator); + }; + return DefinitionFilterAutoCompleteHandler; +}(reactFilterBoxExports.GridDataAutoCompleteHandler)); +var DefinitionFilterOptions = [ + { + columnField: 'started', + type: 'date', + }, + { + columnField: 'finished', + type: 'date', + }, + { + columnField: 'maxResults', + type: 'text', + }, +]; +var initialState = { + viewer: null, + statistics: null, +}; +var hooks = { + setViewer: function (viewer) { return (initialState.viewer = viewer); }, + setStatistics: function (node) { return (initialState.statistics = node); }, +}; +var Plugin = function (_a) { + var root = _a.root, api = _a.api, processDefinitionId = _a.processDefinitionId; + var autoCompleteHandler = reactExports.useState(new DefinitionFilterAutoCompleteHandler([], DefinitionFilterOptions))[0]; + var _b = reactExports.useState([]), expressions = _b[0], setExpressions = _b[1]; + var _c = reactExports.useState({}), query = _c[0], setQuery = _c[1]; + var _d = reactExports.useState(initialState.viewer), viewer = _d[0], setViewer = _d[1]; + var _e = reactExports.useState(initialState.statistics), statistics = _e[0], setStatistics = _e[1]; + hooks.setViewer = setViewer; + hooks.setStatistics = setStatistics; + var _f = reactExports.useState([]), activities = _f[0], setActivities = _f[1]; + var _g = reactExports.useState([]), tokens = _g[0], setTokens = _g[1]; + var _h = reactExports.useState(false), showTokens = _h[0], setShowTokens = _h[1]; + // FETCH + reactExports.useEffect(function () { + if (Object.keys(query).length > 0) { + (function () { return __awaiter(void 0, void 0, void 0, function () { + var activities; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, get(api, '/history/activity-instance', __assign$1(__assign$1({}, query), { processDefinitionId: processDefinitionId }))]; + case 1: + activities = _a.sent(); + setActivities(activities); + return [2 /*return*/]; + } + }); + }); })(); + } + }, [query]); + reactExports.useEffect(function () { + if (expressions.length > 0) { + var query_1 = { + sortBy: 'endTime', + sortOrder: 'desc', + maxResults: 1000, + }; + for (var _i = 0, expressions_1 = expressions; _i < expressions_1.length; _i++) { + var _a = expressions_1[_i], category = _a.category, operator = _a.operator, value = _a.value; + if (category === 'started' && operator === 'after' && !isNaN(new Date("".concat(value)).getTime())) { + query_1['startedAfter'] = "".concat(value, "T00:00:00.000+0000"); + } + else if (category === 'finished' && operator === 'before' && !isNaN(new Date("".concat(value)).getTime())) { + query_1['finishedBefore'] = "".concat(value, "T00:00:00.000+0000"); + } + else if (category === 'maxResults' && operator == 'is' && !isNaN(parseInt("".concat(value), 10))) { + query_1['maxResults'] = "".concat(value); + } + } + setQuery(query_1); + } + else { + /* @ts-ignore */ + var weekAgo = new Date(new Date() - 1000 * 3600 * 24 * 7).toISOString().split('T')[0]; + /* @ts-ignore */ + var tomorrow = new Date(new Date() - 1000 * 3600 * 24 * -1).toISOString().split('T')[0]; + setQuery({ + sortBy: 'endTime', + sortOrder: 'desc', + startedAfter: "".concat(weekAgo, "T00:00:00.000+0000"), + finishedBefore: "".concat(tomorrow, "T00:00:00.000+0000"), + maxResults: '1000', + }); + } + }, [expressions]); + // Overlay + reactExports.useEffect(function () { + if (viewer) { + var toggleHistoryStatisticsButton = document.createElement('div'); + toggleHistoryStatisticsButton.style.cssText = "\n position: absolute;\n right: 15px;\n top: 60px;\n "; + viewer._container.appendChild(toggleHistoryStatisticsButton); + createRoot(toggleHistoryStatisticsButton).render(React.createElement(React.StrictMode, null, + React.createElement(ToggleHistoryStatisticsButton, { onToggleHistoryStatistics: function (value) { + setShowTokens(value); + } }))); + } + }, [viewer]); + reactExports.useEffect(function () { + var _a; + for (var _i = 0, tokens_1 = tokens; _i < tokens_1.length; _i++) { + var token = tokens_1[_i]; + (_a = token.parentElement) === null || _a === void 0 ? void 0 : _a.removeChild(token); + } + if (showTokens && viewer && activities.length) { + var overlays = viewer.get('overlays'); + var update = []; + var counter = {}; + for (var _b = 0, activities_1 = activities; _b < activities_1.length; _b++) { + var activity = activities_1[_b]; + var id = activity.activityId; + counter[id] = counter[id] ? counter[id] + 1 : 1; + } + var seen = {}; + for (var _c = 0, activities_2 = activities; _c < activities_2.length; _c++) { + var activity = activities_2[_c]; + var id = activity.activityId; + if (seen[id]) { + continue; + } + else { + seen[id] = true; + } + var overlay = document.createElement('span'); + overlay.innerText = "".concat(counter[id]); + overlay.className = 'badge'; + overlay.style.cssText = "\n background: lightgray;\n "; + try { + overlays.add(id.split('#')[0], { + position: { + bottom: 17, + right: 10, + }, + html: overlay, + }); + update.push(overlay); + } + catch (e) { } + } + setTokens(update); + } + }, [viewer, activities, showTokens]); + // Hack to ensure long living HTML node for filter box + if (statistics && !Array.from(statistics.children).includes(root)) { + statistics.appendChild(root); + } + // Tabs + return statistics ? (React.createElement(Portal, { node: root }, + React.createElement(FilterBox, { options: DefinitionFilterOptions, autoCompleteHandler: autoCompleteHandler, onParseOk: setExpressions, defaultQuery: function () { + // @ts-ignore + var weekAgo = new Date(new Date() - 1000 * 3600 * 24 * 7).toISOString().split('T')[0]; + // @ts-ignore + var tomorrow = new Date(new Date() - 1000 * 3600 * 24 * -1).toISOString().split('T')[0]; + return "started after ".concat(weekAgo, " AND finished before ").concat(tomorrow, " AND maxResults is 1000"); + } }), + activities.length ? (React.createElement(StatisticsTable, { activities: filter(activities, function (activity) { return activity.activityName && activity.endTime; }) })) : null)) : null; +}; +var definitionHistoricActivities = [ + { + id: 'definitionHistoricActivitiesDiagramTokens', + pluginPoint: 'cockpit.processDefinition.diagram.plugin', + render: function (viewer) { return hooks.setViewer(viewer); }, + }, + { + id: 'definitionHistoricActivitiesStatisticsTab', + pluginPoint: 'cockpit.processDefinition.runtime.tab', + properties: { + label: 'Statistics', + }, + render: function (node) { return hooks.setStatistics(node); }, + }, + { + id: 'definitionHistoricActivitiesPlugin', + pluginPoint: 'cockpit.processDefinition.runtime.action', + render: function (node, _a) { + var api = _a.api, processDefinitionId = _a.processDefinitionId; + createRoot(node).render(React.createElement(React.StrictMode, null, + React.createElement(Plugin, { root: node, api: api, processDefinitionId: processDefinitionId }))); + }, + }, +]; + +export { definitionHistoricActivities as default }; diff --git a/examples/java-c7/src/main/resources/META-INF/resources/webjars/camunda/app/cockpit/scripts/instance-historic-activities.js b/examples/java-c7/src/main/resources/META-INF/resources/webjars/camunda/app/cockpit/scripts/instance-historic-activities.js new file mode 100644 index 0000000..82f3fb8 --- /dev/null +++ b/examples/java-c7/src/main/resources/META-INF/resources/webjars/camunda/app/cockpit/scripts/instance-historic-activities.js @@ -0,0 +1,8779 @@ +function ___$insertStylesToHeader(css) { + if (!css) { + return + } + if (typeof window === 'undefined') { + return + } + + const style = document.createElement('style'); + + style.setAttribute('type', 'text/css'); + style.innerHTML = css; + document.head.appendChild(style); + return css +} + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise */ + + +var __assign$1 = function() { + __assign$1 = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + return __assign$1.apply(this, arguments); +}; + +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +} + +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +var react = {exports: {}}; + +var react_production_min = {}; + +/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +var l=Symbol.for("react.element"),n=Symbol.for("react.portal"),p$1=Symbol.for("react.fragment"),q=Symbol.for("react.strict_mode"),r=Symbol.for("react.profiler"),t=Symbol.for("react.provider"),u=Symbol.for("react.context"),v$1=Symbol.for("react.forward_ref"),w=Symbol.for("react.suspense"),x=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),z$1=Symbol.iterator;function A$1(a){if(null===a||"object"!==typeof a)return null;a=z$1&&a[z$1]||a["@@iterator"];return "function"===typeof a?a:null} +var B$1={isMounted:function(){return !1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C$1=Object.assign,D$1={};function E$1(a,b,e){this.props=a;this.context=b;this.refs=D$1;this.updater=e||B$1;}E$1.prototype.isReactComponent={}; +E$1.prototype.setState=function(a,b){if("object"!==typeof a&&"function"!==typeof a&&null!=a)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,a,b,"setState");};E$1.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,"forceUpdate");};function F(){}F.prototype=E$1.prototype;function G$1(a,b,e){this.props=a;this.context=b;this.refs=D$1;this.updater=e||B$1;}var H$1=G$1.prototype=new F; +H$1.constructor=G$1;C$1(H$1,E$1.prototype);H$1.isPureReactComponent=!0;var I$1=Array.isArray,J=Object.prototype.hasOwnProperty,K$1={current:null},L$1={key:!0,ref:!0,__self:!0,__source:!0}; +function M$1(a,b,e){var d,c={},k=null,h=null;if(null!=b)for(d in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(k=""+b.key),b)J.call(b,d)&&!L$1.hasOwnProperty(d)&&(c[d]=b[d]);var g=arguments.length-2;if(1===g)c.children=e;else if(1>>1,e=a[d];if(0>>1;dg(C,c))ng(x,C)?(a[d]=x,a[n]=c,d=n):(a[d]=C,a[m]=c,d=m);else if(ng(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b} + function g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}if("object"===typeof performance&&"function"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now()};}else {var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q};}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D="function"===typeof setTimeout?setTimeout:null,E="function"===typeof clearTimeout?clearTimeout:null,F="undefined"!==typeof setImmediate?setImmediate:null; + "undefined"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t);}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else {var b=h(t);null!==b&&K(H,b.startTime-a);}} + function J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if("function"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();"function"===typeof e?v.callback=e:v===h(r)&&k(r);G(b);}else k(r);v=h(r);}if(null!==v)var w=!0;else {var m=h(t);null!==m&&K(H,m.startTime-b);w=!1;}return w}finally{v=null,y=c,z=!1;}}var N=!1,O=null,L=-1,P=5,Q=-1; + function M(){return exports.unstable_now()-Qa||125d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a}; + exports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c;}}}; +} (scheduler_production_min)); + +{ + scheduler.exports = scheduler_production_min; +} + +var schedulerExports = scheduler.exports; + +/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +var aa=reactExports,ca=schedulerExports;function p(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;cb}return !1}function v(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g;}var z={}; +"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){z[a]=new v(a,0,!1,a,null,!1,!1);});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];z[b]=new v(b,1,!1,a[1],null,!1,!1);});["contentEditable","draggable","spellCheck","value"].forEach(function(a){z[a]=new v(a,2,!1,a.toLowerCase(),null,!1,!1);}); +["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){z[a]=new v(a,2,!1,a,null,!1,!1);});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){z[a]=new v(a,3,!1,a.toLowerCase(),null,!1,!1);}); +["checked","multiple","muted","selected"].forEach(function(a){z[a]=new v(a,3,!0,a,null,!1,!1);});["capture","download"].forEach(function(a){z[a]=new v(a,4,!1,a,null,!1,!1);});["cols","rows","size","span"].forEach(function(a){z[a]=new v(a,6,!1,a,null,!1,!1);});["rowSpan","start"].forEach(function(a){z[a]=new v(a,5,!1,a.toLowerCase(),null,!1,!1);});var ra=/[\-:]([a-z])/g;function sa(a){return a[1].toUpperCase()} +"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=a.replace(ra, +sa);z[b]=new v(b,1,!1,a,null,!1,!1);});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,"http://www.w3.org/1999/xlink",!1,!1);});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1,!1);});["tabIndex","crossOrigin"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!1,!1);}); +z.xlinkHref=new v("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!0,!0);}); +function ta(a,b,c,d){var e=z.hasOwnProperty(b)?z[b]:null;if(null!==e?0!==e.type:d||!(2h||e[g]!==f[h]){var k="\n"+e[g].replace(" at new "," at ");a.displayName&&k.includes("")&&(k=k.replace("",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{Na=!1,Error.prepareStackTrace=c;}return (a=a?a.displayName||a.name:"")?Ma(a):""} +function Pa(a){switch(a.tag){case 5:return Ma(a.type);case 16:return Ma("Lazy");case 13:return Ma("Suspense");case 19:return Ma("SuspenseList");case 0:case 2:case 15:return a=Oa(a.type,!1),a;case 11:return a=Oa(a.type.render,!1),a;case 1:return a=Oa(a.type,!0),a;default:return ""}} +function Qa(a){if(null==a)return null;if("function"===typeof a)return a.displayName||a.name||null;if("string"===typeof a)return a;switch(a){case ya:return "Fragment";case wa:return "Portal";case Aa:return "Profiler";case za:return "StrictMode";case Ea:return "Suspense";case Fa:return "SuspenseList"}if("object"===typeof a)switch(a.$$typeof){case Ca:return (a.displayName||"Context")+".Consumer";case Ba:return (a._context.displayName||"Context")+".Provider";case Da:var b=a.render;a=a.displayName;a||(a=b.displayName|| +b.name||"",a=""!==a?"ForwardRef("+a+")":"ForwardRef");return a;case Ga:return b=a.displayName||null,null!==b?b:Qa(a.type)||"Memo";case Ha:b=a._payload;a=a._init;try{return Qa(a(b))}catch(c){}}return null} +function Ra(a){var b=a.type;switch(a.tag){case 24:return "Cache";case 9:return (b.displayName||"Context")+".Consumer";case 10:return (b._context.displayName||"Context")+".Provider";case 18:return "DehydratedFragment";case 11:return a=b.render,a=a.displayName||a.name||"",b.displayName||(""!==a?"ForwardRef("+a+")":"ForwardRef");case 7:return "Fragment";case 5:return b;case 4:return "Portal";case 3:return "Root";case 6:return "Text";case 16:return Qa(b);case 8:return b===za?"StrictMode":"Mode";case 22:return "Offscreen"; +case 12:return "Profiler";case 21:return "Scope";case 13:return "Suspense";case 19:return "SuspenseList";case 25:return "TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if("function"===typeof b)return b.displayName||b.name||null;if("string"===typeof b)return b}return null}function Sa(a){switch(typeof a){case "boolean":case "number":case "string":case "undefined":return a;case "object":return a;default:return ""}} +function Ta(a){var b=a.type;return (a=a.nodeName)&&"input"===a.toLowerCase()&&("checkbox"===b||"radio"===b)} +function Ua(a){var b=Ta(a)?"checked":"value",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=""+a[b];if(!a.hasOwnProperty(b)&&"undefined"!==typeof c&&"function"===typeof c.get&&"function"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=""+a;f.call(this,a);}});Object.defineProperty(a,b,{enumerable:c.enumerable});return {getValue:function(){return d},setValue:function(a){d=""+a;},stopTracking:function(){a._valueTracker= +null;delete a[b];}}}}function Va(a){a._valueTracker||(a._valueTracker=Ua(a));}function Wa(a){if(!a)return !1;var b=a._valueTracker;if(!b)return !0;var c=b.getValue();var d="";a&&(d=Ta(a)?a.checked?"true":"false":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}function Xa(a){a=a||("undefined"!==typeof document?document:void 0);if("undefined"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}} +function Ya(a,b){var c=b.checked;return A({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}function Za(a,b){var c=null==b.defaultValue?"":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=Sa(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:"checkbox"===b.type||"radio"===b.type?null!=b.checked:null!=b.value};}function ab(a,b){b=b.checked;null!=b&&ta(a,"checked",b,!1);} +function bb(a,b){ab(a,b);var c=Sa(b.value),d=b.type;if(null!=c)if("number"===d){if(0===c&&""===a.value||a.value!=c)a.value=""+c;}else a.value!==""+c&&(a.value=""+c);else if("submit"===d||"reset"===d){a.removeAttribute("value");return}b.hasOwnProperty("value")?cb(a,b.type,c):b.hasOwnProperty("defaultValue")&&cb(a,b.type,Sa(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked);} +function db(a,b,c){if(b.hasOwnProperty("value")||b.hasOwnProperty("defaultValue")){var d=b.type;if(!("submit"!==d&&"reset"!==d||void 0!==b.value&&null!==b.value))return;b=""+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b;}c=a.name;""!==c&&(a.name="");a.defaultChecked=!!a._wrapperState.initialChecked;""!==c&&(a.name=c);} +function cb(a,b,c){if("number"!==b||Xa(a.ownerDocument)!==a)null==c?a.defaultValue=""+a._wrapperState.initialValue:a.defaultValue!==""+c&&(a.defaultValue=""+c);}var eb=Array.isArray; +function fb(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e"+b.valueOf().toString()+"";for(b=mb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild);}}); +function ob(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b;} +var pb={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0, +zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},qb=["Webkit","ms","Moz","O"];Object.keys(pb).forEach(function(a){qb.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);pb[b]=pb[a];});});function rb(a,b,c){return null==b||"boolean"===typeof b||""===b?"":c||"number"!==typeof b||0===b||pb.hasOwnProperty(a)&&pb[a]?(""+b).trim():b+"px"} +function sb(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf("--"),e=rb(c,b[c],d);"float"===c&&(c="cssFloat");d?a.setProperty(c,e):a[c]=e;}}var tb=A({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0}); +function ub(a,b){if(b){if(tb[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(p(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(p(60));if("object"!==typeof b.dangerouslySetInnerHTML||!("__html"in b.dangerouslySetInnerHTML))throw Error(p(61));}if(null!=b.style&&"object"!==typeof b.style)throw Error(p(62));}} +function vb(a,b){if(-1===a.indexOf("-"))return "string"===typeof b.is;switch(a){case "annotation-xml":case "color-profile":case "font-face":case "font-face-src":case "font-face-uri":case "font-face-format":case "font-face-name":case "missing-glyph":return !1;default:return !0}}var wb=null;function xb(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}var yb=null,zb=null,Ab=null; +function Bb(a){if(a=Cb(a)){if("function"!==typeof yb)throw Error(p(280));var b=a.stateNode;b&&(b=Db(b),yb(a.stateNode,a.type,b));}}function Eb(a){zb?Ab?Ab.push(a):Ab=[a]:zb=a;}function Fb(){if(zb){var a=zb,b=Ab;Ab=zb=null;Bb(a);if(b)for(a=0;a>>=0;return 0===a?32:31-(pc(a)/qc|0)|0}var rc=64,sc=4194304; +function tc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824; +default:return a}}function uc(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=tc(h):(f&=g,0!==f&&(d=tc(f)));}else g=c&~e,0!==g?d=tc(g):0!==f&&(d=tc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0c;c++)b.push(a);return b} +function Ac(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-oc(b);a[b]=c;}function Bc(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0=be),ee=String.fromCharCode(32),fe=!1; +function ge(a,b){switch(a){case "keyup":return -1!==$d.indexOf(b.keyCode);case "keydown":return 229!==b.keyCode;case "keypress":case "mousedown":case "focusout":return !0;default:return !1}}function he(a){a=a.detail;return "object"===typeof a&&"data"in a?a.data:null}var ie=!1;function je(a,b){switch(a){case "compositionend":return he(b);case "keypress":if(32!==b.which)return null;fe=!0;return ee;case "textInput":return a=b.data,a===ee&&fe?null:a;default:return null}} +function ke(a,b){if(ie)return "compositionend"===a||!ae&&ge(a,b)?(a=nd(),md=ld=kd=null,ie=!1,a):null;switch(a){case "paste":return null;case "keypress":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1=b)return {node:c,offset:b-a};a=d;}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode;}c=void 0;}c=Je(c);}}function Le(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Le(a,b.parentNode):"contains"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1} +function Me(){for(var a=window,b=Xa();b instanceof a.HTMLIFrameElement;){try{var c="string"===typeof b.contentWindow.location.href;}catch(d){c=!1;}if(c)a=b.contentWindow;else break;b=Xa(a.document);}return b}function Ne(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&("input"===b&&("text"===a.type||"search"===a.type||"tel"===a.type||"url"===a.type||"password"===a.type)||"textarea"===b||"true"===a.contentEditable)} +function Oe(a){var b=Me(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&Le(c.ownerDocument.documentElement,c)){if(null!==d&&Ne(c))if(b=d.start,a=d.end,void 0===a&&(a=b),"selectionStart"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=Ke(c,f);var g=Ke(c, +d);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset),a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),a.addRange(b)));}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});"function"===typeof c.focus&&c.focus();for(c=0;c=document.documentMode,Qe=null,Re=null,Se=null,Te=!1; +function Ue(a,b,c){var d=c.window===c?c.document:9===c.nodeType?c:c.ownerDocument;Te||null==Qe||Qe!==Xa(d)||(d=Qe,"selectionStart"in d&&Ne(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Se&&Ie(Se,d)||(Se=d,d=oe(Re,"onSelect"),0Tf||(a.current=Sf[Tf],Sf[Tf]=null,Tf--);}function G(a,b){Tf++;Sf[Tf]=a.current;a.current=b;}var Vf={},H=Uf(Vf),Wf=Uf(!1),Xf=Vf;function Yf(a,b){var c=a.type.contextTypes;if(!c)return Vf;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e} +function Zf(a){a=a.childContextTypes;return null!==a&&void 0!==a}function $f(){E(Wf);E(H);}function ag(a,b,c){if(H.current!==Vf)throw Error(p(168));G(H,b);G(Wf,c);}function bg(a,b,c){var d=a.stateNode;b=b.childContextTypes;if("function"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(p(108,Ra(a)||"Unknown",e));return A({},c,d)} +function cg(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Vf;Xf=H.current;G(H,a);G(Wf,Wf.current);return !0}function dg(a,b,c){var d=a.stateNode;if(!d)throw Error(p(169));c?(a=bg(a,b,Xf),d.__reactInternalMemoizedMergedChildContext=a,E(Wf),E(H),G(H,a)):E(Wf);G(Wf,c);}var eg=null,fg=!1,gg=!1;function hg(a){null===eg?eg=[a]:eg.push(a);}function ig(a){fg=!0;hg(a);} +function jg(){if(!gg&&null!==eg){gg=!0;var a=0,b=C;try{var c=eg;for(C=1;a>=g;e-=g;rg=1<<32-oc(b)+e|c<w?(x=u,u=null):x=u.sibling;var n=r(e,u,h[w],k);if(null===n){null===u&&(u=x);break}a&&u&&null===n.alternate&&b(e,u);g=f(n,g,w);null===m?l=n:m.sibling=n;m=n;u=x;}if(w===h.length)return c(e,u),I&&tg(e,w),l;if(null===u){for(;ww?(x=m,m=null):x=m.sibling;var t=r(e,m,n.value,k);if(null===t){null===m&&(m=x);break}a&&m&&null===t.alternate&&b(e,m);g=f(t,g,w);null===u?l=t:u.sibling=t;u=t;m=x;}if(n.done)return c(e, +m),I&&tg(e,w),l;if(null===m){for(;!n.done;w++,n=h.next())n=q(e,n.value,k),null!==n&&(g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);I&&tg(e,w);return l}for(m=d(e,m);!n.done;w++,n=h.next())n=y(m,e,w,n.value,k),null!==n&&(a&&null!==n.alternate&&m.delete(null===n.key?w:n.key),g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);a&&m.forEach(function(a){return b(e,a)});I&&tg(e,w);return l}function J(a,d,f,h){"object"===typeof f&&null!==f&&f.type===ya&&null===f.key&&(f=f.props.children);if("object"===typeof f&&null!==f){switch(f.$$typeof){case va:a:{for(var k= +f.key,l=d;null!==l;){if(l.key===k){k=f.type;if(k===ya){if(7===l.tag){c(a,l.sibling);d=e(l,f.props.children);d.return=a;a=d;break a}}else if(l.elementType===k||"object"===typeof k&&null!==k&&k.$$typeof===Ha&&uh(k)===l.type){c(a,l.sibling);d=e(l,f.props);d.ref=sh(a,l,f);d.return=a;a=d;break a}c(a,l);break}else b(a,l);l=l.sibling;}f.type===ya?(d=Ah(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=yh(f.type,f.key,f.props,null,a.mode,h),h.ref=sh(a,d,f),h.return=a,a=h);}return g(a);case wa:a:{for(l=f.key;null!== +d;){if(d.key===l)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else {c(a,d);break}else b(a,d);d=d.sibling;}d=zh(f,a.mode,h);d.return=a;a=d;}return g(a);case Ha:return l=f._init,J(a,d,l(f._payload),h)}if(eb(f))return n(a,d,f,h);if(Ka(f))return t(a,d,f,h);th(a,f);}return "string"===typeof f&&""!==f||"number"===typeof f?(f=""+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d): +(c(a,d),d=xh(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d)}return J}var Bh=vh(!0),Ch=vh(!1),Dh={},Eh=Uf(Dh),Fh=Uf(Dh),Gh=Uf(Dh);function Hh(a){if(a===Dh)throw Error(p(174));return a}function Ih(a,b){G(Gh,b);G(Fh,a);G(Eh,Dh);a=b.nodeType;switch(a){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:lb(null,"");break;default:a=8===a?b.parentNode:b,b=a.namespaceURI||null,a=a.tagName,b=lb(b,a);}E(Eh);G(Eh,b);}function Jh(){E(Eh);E(Fh);E(Gh);} +function Kh(a){Hh(Gh.current);var b=Hh(Eh.current);var c=lb(b,a.type);b!==c&&(G(Fh,a),G(Eh,c));}function Lh(a){Fh.current===a&&(E(Eh),E(Fh));}var M=Uf(0); +function Mh(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||"$?"===c.data||"$!"===c.data))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.flags&128))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return;}b.sibling.return=b.return;b=b.sibling;}return null}var Nh=[]; +function Oh(){for(var a=0;ac?c:4;a(!0);var d=Qh.transition;Qh.transition={};try{a(!1),b();}finally{C=c,Qh.transition=d;}}function Fi(){return di().memoizedState} +function Gi(a,b,c){var d=lh(a);c={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(b,c);else if(c=Yg(a,b,c,d),null!==c){var e=L();mh(c,a,d,e);Ji(c,b,d);}} +function ri(a,b,c){var d=lh(a),e={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(b,e);else {var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(He(h,g)){var k=b.interleaved;null===k?(e.next=e,Xg(b)):(e.next=k.next,k.next=e);b.interleaved=e;return}}catch(l){}finally{}c=Yg(a,b,e,d);null!==c&&(e=L(),mh(c,a,d,e),Ji(c,b,d));}} +function Hi(a){var b=a.alternate;return a===N||null!==b&&b===N}function Ii(a,b){Th=Sh=!0;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b;}function Ji(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c);}} +var ai={readContext:Vg,useCallback:Q,useContext:Q,useEffect:Q,useImperativeHandle:Q,useInsertionEffect:Q,useLayoutEffect:Q,useMemo:Q,useReducer:Q,useRef:Q,useState:Q,useDebugValue:Q,useDeferredValue:Q,useTransition:Q,useMutableSource:Q,useSyncExternalStore:Q,useId:Q,unstable_isNewReconciler:!1},Yh={readContext:Vg,useCallback:function(a,b){ci().memoizedState=[a,void 0===b?null:b];return a},useContext:Vg,useEffect:vi,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ti(4194308, +4,yi.bind(null,b,a),c)},useLayoutEffect:function(a,b){return ti(4194308,4,a,b)},useInsertionEffect:function(a,b){return ti(4,2,a,b)},useMemo:function(a,b){var c=ci();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=ci();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=Gi.bind(null,N,a);return [d.memoizedState,a]},useRef:function(a){var b= +ci();a={current:a};return b.memoizedState=a},useState:qi,useDebugValue:Ai,useDeferredValue:function(a){return ci().memoizedState=a},useTransition:function(){var a=qi(!1),b=a[0];a=Ei.bind(null,a[1]);ci().memoizedState=a;return [b,a]},useMutableSource:function(){},useSyncExternalStore:function(a,b,c){var d=N,e=ci();if(I){if(void 0===c)throw Error(p(407));c=c();}else {c=b();if(null===R)throw Error(p(349));0!==(Rh&30)||ni(d,b,c);}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;vi(ki.bind(null,d, +f,a),[a]);d.flags|=2048;li(9,mi.bind(null,d,f,c,b),void 0,null);return c},useId:function(){var a=ci(),b=R.identifierPrefix;if(I){var c=sg;var d=rg;c=(d&~(1<<32-oc(d)-1)).toString(32)+c;b=":"+b+"R"+c;c=Uh++;0\x3c/script>",a=a.removeChild(a.firstChild)): +"string"===typeof d.is?a=g.createElement(c,{is:d.is}):(a=g.createElement(c),"select"===c&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,c);a[Of]=b;a[Pf]=d;Aj(a,b,!1,!1);b.stateNode=a;a:{g=vb(c,d);switch(c){case "dialog":D("cancel",a);D("close",a);e=d;break;case "iframe":case "object":case "embed":D("load",a);e=d;break;case "video":case "audio":for(e=0;eHj&&(b.flags|=128,d=!0,Ej(f,!1),b.lanes=4194304);}else {if(!d)if(a=Mh(g),null!==a){if(b.flags|=128,d=!0,c=a.updateQueue,null!==c&&(b.updateQueue=c,b.flags|=4),Ej(f,!0),null===f.tail&&"hidden"===f.tailMode&&!g.alternate&&!I)return S(b),null}else 2*B()-f.renderingStartTime>Hj&&1073741824!==c&&(b.flags|=128,d=!0,Ej(f,!1),b.lanes=4194304);f.isBackwards?(g.sibling=b.child,b.child=g):(c=f.last,null!==c?c.sibling=g:b.child=g,f.last=g);}if(null!==f.tail)return b=f.tail,f.rendering= +b,f.tail=b.sibling,f.renderingStartTime=B(),b.sibling=null,c=M.current,G(M,d?c&1|2:c&1),b;S(b);return null;case 22:case 23:return Ij(),d=null!==b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(gj&1073741824)&&(S(b),b.subtreeFlags&6&&(b.flags|=8192)):S(b),null;case 24:return null;case 25:return null}throw Error(p(156,b.tag));} +function Jj(a,b){wg(b);switch(b.tag){case 1:return Zf(b.type)&&$f(),a=b.flags,a&65536?(b.flags=a&-65537|128,b):null;case 3:return Jh(),E(Wf),E(H),Oh(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return Lh(b),null;case 13:E(M);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(p(340));Ig();}a=b.flags;return a&65536?(b.flags=a&-65537|128,b):null;case 19:return E(M),null;case 4:return Jh(),null;case 10:return Rg(b.type._context),null;case 22:case 23:return Ij(), +null;case 24:return null;default:return null}}var Kj=!1,U=!1,Lj="function"===typeof WeakSet?WeakSet:Set,V=null;function Mj(a,b){var c=a.ref;if(null!==c)if("function"===typeof c)try{c(null);}catch(d){W(a,b,d);}else c.current=null;}function Nj(a,b,c){try{c();}catch(d){W(a,b,d);}}var Oj=!1; +function Pj(a,b){Cf=dd;a=Me();if(Ne(a)){if("selectionStart"in a)var c={start:a.selectionStart,end:a.selectionEnd};else a:{c=(c=a.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&0!==d.rangeCount){c=d.anchorNode;var e=d.anchorOffset,f=d.focusNode;d=d.focusOffset;try{c.nodeType,f.nodeType;}catch(F){c=null;break a}var g=0,h=-1,k=-1,l=0,m=0,q=a,r=null;b:for(;;){for(var y;;){q!==c||0!==e&&3!==q.nodeType||(h=g+e);q!==f||0!==d&&3!==q.nodeType||(k=g+d);3===q.nodeType&&(g+= +q.nodeValue.length);if(null===(y=q.firstChild))break;r=q;q=y;}for(;;){if(q===a)break b;r===c&&++l===e&&(h=g);r===f&&++m===d&&(k=g);if(null!==(y=q.nextSibling))break;q=r;r=q.parentNode;}q=y;}c=-1===h||-1===k?null:{start:h,end:k};}else c=null;}c=c||{start:0,end:0};}else c=null;Df={focusedElem:a,selectionRange:c};dd=!1;for(V=b;null!==V;)if(b=V,a=b.child,0!==(b.subtreeFlags&1028)&&null!==a)a.return=b,V=a;else for(;null!==V;){b=V;try{var n=b.alternate;if(0!==(b.flags&1024))switch(b.tag){case 0:case 11:case 15:break; +case 1:if(null!==n){var t=n.memoizedProps,J=n.memoizedState,x=b.stateNode,w=x.getSnapshotBeforeUpdate(b.elementType===b.type?t:Lg(b.type,t),J);x.__reactInternalSnapshotBeforeUpdate=w;}break;case 3:var u=b.stateNode.containerInfo;1===u.nodeType?u.textContent="":9===u.nodeType&&u.documentElement&&u.removeChild(u.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(p(163));}}catch(F){W(b,b.return,F);}a=b.sibling;if(null!==a){a.return=b.return;V=a;break}V=b.return;}n=Oj;Oj=!1;return n} +function Qj(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&Nj(b,c,f);}e=e.next;}while(e!==d)}}function Rj(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d();}c=c.next;}while(c!==b)}}function Sj(a){var b=a.ref;if(null!==b){var c=a.stateNode;switch(a.tag){case 5:a=c;break;default:a=c;}"function"===typeof b?b(a):b.current=a;}} +function Tj(a){var b=a.alternate;null!==b&&(a.alternate=null,Tj(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&(delete b[Of],delete b[Pf],delete b[of],delete b[Qf],delete b[Rf]));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null;}function Uj(a){return 5===a.tag||3===a.tag||4===a.tag} +function Vj(a){a:for(;;){for(;null===a.sibling;){if(null===a.return||Uj(a.return))return null;a=a.return;}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child;}if(!(a.flags&2))return a.stateNode}} +function Wj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?8===c.nodeType?c.parentNode.insertBefore(a,b):c.insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,null!==c&&void 0!==c||null!==b.onclick||(b.onclick=Bf));else if(4!==d&&(a=a.child,null!==a))for(Wj(a,b,c),a=a.sibling;null!==a;)Wj(a,b,c),a=a.sibling;} +function Xj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(Xj(a,b,c),a=a.sibling;null!==a;)Xj(a,b,c),a=a.sibling;}var X=null,Yj=!1;function Zj(a,b,c){for(c=c.child;null!==c;)ak(a,b,c),c=c.sibling;} +function ak(a,b,c){if(lc&&"function"===typeof lc.onCommitFiberUnmount)try{lc.onCommitFiberUnmount(kc,c);}catch(h){}switch(c.tag){case 5:U||Mj(c,b);case 6:var d=X,e=Yj;X=null;Zj(a,b,c);X=d;Yj=e;null!==X&&(Yj?(a=X,c=c.stateNode,8===a.nodeType?a.parentNode.removeChild(c):a.removeChild(c)):X.removeChild(c.stateNode));break;case 18:null!==X&&(Yj?(a=X,c=c.stateNode,8===a.nodeType?Kf(a.parentNode,c):1===a.nodeType&&Kf(a,c),bd(a)):Kf(X,c.stateNode));break;case 4:d=X;e=Yj;X=c.stateNode.containerInfo;Yj=!0; +Zj(a,b,c);X=d;Yj=e;break;case 0:case 11:case 14:case 15:if(!U&&(d=c.updateQueue,null!==d&&(d=d.lastEffect,null!==d))){e=d=d.next;do{var f=e,g=f.destroy;f=f.tag;void 0!==g&&(0!==(f&2)?Nj(c,b,g):0!==(f&4)&&Nj(c,b,g));e=e.next;}while(e!==d)}Zj(a,b,c);break;case 1:if(!U&&(Mj(c,b),d=c.stateNode,"function"===typeof d.componentWillUnmount))try{d.props=c.memoizedProps,d.state=c.memoizedState,d.componentWillUnmount();}catch(h){W(c,b,h);}Zj(a,b,c);break;case 21:Zj(a,b,c);break;case 22:c.mode&1?(U=(d=U)||null!== +c.memoizedState,Zj(a,b,c),U=d):Zj(a,b,c);break;default:Zj(a,b,c);}}function bk(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Lj);b.forEach(function(b){var d=ck.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d));});}} +function dk(a,b){var c=b.deletions;if(null!==c)for(var d=0;de&&(e=g);d&=~f;}d=e;d=B()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*mk(d/1960))-d;if(10a?16:a;if(null===xk)var d=!1;else {a=xk;xk=null;yk=0;if(0!==(K&6))throw Error(p(331));var e=K;K|=4;for(V=a.current;null!==V;){var f=V,g=f.child;if(0!==(V.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;kB()-gk?Lk(a,0):sk|=c);Ek(a,b);}function Zk(a,b){0===b&&(0===(a.mode&1)?b=1:(b=sc,sc<<=1,0===(sc&130023424)&&(sc=4194304)));var c=L();a=Zg(a,b);null!==a&&(Ac(a,b,c),Ek(a,c));}function vj(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);Zk(a,c);} +function ck(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);break;case 19:d=a.stateNode;break;default:throw Error(p(314));}null!==d&&d.delete(b);Zk(a,c);}var Wk; +Wk=function(a,b,c){if(null!==a)if(a.memoizedProps!==b.pendingProps||Wf.current)Ug=!0;else {if(0===(a.lanes&c)&&0===(b.flags&128))return Ug=!1,zj(a,b,c);Ug=0!==(a.flags&131072)?!0:!1;}else Ug=!1,I&&0!==(b.flags&1048576)&&ug(b,ng,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;jj(a,b);a=b.pendingProps;var e=Yf(b,H.current);Tg(b,c);e=Xh(null,b,d,a,e,c);var f=bi();b.flags|=1;"object"===typeof e&&null!==e&&"function"===typeof e.render&&void 0===e.$$typeof?(b.tag=1,b.memoizedState=null,b.updateQueue= +null,Zf(d)?(f=!0,cg(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,ah(b),e.updater=nh,b.stateNode=e,e._reactInternals=b,rh(b,d,a,c),b=kj(null,b,d,!0,f,c)):(b.tag=0,I&&f&&vg(b),Yi(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{jj(a,b);a=b.pendingProps;e=d._init;d=e(d._payload);b.type=d;e=b.tag=$k(d);a=Lg(d,a);switch(e){case 0:b=dj(null,b,d,a,c);break a;case 1:b=ij(null,b,d,a,c);break a;case 11:b=Zi(null,b,d,a,c);break a;case 14:b=aj(null,b,d,Lg(d.type,a),c);break a}throw Error(p(306, +d,""));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),dj(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),ij(a,b,d,e,c);case 3:a:{lj(b);if(null===a)throw Error(p(387));d=b.pendingProps;f=b.memoizedState;e=f.element;bh(a,b);gh(b,d,null,c);var g=b.memoizedState;d=g.element;if(f.isDehydrated)if(f={element:d,isDehydrated:!1,cache:g.cache,pendingSuspenseBoundaries:g.pendingSuspenseBoundaries,transitions:g.transitions},b.updateQueue.baseState= +f,b.memoizedState=f,b.flags&256){e=Ki(Error(p(423)),b);b=mj(a,b,d,c,e);break a}else if(d!==e){e=Ki(Error(p(424)),b);b=mj(a,b,d,c,e);break a}else for(yg=Lf(b.stateNode.containerInfo.firstChild),xg=b,I=!0,zg=null,c=Ch(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else {Ig();if(d===e){b=$i(a,b,c);break a}Yi(a,b,d,c);}b=b.child;}return b;case 5:return Kh(b),null===a&&Eg(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,Ef(d,e)?g=null:null!==f&&Ef(d,f)&&(b.flags|=32), +hj(a,b),Yi(a,b,g,c),b.child;case 6:return null===a&&Eg(b),null;case 13:return pj(a,b,c);case 4:return Ih(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=Bh(b,null,d,c):Yi(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),Zi(a,b,d,e,c);case 7:return Yi(a,b,b.pendingProps,c),b.child;case 8:return Yi(a,b,b.pendingProps.children,c),b.child;case 12:return Yi(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;f=b.memoizedProps; +g=e.value;G(Mg,d._currentValue);d._currentValue=g;if(null!==f)if(He(f.value,g)){if(f.children===e.children&&!Wf.current){b=$i(a,b,c);break a}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=ch(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var m=l.pending;null===m?k.next=k:(k.next=m.next,m.next=k);l.pending=k;}}f.lanes|=c;k=f.alternate;null!==k&&(k.lanes|=c);Sg(f.return, +c,b);h.lanes|=c;break}k=k.next;}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===f.tag){g=f.return;if(null===g)throw Error(p(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);Sg(g,c,b);g=f.sibling;}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break}f=g.sibling;if(null!==f){f.return=g.return;g=f;break}g=g.return;}f=g;}Yi(a,b,e.children,c);b=b.child;}return b;case 9:return e=b.type,d=b.pendingProps.children,Tg(b,c),e=Vg(e),d=d(e),b.flags|=1,Yi(a,b,d,c), +b.child;case 14:return d=b.type,e=Lg(d,b.pendingProps),e=Lg(d.type,e),aj(a,b,d,e,c);case 15:return cj(a,b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),jj(a,b),b.tag=1,Zf(d)?(a=!0,cg(b)):a=!1,Tg(b,c),ph(b,d,e),rh(b,d,e,c),kj(null,b,d,!0,a,c);case 19:return yj(a,b,c);case 22:return ej(a,b,c)}throw Error(p(156,b.tag));};function Gk(a,b){return ac(a,b)} +function al(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null;}function Bg(a,b,c,d){return new al(a,b,c,d)}function bj(a){a=a.prototype;return !(!a||!a.isReactComponent)} +function $k(a){if("function"===typeof a)return bj(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===Da)return 11;if(a===Ga)return 14}return 2} +function wh(a,b){var c=a.alternate;null===c?(c=Bg(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.subtreeFlags=0,c.deletions=null);c.flags=a.flags&14680064;c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{lanes:b.lanes,firstContext:b.firstContext}; +c.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c} +function yh(a,b,c,d,e,f){var g=2;d=a;if("function"===typeof a)bj(a)&&(g=1);else if("string"===typeof a)g=5;else a:switch(a){case ya:return Ah(c.children,e,f,b);case za:g=8;e|=8;break;case Aa:return a=Bg(12,c,b,e|2),a.elementType=Aa,a.lanes=f,a;case Ea:return a=Bg(13,c,b,e),a.elementType=Ea,a.lanes=f,a;case Fa:return a=Bg(19,c,b,e),a.elementType=Fa,a.lanes=f,a;case Ia:return qj(c,e,f,b);default:if("object"===typeof a&&null!==a)switch(a.$$typeof){case Ba:g=10;break a;case Ca:g=9;break a;case Da:g=11; +break a;case Ga:g=14;break a;case Ha:g=16;d=null;break a}throw Error(p(130,null==a?a:typeof a,""));}b=Bg(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function Ah(a,b,c,d){a=Bg(7,a,d,b);a.lanes=c;return a}function qj(a,b,c,d){a=Bg(22,a,d,b);a.elementType=Ia;a.lanes=c;a.stateNode={isHidden:!1};return a}function xh(a,b,c){a=Bg(6,a,null,b);a.lanes=c;return a} +function zh(a,b,c){b=Bg(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b} +function bl(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=-1;this.callbackNode=this.pendingContext=this.context=null;this.callbackPriority=0;this.eventTimes=zc(0);this.expirationTimes=zc(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=zc(0);this.identifierPrefix=d;this.onRecoverableError=e;this.mutableSourceEagerHydrationData= +null;}function cl(a,b,c,d,e,f,g,h,k){a=new bl(a,b,c,h,k);1===b?(b=1,!0===f&&(b|=8)):b=0;f=Bg(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null,pendingSuspenseBoundaries:null};ah(f);return a}function dl(a,b,c){var d=3>> 0, + i; + + for (i = 0; i < len; i++) { + if (i in t && fun.call(this, t[i], i, t)) { + return true; + } + } + + return false; + }; + } + + function isValid(m) { + if (m._isValid == null) { + var flags = getParsingFlags(m), + parsedParts = some.call(flags.parsedDateParts, function (i) { + return i != null; + }), + isNowValid = + !isNaN(m._d.getTime()) && + flags.overflow < 0 && + !flags.empty && + !flags.invalidEra && + !flags.invalidMonth && + !flags.invalidWeekday && + !flags.weekdayMismatch && + !flags.nullInput && + !flags.invalidFormat && + !flags.userInvalidated && + (!flags.meridiem || (flags.meridiem && parsedParts)); + + if (m._strict) { + isNowValid = + isNowValid && + flags.charsLeftOver === 0 && + flags.unusedTokens.length === 0 && + flags.bigHour === undefined; + } + + if (Object.isFrozen == null || !Object.isFrozen(m)) { + m._isValid = isNowValid; + } else { + return isNowValid; + } + } + return m._isValid; + } + + function createInvalid(flags) { + var m = createUTC(NaN); + if (flags != null) { + extend(getParsingFlags(m), flags); + } else { + getParsingFlags(m).userInvalidated = true; + } + + return m; + } + + // Plugins that add properties should also add the key here (null value), + // so we can properly clone ourselves. + var momentProperties = (hooks.momentProperties = []), + updateInProgress = false; + + function copyConfig(to, from) { + var i, + prop, + val, + momentPropertiesLen = momentProperties.length; + + if (!isUndefined(from._isAMomentObject)) { + to._isAMomentObject = from._isAMomentObject; + } + if (!isUndefined(from._i)) { + to._i = from._i; + } + if (!isUndefined(from._f)) { + to._f = from._f; + } + if (!isUndefined(from._l)) { + to._l = from._l; + } + if (!isUndefined(from._strict)) { + to._strict = from._strict; + } + if (!isUndefined(from._tzm)) { + to._tzm = from._tzm; + } + if (!isUndefined(from._isUTC)) { + to._isUTC = from._isUTC; + } + if (!isUndefined(from._offset)) { + to._offset = from._offset; + } + if (!isUndefined(from._pf)) { + to._pf = getParsingFlags(from); + } + if (!isUndefined(from._locale)) { + to._locale = from._locale; + } + + if (momentPropertiesLen > 0) { + for (i = 0; i < momentPropertiesLen; i++) { + prop = momentProperties[i]; + val = from[prop]; + if (!isUndefined(val)) { + to[prop] = val; + } + } + } + + return to; + } + + // Moment prototype object + function Moment(config) { + copyConfig(this, config); + this._d = new Date(config._d != null ? config._d.getTime() : NaN); + if (!this.isValid()) { + this._d = new Date(NaN); + } + // Prevent infinite loop in case updateOffset creates new moment + // objects. + if (updateInProgress === false) { + updateInProgress = true; + hooks.updateOffset(this); + updateInProgress = false; + } + } + + function isMoment(obj) { + return ( + obj instanceof Moment || (obj != null && obj._isAMomentObject != null) + ); + } + + function warn(msg) { + if ( + hooks.suppressDeprecationWarnings === false && + typeof console !== 'undefined' && + console.warn + ) { + console.warn('Deprecation warning: ' + msg); + } + } + + function deprecate(msg, fn) { + var firstTime = true; + + return extend(function () { + if (hooks.deprecationHandler != null) { + hooks.deprecationHandler(null, msg); + } + if (firstTime) { + var args = [], + arg, + i, + key, + argLen = arguments.length; + for (i = 0; i < argLen; i++) { + arg = ''; + if (typeof arguments[i] === 'object') { + arg += '\n[' + i + '] '; + for (key in arguments[0]) { + if (hasOwnProp(arguments[0], key)) { + arg += key + ': ' + arguments[0][key] + ', '; + } + } + arg = arg.slice(0, -2); // Remove trailing comma and space + } else { + arg = arguments[i]; + } + args.push(arg); + } + warn( + msg + + '\nArguments: ' + + Array.prototype.slice.call(args).join('') + + '\n' + + new Error().stack + ); + firstTime = false; + } + return fn.apply(this, arguments); + }, fn); + } + + var deprecations = {}; + + function deprecateSimple(name, msg) { + if (hooks.deprecationHandler != null) { + hooks.deprecationHandler(name, msg); + } + if (!deprecations[name]) { + warn(msg); + deprecations[name] = true; + } + } + + hooks.suppressDeprecationWarnings = false; + hooks.deprecationHandler = null; + + function isFunction(input) { + return ( + (typeof Function !== 'undefined' && input instanceof Function) || + Object.prototype.toString.call(input) === '[object Function]' + ); + } + + function set(config) { + var prop, i; + for (i in config) { + if (hasOwnProp(config, i)) { + prop = config[i]; + if (isFunction(prop)) { + this[i] = prop; + } else { + this['_' + i] = prop; + } + } + } + this._config = config; + // Lenient ordinal parsing accepts just a number in addition to + // number + (possibly) stuff coming from _dayOfMonthOrdinalParse. + // TODO: Remove "ordinalParse" fallback in next major release. + this._dayOfMonthOrdinalParseLenient = new RegExp( + (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + + '|' + + /\d{1,2}/.source + ); + } + + function mergeConfigs(parentConfig, childConfig) { + var res = extend({}, parentConfig), + prop; + for (prop in childConfig) { + if (hasOwnProp(childConfig, prop)) { + if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) { + res[prop] = {}; + extend(res[prop], parentConfig[prop]); + extend(res[prop], childConfig[prop]); + } else if (childConfig[prop] != null) { + res[prop] = childConfig[prop]; + } else { + delete res[prop]; + } + } + } + for (prop in parentConfig) { + if ( + hasOwnProp(parentConfig, prop) && + !hasOwnProp(childConfig, prop) && + isObject(parentConfig[prop]) + ) { + // make sure changes to properties don't modify parent config + res[prop] = extend({}, res[prop]); + } + } + return res; + } + + function Locale(config) { + if (config != null) { + this.set(config); + } + } + + var keys; + + if (Object.keys) { + keys = Object.keys; + } else { + keys = function (obj) { + var i, + res = []; + for (i in obj) { + if (hasOwnProp(obj, i)) { + res.push(i); + } + } + return res; + }; + } + + var defaultCalendar = { + sameDay: '[Today at] LT', + nextDay: '[Tomorrow at] LT', + nextWeek: 'dddd [at] LT', + lastDay: '[Yesterday at] LT', + lastWeek: '[Last] dddd [at] LT', + sameElse: 'L', + }; + + function calendar(key, mom, now) { + var output = this._calendar[key] || this._calendar['sameElse']; + return isFunction(output) ? output.call(mom, now) : output; + } + + function zeroFill(number, targetLength, forceSign) { + var absNumber = '' + Math.abs(number), + zerosToFill = targetLength - absNumber.length, + sign = number >= 0; + return ( + (sign ? (forceSign ? '+' : '') : '-') + + Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + + absNumber + ); + } + + var formattingTokens = + /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g, + localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, + formatFunctions = {}, + formatTokenFunctions = {}; + + // token: 'M' + // padded: ['MM', 2] + // ordinal: 'Mo' + // callback: function () { this.month() + 1 } + function addFormatToken(token, padded, ordinal, callback) { + var func = callback; + if (typeof callback === 'string') { + func = function () { + return this[callback](); + }; + } + if (token) { + formatTokenFunctions[token] = func; + } + if (padded) { + formatTokenFunctions[padded[0]] = function () { + return zeroFill(func.apply(this, arguments), padded[1], padded[2]); + }; + } + if (ordinal) { + formatTokenFunctions[ordinal] = function () { + return this.localeData().ordinal( + func.apply(this, arguments), + token + ); + }; + } + } + + function removeFormattingTokens(input) { + if (input.match(/\[[\s\S]/)) { + return input.replace(/^\[|\]$/g, ''); + } + return input.replace(/\\/g, ''); + } + + function makeFormatFunction(format) { + var array = format.match(formattingTokens), + i, + length; + + for (i = 0, length = array.length; i < length; i++) { + if (formatTokenFunctions[array[i]]) { + array[i] = formatTokenFunctions[array[i]]; + } else { + array[i] = removeFormattingTokens(array[i]); + } + } + + return function (mom) { + var output = '', + i; + for (i = 0; i < length; i++) { + output += isFunction(array[i]) + ? array[i].call(mom, format) + : array[i]; + } + return output; + }; + } + + // format date using native date object + function formatMoment(m, format) { + if (!m.isValid()) { + return m.localeData().invalidDate(); + } + + format = expandFormat(format, m.localeData()); + formatFunctions[format] = + formatFunctions[format] || makeFormatFunction(format); + + return formatFunctions[format](m); + } + + function expandFormat(format, locale) { + var i = 5; + + function replaceLongDateFormatTokens(input) { + return locale.longDateFormat(input) || input; + } + + localFormattingTokens.lastIndex = 0; + while (i >= 0 && localFormattingTokens.test(format)) { + format = format.replace( + localFormattingTokens, + replaceLongDateFormatTokens + ); + localFormattingTokens.lastIndex = 0; + i -= 1; + } + + return format; + } + + var defaultLongDateFormat = { + LTS: 'h:mm:ss A', + LT: 'h:mm A', + L: 'MM/DD/YYYY', + LL: 'MMMM D, YYYY', + LLL: 'MMMM D, YYYY h:mm A', + LLLL: 'dddd, MMMM D, YYYY h:mm A', + }; + + function longDateFormat(key) { + var format = this._longDateFormat[key], + formatUpper = this._longDateFormat[key.toUpperCase()]; + + if (format || !formatUpper) { + return format; + } + + this._longDateFormat[key] = formatUpper + .match(formattingTokens) + .map(function (tok) { + if ( + tok === 'MMMM' || + tok === 'MM' || + tok === 'DD' || + tok === 'dddd' + ) { + return tok.slice(1); + } + return tok; + }) + .join(''); + + return this._longDateFormat[key]; + } + + var defaultInvalidDate = 'Invalid date'; + + function invalidDate() { + return this._invalidDate; + } + + var defaultOrdinal = '%d', + defaultDayOfMonthOrdinalParse = /\d{1,2}/; + + function ordinal(number) { + return this._ordinal.replace('%d', number); + } + + var defaultRelativeTime = { + future: 'in %s', + past: '%s ago', + s: 'a few seconds', + ss: '%d seconds', + m: 'a minute', + mm: '%d minutes', + h: 'an hour', + hh: '%d hours', + d: 'a day', + dd: '%d days', + w: 'a week', + ww: '%d weeks', + M: 'a month', + MM: '%d months', + y: 'a year', + yy: '%d years', + }; + + function relativeTime(number, withoutSuffix, string, isFuture) { + var output = this._relativeTime[string]; + return isFunction(output) + ? output(number, withoutSuffix, string, isFuture) + : output.replace(/%d/i, number); + } + + function pastFuture(diff, output) { + var format = this._relativeTime[diff > 0 ? 'future' : 'past']; + return isFunction(format) ? format(output) : format.replace(/%s/i, output); + } + + var aliases = {}; + + function addUnitAlias(unit, shorthand) { + var lowerCase = unit.toLowerCase(); + aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit; + } + + function normalizeUnits(units) { + return typeof units === 'string' + ? aliases[units] || aliases[units.toLowerCase()] + : undefined; + } + + function normalizeObjectUnits(inputObject) { + var normalizedInput = {}, + normalizedProp, + prop; + + for (prop in inputObject) { + if (hasOwnProp(inputObject, prop)) { + normalizedProp = normalizeUnits(prop); + if (normalizedProp) { + normalizedInput[normalizedProp] = inputObject[prop]; + } + } + } + + return normalizedInput; + } + + var priorities = {}; + + function addUnitPriority(unit, priority) { + priorities[unit] = priority; + } + + function getPrioritizedUnits(unitsObj) { + var units = [], + u; + for (u in unitsObj) { + if (hasOwnProp(unitsObj, u)) { + units.push({ unit: u, priority: priorities[u] }); + } + } + units.sort(function (a, b) { + return a.priority - b.priority; + }); + return units; + } + + function isLeapYear(year) { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; + } + + function absFloor(number) { + if (number < 0) { + // -0 -> 0 + return Math.ceil(number) || 0; + } else { + return Math.floor(number); + } + } + + function toInt(argumentForCoercion) { + var coercedNumber = +argumentForCoercion, + value = 0; + + if (coercedNumber !== 0 && isFinite(coercedNumber)) { + value = absFloor(coercedNumber); + } + + return value; + } + + function makeGetSet(unit, keepTime) { + return function (value) { + if (value != null) { + set$1(this, unit, value); + hooks.updateOffset(this, keepTime); + return this; + } else { + return get(this, unit); + } + }; + } + + function get(mom, unit) { + return mom.isValid() + ? mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() + : NaN; + } + + function set$1(mom, unit, value) { + if (mom.isValid() && !isNaN(value)) { + if ( + unit === 'FullYear' && + isLeapYear(mom.year()) && + mom.month() === 1 && + mom.date() === 29 + ) { + value = toInt(value); + mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit]( + value, + mom.month(), + daysInMonth(value, mom.month()) + ); + } else { + mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value); + } + } + } + + // MOMENTS + + function stringGet(units) { + units = normalizeUnits(units); + if (isFunction(this[units])) { + return this[units](); + } + return this; + } + + function stringSet(units, value) { + if (typeof units === 'object') { + units = normalizeObjectUnits(units); + var prioritized = getPrioritizedUnits(units), + i, + prioritizedLen = prioritized.length; + for (i = 0; i < prioritizedLen; i++) { + this[prioritized[i].unit](units[prioritized[i].unit]); + } + } else { + units = normalizeUnits(units); + if (isFunction(this[units])) { + return this[units](value); + } + } + return this; + } + + var match1 = /\d/, // 0 - 9 + match2 = /\d\d/, // 00 - 99 + match3 = /\d{3}/, // 000 - 999 + match4 = /\d{4}/, // 0000 - 9999 + match6 = /[+-]?\d{6}/, // -999999 - 999999 + match1to2 = /\d\d?/, // 0 - 99 + match3to4 = /\d\d\d\d?/, // 999 - 9999 + match5to6 = /\d\d\d\d\d\d?/, // 99999 - 999999 + match1to3 = /\d{1,3}/, // 0 - 999 + match1to4 = /\d{1,4}/, // 0 - 9999 + match1to6 = /[+-]?\d{1,6}/, // -999999 - 999999 + matchUnsigned = /\d+/, // 0 - inf + matchSigned = /[+-]?\d+/, // -inf - inf + matchOffset = /Z|[+-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z + matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi, // +00 -00 +00:00 -00:00 +0000 -0000 or Z + matchTimestamp = /[+-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123 + // any word (or two) characters or numbers including two/three word month in arabic. + // includes scottish gaelic two word and hyphenated months + 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, + regexes; + + regexes = {}; + + function addRegexToken(token, regex, strictRegex) { + regexes[token] = isFunction(regex) + ? regex + : function (isStrict, localeData) { + return isStrict && strictRegex ? strictRegex : regex; + }; + } + + function getParseRegexForToken(token, config) { + if (!hasOwnProp(regexes, token)) { + return new RegExp(unescapeFormat(token)); + } + + return regexes[token](config._strict, config._locale); + } + + // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript + function unescapeFormat(s) { + return regexEscape( + s + .replace('\\', '') + .replace( + /\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, + function (matched, p1, p2, p3, p4) { + return p1 || p2 || p3 || p4; + } + ) + ); + } + + function regexEscape(s) { + return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); + } + + var tokens = {}; + + function addParseToken(token, callback) { + var i, + func = callback, + tokenLen; + if (typeof token === 'string') { + token = [token]; + } + if (isNumber(callback)) { + func = function (input, array) { + array[callback] = toInt(input); + }; + } + tokenLen = token.length; + for (i = 0; i < tokenLen; i++) { + tokens[token[i]] = func; + } + } + + function addWeekParseToken(token, callback) { + addParseToken(token, function (input, array, config, token) { + config._w = config._w || {}; + callback(input, config._w, config, token); + }); + } + + function addTimeToArrayFromToken(token, input, config) { + if (input != null && hasOwnProp(tokens, token)) { + tokens[token](input, config._a, config, token); + } + } + + var YEAR = 0, + MONTH = 1, + DATE = 2, + HOUR = 3, + MINUTE = 4, + SECOND = 5, + MILLISECOND = 6, + WEEK = 7, + WEEKDAY = 8; + + function mod(n, x) { + return ((n % x) + x) % x; + } + + var indexOf; + + if (Array.prototype.indexOf) { + indexOf = Array.prototype.indexOf; + } else { + indexOf = function (o) { + // I know + var i; + for (i = 0; i < this.length; ++i) { + if (this[i] === o) { + return i; + } + } + return -1; + }; + } + + function daysInMonth(year, month) { + if (isNaN(year) || isNaN(month)) { + return NaN; + } + var modMonth = mod(month, 12); + year += (month - modMonth) / 12; + return modMonth === 1 + ? isLeapYear(year) + ? 29 + : 28 + : 31 - ((modMonth % 7) % 2); + } + + // FORMATTING + + addFormatToken('M', ['MM', 2], 'Mo', function () { + return this.month() + 1; + }); + + addFormatToken('MMM', 0, 0, function (format) { + return this.localeData().monthsShort(this, format); + }); + + addFormatToken('MMMM', 0, 0, function (format) { + return this.localeData().months(this, format); + }); + + // ALIASES + + addUnitAlias('month', 'M'); + + // PRIORITY + + addUnitPriority('month', 8); + + // PARSING + + addRegexToken('M', match1to2); + addRegexToken('MM', match1to2, match2); + addRegexToken('MMM', function (isStrict, locale) { + return locale.monthsShortRegex(isStrict); + }); + addRegexToken('MMMM', function (isStrict, locale) { + return locale.monthsRegex(isStrict); + }); + + addParseToken(['M', 'MM'], function (input, array) { + array[MONTH] = toInt(input) - 1; + }); + + addParseToken(['MMM', 'MMMM'], function (input, array, config, token) { + var month = config._locale.monthsParse(input, token, config._strict); + // if we didn't find a month name, mark the date as invalid. + if (month != null) { + array[MONTH] = month; + } else { + getParsingFlags(config).invalidMonth = input; + } + }); + + // LOCALES + + var defaultLocaleMonths = + 'January_February_March_April_May_June_July_August_September_October_November_December'.split( + '_' + ), + defaultLocaleMonthsShort = + 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), + MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/, + defaultMonthsShortRegex = matchWord, + defaultMonthsRegex = matchWord; + + function localeMonths(m, format) { + if (!m) { + return isArray(this._months) + ? this._months + : this._months['standalone']; + } + return isArray(this._months) + ? this._months[m.month()] + : this._months[ + (this._months.isFormat || MONTHS_IN_FORMAT).test(format) + ? 'format' + : 'standalone' + ][m.month()]; + } + + function localeMonthsShort(m, format) { + if (!m) { + return isArray(this._monthsShort) + ? this._monthsShort + : this._monthsShort['standalone']; + } + return isArray(this._monthsShort) + ? this._monthsShort[m.month()] + : this._monthsShort[ + MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone' + ][m.month()]; + } + + function handleStrictParse(monthName, format, strict) { + var i, + ii, + mom, + llc = monthName.toLocaleLowerCase(); + if (!this._monthsParse) { + // this is not used + this._monthsParse = []; + this._longMonthsParse = []; + this._shortMonthsParse = []; + for (i = 0; i < 12; ++i) { + mom = createUTC([2000, i]); + this._shortMonthsParse[i] = this.monthsShort( + mom, + '' + ).toLocaleLowerCase(); + this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase(); + } + } + + if (strict) { + if (format === 'MMM') { + ii = indexOf.call(this._shortMonthsParse, llc); + return ii !== -1 ? ii : null; + } else { + ii = indexOf.call(this._longMonthsParse, llc); + return ii !== -1 ? ii : null; + } + } else { + if (format === 'MMM') { + ii = indexOf.call(this._shortMonthsParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._longMonthsParse, llc); + return ii !== -1 ? ii : null; + } else { + ii = indexOf.call(this._longMonthsParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._shortMonthsParse, llc); + return ii !== -1 ? ii : null; + } + } + } + + function localeMonthsParse(monthName, format, strict) { + var i, mom, regex; + + if (this._monthsParseExact) { + return handleStrictParse.call(this, monthName, format, strict); + } + + if (!this._monthsParse) { + this._monthsParse = []; + this._longMonthsParse = []; + this._shortMonthsParse = []; + } + + // TODO: add sorting + // Sorting makes sure if one month (or abbr) is a prefix of another + // see sorting in computeMonthsParse + for (i = 0; i < 12; i++) { + // make the regex if we don't have it already + mom = createUTC([2000, i]); + if (strict && !this._longMonthsParse[i]) { + this._longMonthsParse[i] = new RegExp( + '^' + this.months(mom, '').replace('.', '') + '$', + 'i' + ); + this._shortMonthsParse[i] = new RegExp( + '^' + this.monthsShort(mom, '').replace('.', '') + '$', + 'i' + ); + } + if (!strict && !this._monthsParse[i]) { + regex = + '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); + this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); + } + // test the regex + if ( + strict && + format === 'MMMM' && + this._longMonthsParse[i].test(monthName) + ) { + return i; + } else if ( + strict && + format === 'MMM' && + this._shortMonthsParse[i].test(monthName) + ) { + return i; + } else if (!strict && this._monthsParse[i].test(monthName)) { + return i; + } + } + } + + // MOMENTS + + function setMonth(mom, value) { + var dayOfMonth; + + if (!mom.isValid()) { + // No op + return mom; + } + + if (typeof value === 'string') { + if (/^\d+$/.test(value)) { + value = toInt(value); + } else { + value = mom.localeData().monthsParse(value); + // TODO: Another silent failure? + if (!isNumber(value)) { + return mom; + } + } + } + + dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); + mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth); + return mom; + } + + function getSetMonth(value) { + if (value != null) { + setMonth(this, value); + hooks.updateOffset(this, true); + return this; + } else { + return get(this, 'Month'); + } + } + + function getDaysInMonth() { + return daysInMonth(this.year(), this.month()); + } + + function monthsShortRegex(isStrict) { + if (this._monthsParseExact) { + if (!hasOwnProp(this, '_monthsRegex')) { + computeMonthsParse.call(this); + } + if (isStrict) { + return this._monthsShortStrictRegex; + } else { + return this._monthsShortRegex; + } + } else { + if (!hasOwnProp(this, '_monthsShortRegex')) { + this._monthsShortRegex = defaultMonthsShortRegex; + } + return this._monthsShortStrictRegex && isStrict + ? this._monthsShortStrictRegex + : this._monthsShortRegex; + } + } + + function monthsRegex(isStrict) { + if (this._monthsParseExact) { + if (!hasOwnProp(this, '_monthsRegex')) { + computeMonthsParse.call(this); + } + if (isStrict) { + return this._monthsStrictRegex; + } else { + return this._monthsRegex; + } + } else { + if (!hasOwnProp(this, '_monthsRegex')) { + this._monthsRegex = defaultMonthsRegex; + } + return this._monthsStrictRegex && isStrict + ? this._monthsStrictRegex + : this._monthsRegex; + } + } + + function computeMonthsParse() { + function cmpLenRev(a, b) { + return b.length - a.length; + } + + var shortPieces = [], + longPieces = [], + mixedPieces = [], + i, + mom; + for (i = 0; i < 12; i++) { + // make the regex if we don't have it already + mom = createUTC([2000, i]); + shortPieces.push(this.monthsShort(mom, '')); + longPieces.push(this.months(mom, '')); + mixedPieces.push(this.months(mom, '')); + mixedPieces.push(this.monthsShort(mom, '')); + } + // Sorting makes sure if one month (or abbr) is a prefix of another it + // will match the longer piece. + shortPieces.sort(cmpLenRev); + longPieces.sort(cmpLenRev); + mixedPieces.sort(cmpLenRev); + for (i = 0; i < 12; i++) { + shortPieces[i] = regexEscape(shortPieces[i]); + longPieces[i] = regexEscape(longPieces[i]); + } + for (i = 0; i < 24; i++) { + mixedPieces[i] = regexEscape(mixedPieces[i]); + } + + this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); + this._monthsShortRegex = this._monthsRegex; + this._monthsStrictRegex = new RegExp( + '^(' + longPieces.join('|') + ')', + 'i' + ); + this._monthsShortStrictRegex = new RegExp( + '^(' + shortPieces.join('|') + ')', + 'i' + ); + } + + // FORMATTING + + addFormatToken('Y', 0, 0, function () { + var y = this.year(); + return y <= 9999 ? zeroFill(y, 4) : '+' + y; + }); + + addFormatToken(0, ['YY', 2], 0, function () { + return this.year() % 100; + }); + + addFormatToken(0, ['YYYY', 4], 0, 'year'); + addFormatToken(0, ['YYYYY', 5], 0, 'year'); + addFormatToken(0, ['YYYYYY', 6, true], 0, 'year'); + + // ALIASES + + addUnitAlias('year', 'y'); + + // PRIORITIES + + addUnitPriority('year', 1); + + // PARSING + + addRegexToken('Y', matchSigned); + addRegexToken('YY', match1to2, match2); + addRegexToken('YYYY', match1to4, match4); + addRegexToken('YYYYY', match1to6, match6); + addRegexToken('YYYYYY', match1to6, match6); + + addParseToken(['YYYYY', 'YYYYYY'], YEAR); + addParseToken('YYYY', function (input, array) { + array[YEAR] = + input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input); + }); + addParseToken('YY', function (input, array) { + array[YEAR] = hooks.parseTwoDigitYear(input); + }); + addParseToken('Y', function (input, array) { + array[YEAR] = parseInt(input, 10); + }); + + // HELPERS + + function daysInYear(year) { + return isLeapYear(year) ? 366 : 365; + } + + // HOOKS + + hooks.parseTwoDigitYear = function (input) { + return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); + }; + + // MOMENTS + + var getSetYear = makeGetSet('FullYear', true); + + function getIsLeapYear() { + return isLeapYear(this.year()); + } + + function createDate(y, m, d, h, M, s, ms) { + // can't just apply() to create a date: + // https://stackoverflow.com/q/181348 + var date; + // the date constructor remaps years 0-99 to 1900-1999 + if (y < 100 && y >= 0) { + // preserve leap years using a full 400 year cycle, then reset + date = new Date(y + 400, m, d, h, M, s, ms); + if (isFinite(date.getFullYear())) { + date.setFullYear(y); + } + } else { + date = new Date(y, m, d, h, M, s, ms); + } + + return date; + } + + function createUTCDate(y) { + var date, args; + // the Date.UTC function remaps years 0-99 to 1900-1999 + if (y < 100 && y >= 0) { + args = Array.prototype.slice.call(arguments); + // preserve leap years using a full 400 year cycle, then reset + args[0] = y + 400; + date = new Date(Date.UTC.apply(null, args)); + if (isFinite(date.getUTCFullYear())) { + date.setUTCFullYear(y); + } + } else { + date = new Date(Date.UTC.apply(null, arguments)); + } + + return date; + } + + // start-of-first-week - start-of-year + function firstWeekOffset(year, dow, doy) { + var // first-week day -- which january is always in the first week (4 for iso, 1 for other) + fwd = 7 + dow - doy, + // first-week day local weekday -- which local weekday is fwd + fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7; + + return -fwdlw + fwd - 1; + } + + // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday + function dayOfYearFromWeeks(year, week, weekday, dow, doy) { + var localWeekday = (7 + weekday - dow) % 7, + weekOffset = firstWeekOffset(year, dow, doy), + dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset, + resYear, + resDayOfYear; + + if (dayOfYear <= 0) { + resYear = year - 1; + resDayOfYear = daysInYear(resYear) + dayOfYear; + } else if (dayOfYear > daysInYear(year)) { + resYear = year + 1; + resDayOfYear = dayOfYear - daysInYear(year); + } else { + resYear = year; + resDayOfYear = dayOfYear; + } + + return { + year: resYear, + dayOfYear: resDayOfYear, + }; + } + + function weekOfYear(mom, dow, doy) { + var weekOffset = firstWeekOffset(mom.year(), dow, doy), + week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1, + resWeek, + resYear; + + if (week < 1) { + resYear = mom.year() - 1; + resWeek = week + weeksInYear(resYear, dow, doy); + } else if (week > weeksInYear(mom.year(), dow, doy)) { + resWeek = week - weeksInYear(mom.year(), dow, doy); + resYear = mom.year() + 1; + } else { + resYear = mom.year(); + resWeek = week; + } + + return { + week: resWeek, + year: resYear, + }; + } + + function weeksInYear(year, dow, doy) { + var weekOffset = firstWeekOffset(year, dow, doy), + weekOffsetNext = firstWeekOffset(year + 1, dow, doy); + return (daysInYear(year) - weekOffset + weekOffsetNext) / 7; + } + + // FORMATTING + + addFormatToken('w', ['ww', 2], 'wo', 'week'); + addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek'); + + // ALIASES + + addUnitAlias('week', 'w'); + addUnitAlias('isoWeek', 'W'); + + // PRIORITIES + + addUnitPriority('week', 5); + addUnitPriority('isoWeek', 5); + + // PARSING + + addRegexToken('w', match1to2); + addRegexToken('ww', match1to2, match2); + addRegexToken('W', match1to2); + addRegexToken('WW', match1to2, match2); + + addWeekParseToken( + ['w', 'ww', 'W', 'WW'], + function (input, week, config, token) { + week[token.substr(0, 1)] = toInt(input); + } + ); + + // HELPERS + + // LOCALES + + function localeWeek(mom) { + return weekOfYear(mom, this._week.dow, this._week.doy).week; + } + + var defaultLocaleWeek = { + dow: 0, // Sunday is the first day of the week. + doy: 6, // The week that contains Jan 6th is the first week of the year. + }; + + function localeFirstDayOfWeek() { + return this._week.dow; + } + + function localeFirstDayOfYear() { + return this._week.doy; + } + + // MOMENTS + + function getSetWeek(input) { + var week = this.localeData().week(this); + return input == null ? week : this.add((input - week) * 7, 'd'); + } + + function getSetISOWeek(input) { + var week = weekOfYear(this, 1, 4).week; + return input == null ? week : this.add((input - week) * 7, 'd'); + } + + // FORMATTING + + addFormatToken('d', 0, 'do', 'day'); + + addFormatToken('dd', 0, 0, function (format) { + return this.localeData().weekdaysMin(this, format); + }); + + addFormatToken('ddd', 0, 0, function (format) { + return this.localeData().weekdaysShort(this, format); + }); + + addFormatToken('dddd', 0, 0, function (format) { + return this.localeData().weekdays(this, format); + }); + + addFormatToken('e', 0, 0, 'weekday'); + addFormatToken('E', 0, 0, 'isoWeekday'); + + // ALIASES + + addUnitAlias('day', 'd'); + addUnitAlias('weekday', 'e'); + addUnitAlias('isoWeekday', 'E'); + + // PRIORITY + addUnitPriority('day', 11); + addUnitPriority('weekday', 11); + addUnitPriority('isoWeekday', 11); + + // PARSING + + addRegexToken('d', match1to2); + addRegexToken('e', match1to2); + addRegexToken('E', match1to2); + addRegexToken('dd', function (isStrict, locale) { + return locale.weekdaysMinRegex(isStrict); + }); + addRegexToken('ddd', function (isStrict, locale) { + return locale.weekdaysShortRegex(isStrict); + }); + addRegexToken('dddd', function (isStrict, locale) { + return locale.weekdaysRegex(isStrict); + }); + + addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) { + var weekday = config._locale.weekdaysParse(input, token, config._strict); + // if we didn't get a weekday name, mark the date as invalid + if (weekday != null) { + week.d = weekday; + } else { + getParsingFlags(config).invalidWeekday = input; + } + }); + + addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) { + week[token] = toInt(input); + }); + + // HELPERS + + function parseWeekday(input, locale) { + if (typeof input !== 'string') { + return input; + } + + if (!isNaN(input)) { + return parseInt(input, 10); + } + + input = locale.weekdaysParse(input); + if (typeof input === 'number') { + return input; + } + + return null; + } + + function parseIsoWeekday(input, locale) { + if (typeof input === 'string') { + return locale.weekdaysParse(input) % 7 || 7; + } + return isNaN(input) ? null : input; + } + + // LOCALES + function shiftWeekdays(ws, n) { + return ws.slice(n, 7).concat(ws.slice(0, n)); + } + + var defaultLocaleWeekdays = + 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), + defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), + defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), + defaultWeekdaysRegex = matchWord, + defaultWeekdaysShortRegex = matchWord, + defaultWeekdaysMinRegex = matchWord; + + function localeWeekdays(m, format) { + var weekdays = isArray(this._weekdays) + ? this._weekdays + : this._weekdays[ + m && m !== true && this._weekdays.isFormat.test(format) + ? 'format' + : 'standalone' + ]; + return m === true + ? shiftWeekdays(weekdays, this._week.dow) + : m + ? weekdays[m.day()] + : weekdays; + } + + function localeWeekdaysShort(m) { + return m === true + ? shiftWeekdays(this._weekdaysShort, this._week.dow) + : m + ? this._weekdaysShort[m.day()] + : this._weekdaysShort; + } + + function localeWeekdaysMin(m) { + return m === true + ? shiftWeekdays(this._weekdaysMin, this._week.dow) + : m + ? this._weekdaysMin[m.day()] + : this._weekdaysMin; + } + + function handleStrictParse$1(weekdayName, format, strict) { + var i, + ii, + mom, + llc = weekdayName.toLocaleLowerCase(); + if (!this._weekdaysParse) { + this._weekdaysParse = []; + this._shortWeekdaysParse = []; + this._minWeekdaysParse = []; + + for (i = 0; i < 7; ++i) { + mom = createUTC([2000, 1]).day(i); + this._minWeekdaysParse[i] = this.weekdaysMin( + mom, + '' + ).toLocaleLowerCase(); + this._shortWeekdaysParse[i] = this.weekdaysShort( + mom, + '' + ).toLocaleLowerCase(); + this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase(); + } + } + + if (strict) { + if (format === 'dddd') { + ii = indexOf.call(this._weekdaysParse, llc); + return ii !== -1 ? ii : null; + } else if (format === 'ddd') { + ii = indexOf.call(this._shortWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } else { + ii = indexOf.call(this._minWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } + } else { + if (format === 'dddd') { + ii = indexOf.call(this._weekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._shortWeekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._minWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } else if (format === 'ddd') { + ii = indexOf.call(this._shortWeekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._weekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._minWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } else { + ii = indexOf.call(this._minWeekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._weekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._shortWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } + } + } + + function localeWeekdaysParse(weekdayName, format, strict) { + var i, mom, regex; + + if (this._weekdaysParseExact) { + return handleStrictParse$1.call(this, weekdayName, format, strict); + } + + if (!this._weekdaysParse) { + this._weekdaysParse = []; + this._minWeekdaysParse = []; + this._shortWeekdaysParse = []; + this._fullWeekdaysParse = []; + } + + for (i = 0; i < 7; i++) { + // make the regex if we don't have it already + + mom = createUTC([2000, 1]).day(i); + if (strict && !this._fullWeekdaysParse[i]) { + this._fullWeekdaysParse[i] = new RegExp( + '^' + this.weekdays(mom, '').replace('.', '\\.?') + '$', + 'i' + ); + this._shortWeekdaysParse[i] = new RegExp( + '^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$', + 'i' + ); + this._minWeekdaysParse[i] = new RegExp( + '^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$', + 'i' + ); + } + if (!this._weekdaysParse[i]) { + regex = + '^' + + this.weekdays(mom, '') + + '|^' + + this.weekdaysShort(mom, '') + + '|^' + + this.weekdaysMin(mom, ''); + this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); + } + // test the regex + if ( + strict && + format === 'dddd' && + this._fullWeekdaysParse[i].test(weekdayName) + ) { + return i; + } else if ( + strict && + format === 'ddd' && + this._shortWeekdaysParse[i].test(weekdayName) + ) { + return i; + } else if ( + strict && + format === 'dd' && + this._minWeekdaysParse[i].test(weekdayName) + ) { + return i; + } else if (!strict && this._weekdaysParse[i].test(weekdayName)) { + return i; + } + } + } + + // MOMENTS + + function getSetDayOfWeek(input) { + if (!this.isValid()) { + return input != null ? this : NaN; + } + var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); + if (input != null) { + input = parseWeekday(input, this.localeData()); + return this.add(input - day, 'd'); + } else { + return day; + } + } + + function getSetLocaleDayOfWeek(input) { + if (!this.isValid()) { + return input != null ? this : NaN; + } + var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; + return input == null ? weekday : this.add(input - weekday, 'd'); + } + + function getSetISODayOfWeek(input) { + if (!this.isValid()) { + return input != null ? this : NaN; + } + + // behaves the same as moment#day except + // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) + // as a setter, sunday should belong to the previous week. + + if (input != null) { + var weekday = parseIsoWeekday(input, this.localeData()); + return this.day(this.day() % 7 ? weekday : weekday - 7); + } else { + return this.day() || 7; + } + } + + function weekdaysRegex(isStrict) { + if (this._weekdaysParseExact) { + if (!hasOwnProp(this, '_weekdaysRegex')) { + computeWeekdaysParse.call(this); + } + if (isStrict) { + return this._weekdaysStrictRegex; + } else { + return this._weekdaysRegex; + } + } else { + if (!hasOwnProp(this, '_weekdaysRegex')) { + this._weekdaysRegex = defaultWeekdaysRegex; + } + return this._weekdaysStrictRegex && isStrict + ? this._weekdaysStrictRegex + : this._weekdaysRegex; + } + } + + function weekdaysShortRegex(isStrict) { + if (this._weekdaysParseExact) { + if (!hasOwnProp(this, '_weekdaysRegex')) { + computeWeekdaysParse.call(this); + } + if (isStrict) { + return this._weekdaysShortStrictRegex; + } else { + return this._weekdaysShortRegex; + } + } else { + if (!hasOwnProp(this, '_weekdaysShortRegex')) { + this._weekdaysShortRegex = defaultWeekdaysShortRegex; + } + return this._weekdaysShortStrictRegex && isStrict + ? this._weekdaysShortStrictRegex + : this._weekdaysShortRegex; + } + } + + function weekdaysMinRegex(isStrict) { + if (this._weekdaysParseExact) { + if (!hasOwnProp(this, '_weekdaysRegex')) { + computeWeekdaysParse.call(this); + } + if (isStrict) { + return this._weekdaysMinStrictRegex; + } else { + return this._weekdaysMinRegex; + } + } else { + if (!hasOwnProp(this, '_weekdaysMinRegex')) { + this._weekdaysMinRegex = defaultWeekdaysMinRegex; + } + return this._weekdaysMinStrictRegex && isStrict + ? this._weekdaysMinStrictRegex + : this._weekdaysMinRegex; + } + } + + function computeWeekdaysParse() { + function cmpLenRev(a, b) { + return b.length - a.length; + } + + var minPieces = [], + shortPieces = [], + longPieces = [], + mixedPieces = [], + i, + mom, + minp, + shortp, + longp; + for (i = 0; i < 7; i++) { + // make the regex if we don't have it already + mom = createUTC([2000, 1]).day(i); + minp = regexEscape(this.weekdaysMin(mom, '')); + shortp = regexEscape(this.weekdaysShort(mom, '')); + longp = regexEscape(this.weekdays(mom, '')); + minPieces.push(minp); + shortPieces.push(shortp); + longPieces.push(longp); + mixedPieces.push(minp); + mixedPieces.push(shortp); + mixedPieces.push(longp); + } + // Sorting makes sure if one weekday (or abbr) is a prefix of another it + // will match the longer piece. + minPieces.sort(cmpLenRev); + shortPieces.sort(cmpLenRev); + longPieces.sort(cmpLenRev); + mixedPieces.sort(cmpLenRev); + + this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); + this._weekdaysShortRegex = this._weekdaysRegex; + this._weekdaysMinRegex = this._weekdaysRegex; + + this._weekdaysStrictRegex = new RegExp( + '^(' + longPieces.join('|') + ')', + 'i' + ); + this._weekdaysShortStrictRegex = new RegExp( + '^(' + shortPieces.join('|') + ')', + 'i' + ); + this._weekdaysMinStrictRegex = new RegExp( + '^(' + minPieces.join('|') + ')', + 'i' + ); + } + + // FORMATTING + + function hFormat() { + return this.hours() % 12 || 12; + } + + function kFormat() { + return this.hours() || 24; + } + + addFormatToken('H', ['HH', 2], 0, 'hour'); + addFormatToken('h', ['hh', 2], 0, hFormat); + addFormatToken('k', ['kk', 2], 0, kFormat); + + addFormatToken('hmm', 0, 0, function () { + return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2); + }); + + addFormatToken('hmmss', 0, 0, function () { + return ( + '' + + hFormat.apply(this) + + zeroFill(this.minutes(), 2) + + zeroFill(this.seconds(), 2) + ); + }); + + addFormatToken('Hmm', 0, 0, function () { + return '' + this.hours() + zeroFill(this.minutes(), 2); + }); + + addFormatToken('Hmmss', 0, 0, function () { + return ( + '' + + this.hours() + + zeroFill(this.minutes(), 2) + + zeroFill(this.seconds(), 2) + ); + }); + + function meridiem(token, lowercase) { + addFormatToken(token, 0, 0, function () { + return this.localeData().meridiem( + this.hours(), + this.minutes(), + lowercase + ); + }); + } + + meridiem('a', true); + meridiem('A', false); + + // ALIASES + + addUnitAlias('hour', 'h'); + + // PRIORITY + addUnitPriority('hour', 13); + + // PARSING + + function matchMeridiem(isStrict, locale) { + return locale._meridiemParse; + } + + addRegexToken('a', matchMeridiem); + addRegexToken('A', matchMeridiem); + addRegexToken('H', match1to2); + addRegexToken('h', match1to2); + addRegexToken('k', match1to2); + addRegexToken('HH', match1to2, match2); + addRegexToken('hh', match1to2, match2); + addRegexToken('kk', match1to2, match2); + + addRegexToken('hmm', match3to4); + addRegexToken('hmmss', match5to6); + addRegexToken('Hmm', match3to4); + addRegexToken('Hmmss', match5to6); + + addParseToken(['H', 'HH'], HOUR); + addParseToken(['k', 'kk'], function (input, array, config) { + var kInput = toInt(input); + array[HOUR] = kInput === 24 ? 0 : kInput; + }); + addParseToken(['a', 'A'], function (input, array, config) { + config._isPm = config._locale.isPM(input); + config._meridiem = input; + }); + addParseToken(['h', 'hh'], function (input, array, config) { + array[HOUR] = toInt(input); + getParsingFlags(config).bigHour = true; + }); + addParseToken('hmm', function (input, array, config) { + var pos = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos)); + array[MINUTE] = toInt(input.substr(pos)); + getParsingFlags(config).bigHour = true; + }); + addParseToken('hmmss', function (input, array, config) { + var pos1 = input.length - 4, + pos2 = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos1)); + array[MINUTE] = toInt(input.substr(pos1, 2)); + array[SECOND] = toInt(input.substr(pos2)); + getParsingFlags(config).bigHour = true; + }); + addParseToken('Hmm', function (input, array, config) { + var pos = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos)); + array[MINUTE] = toInt(input.substr(pos)); + }); + addParseToken('Hmmss', function (input, array, config) { + var pos1 = input.length - 4, + pos2 = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos1)); + array[MINUTE] = toInt(input.substr(pos1, 2)); + array[SECOND] = toInt(input.substr(pos2)); + }); + + // LOCALES + + function localeIsPM(input) { + // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays + // Using charAt should be more compatible. + return (input + '').toLowerCase().charAt(0) === 'p'; + } + + var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i, + // Setting the hour should keep the time, because the user explicitly + // specified which hour they want. So trying to maintain the same hour (in + // a new timezone) makes sense. Adding/subtracting hours does not follow + // this rule. + getSetHour = makeGetSet('Hours', true); + + function localeMeridiem(hours, minutes, isLower) { + if (hours > 11) { + return isLower ? 'pm' : 'PM'; + } else { + return isLower ? 'am' : 'AM'; + } + } + + var baseConfig = { + calendar: defaultCalendar, + longDateFormat: defaultLongDateFormat, + invalidDate: defaultInvalidDate, + ordinal: defaultOrdinal, + dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse, + relativeTime: defaultRelativeTime, + + months: defaultLocaleMonths, + monthsShort: defaultLocaleMonthsShort, + + week: defaultLocaleWeek, + + weekdays: defaultLocaleWeekdays, + weekdaysMin: defaultLocaleWeekdaysMin, + weekdaysShort: defaultLocaleWeekdaysShort, + + meridiemParse: defaultLocaleMeridiemParse, + }; + + // internal storage for locale config files + var locales = {}, + localeFamilies = {}, + globalLocale; + + function commonPrefix(arr1, arr2) { + var i, + minl = Math.min(arr1.length, arr2.length); + for (i = 0; i < minl; i += 1) { + if (arr1[i] !== arr2[i]) { + return i; + } + } + return minl; + } + + function normalizeLocale(key) { + return key ? key.toLowerCase().replace('_', '-') : key; + } + + // pick the locale from the array + // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each + // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root + function chooseLocale(names) { + var i = 0, + j, + next, + locale, + split; + + while (i < names.length) { + split = normalizeLocale(names[i]).split('-'); + j = split.length; + next = normalizeLocale(names[i + 1]); + next = next ? next.split('-') : null; + while (j > 0) { + locale = loadLocale(split.slice(0, j).join('-')); + if (locale) { + return locale; + } + if ( + next && + next.length >= j && + commonPrefix(split, next) >= j - 1 + ) { + //the next array item is better than a shallower substring of this one + break; + } + j--; + } + i++; + } + return globalLocale; + } + + function isLocaleNameSane(name) { + // Prevent names that look like filesystem paths, i.e contain '/' or '\' + return name.match('^[^/\\\\]*$') != null; + } + + function loadLocale(name) { + var oldLocale = null, + aliasedRequire; + // TODO: Find a better way to register and load all the locales in Node + if ( + locales[name] === undefined && + 'object' !== 'undefined' && + module && + module.exports && + isLocaleNameSane(name) + ) { + try { + oldLocale = globalLocale._abbr; + aliasedRequire = commonjsRequire; + aliasedRequire('./locale/' + name); + getSetGlobalLocale(oldLocale); + } catch (e) { + // mark as not found to avoid repeating expensive file require call causing high CPU + // when trying to find en-US, en_US, en-us for every format call + locales[name] = null; // null means not found + } + } + return locales[name]; + } + + // This function will load locale and then set the global locale. If + // no arguments are passed in, it will simply return the current global + // locale key. + function getSetGlobalLocale(key, values) { + var data; + if (key) { + if (isUndefined(values)) { + data = getLocale(key); + } else { + data = defineLocale(key, values); + } + + if (data) { + // moment.duration._locale = moment._locale = data; + globalLocale = data; + } else { + if (typeof console !== 'undefined' && console.warn) { + //warn user if arguments are passed but the locale could not be set + console.warn( + 'Locale ' + key + ' not found. Did you forget to load it?' + ); + } + } + } + + return globalLocale._abbr; + } + + function defineLocale(name, config) { + if (config !== null) { + var locale, + parentConfig = baseConfig; + config.abbr = name; + if (locales[name] != null) { + 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.' + ); + parentConfig = locales[name]._config; + } else if (config.parentLocale != null) { + if (locales[config.parentLocale] != null) { + parentConfig = locales[config.parentLocale]._config; + } else { + locale = loadLocale(config.parentLocale); + if (locale != null) { + parentConfig = locale._config; + } else { + if (!localeFamilies[config.parentLocale]) { + localeFamilies[config.parentLocale] = []; + } + localeFamilies[config.parentLocale].push({ + name: name, + config: config, + }); + return null; + } + } + } + locales[name] = new Locale(mergeConfigs(parentConfig, config)); + + if (localeFamilies[name]) { + localeFamilies[name].forEach(function (x) { + defineLocale(x.name, x.config); + }); + } + + // backwards compat for now: also set the locale + // make sure we set the locale AFTER all child locales have been + // created, so we won't end up with the child locale set. + getSetGlobalLocale(name); + + return locales[name]; + } else { + // useful for testing + delete locales[name]; + return null; + } + } + + function updateLocale(name, config) { + if (config != null) { + var locale, + tmpLocale, + parentConfig = baseConfig; + + if (locales[name] != null && locales[name].parentLocale != null) { + // Update existing child locale in-place to avoid memory-leaks + locales[name].set(mergeConfigs(locales[name]._config, config)); + } else { + // MERGE + tmpLocale = loadLocale(name); + if (tmpLocale != null) { + parentConfig = tmpLocale._config; + } + config = mergeConfigs(parentConfig, config); + if (tmpLocale == null) { + // updateLocale is called for creating a new locale + // Set abbr so it will have a name (getters return + // undefined otherwise). + config.abbr = name; + } + locale = new Locale(config); + locale.parentLocale = locales[name]; + locales[name] = locale; + } + + // backwards compat for now: also set the locale + getSetGlobalLocale(name); + } else { + // pass null for config to unupdate, useful for tests + if (locales[name] != null) { + if (locales[name].parentLocale != null) { + locales[name] = locales[name].parentLocale; + if (name === getSetGlobalLocale()) { + getSetGlobalLocale(name); + } + } else if (locales[name] != null) { + delete locales[name]; + } + } + } + return locales[name]; + } + + // returns locale data + function getLocale(key) { + var locale; + + if (key && key._locale && key._locale._abbr) { + key = key._locale._abbr; + } + + if (!key) { + return globalLocale; + } + + if (!isArray(key)) { + //short-circuit everything else + locale = loadLocale(key); + if (locale) { + return locale; + } + key = [key]; + } + + return chooseLocale(key); + } + + function listLocales() { + return keys(locales); + } + + function checkOverflow(m) { + var overflow, + a = m._a; + + if (a && getParsingFlags(m).overflow === -2) { + 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; + + if ( + getParsingFlags(m)._overflowDayOfYear && + (overflow < YEAR || overflow > DATE) + ) { + overflow = DATE; + } + if (getParsingFlags(m)._overflowWeeks && overflow === -1) { + overflow = WEEK; + } + if (getParsingFlags(m)._overflowWeekday && overflow === -1) { + overflow = WEEKDAY; + } + + getParsingFlags(m).overflow = overflow; + } + + return m; + } + + // iso 8601 regex + // 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) + 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)?)?$/, + 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)?)?$/, + tzRegex = /Z|[+-]\d\d(?::?\d\d)?/, + 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}/], + ['GGGG[W]WWE', /\d{4}W\d{3}/], + ['GGGG[W]WW', /\d{4}W\d{2}/, false], + ['YYYYDDD', /\d{7}/], + ['YYYYMM', /\d{6}/, false], + ['YYYY', /\d{4}/, false], + ], + // iso time formats and regexes + 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/], + ], + aspNetJsonRegex = /^\/?Date\((-?\d+)/i, + // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3 + 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}))$/, + obsOffsets = { + UT: 0, + GMT: 0, + EDT: -4 * 60, + EST: -5 * 60, + CDT: -5 * 60, + CST: -6 * 60, + MDT: -6 * 60, + MST: -7 * 60, + PDT: -7 * 60, + PST: -8 * 60, + }; + + // date from iso format + function configFromISO(config) { + var i, + l, + string = config._i, + match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string), + allowTime, + dateFormat, + timeFormat, + tzFormat, + isoDatesLen = isoDates.length, + isoTimesLen = isoTimes.length; + + if (match) { + getParsingFlags(config).iso = true; + for (i = 0, l = isoDatesLen; i < l; i++) { + if (isoDates[i][1].exec(match[1])) { + dateFormat = isoDates[i][0]; + allowTime = isoDates[i][2] !== false; + break; + } + } + if (dateFormat == null) { + config._isValid = false; + return; + } + if (match[3]) { + for (i = 0, l = isoTimesLen; i < l; i++) { + if (isoTimes[i][1].exec(match[3])) { + // match[2] should be 'T' or space + timeFormat = (match[2] || ' ') + isoTimes[i][0]; + break; + } + } + if (timeFormat == null) { + config._isValid = false; + return; + } + } + if (!allowTime && timeFormat != null) { + config._isValid = false; + return; + } + if (match[4]) { + if (tzRegex.exec(match[4])) { + tzFormat = 'Z'; + } else { + config._isValid = false; + return; + } + } + config._f = dateFormat + (timeFormat || '') + (tzFormat || ''); + configFromStringAndFormat(config); + } else { + config._isValid = false; + } + } + + function extractFromRFC2822Strings( + yearStr, + monthStr, + dayStr, + hourStr, + minuteStr, + secondStr + ) { + var result = [ + untruncateYear(yearStr), + defaultLocaleMonthsShort.indexOf(monthStr), + parseInt(dayStr, 10), + parseInt(hourStr, 10), + parseInt(minuteStr, 10), + ]; + + if (secondStr) { + result.push(parseInt(secondStr, 10)); + } + + return result; + } + + function untruncateYear(yearStr) { + var year = parseInt(yearStr, 10); + if (year <= 49) { + return 2000 + year; + } else if (year <= 999) { + return 1900 + year; + } + return year; + } + + function preprocessRFC2822(s) { + // Remove comments and folding whitespace and replace multiple-spaces with a single space + return s + .replace(/\([^()]*\)|[\n\t]/g, ' ') + .replace(/(\s\s+)/g, ' ') + .replace(/^\s\s*/, '') + .replace(/\s\s*$/, ''); + } + + function checkWeekday(weekdayStr, parsedInput, config) { + if (weekdayStr) { + // TODO: Replace the vanilla JS Date object with an independent day-of-week check. + var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr), + weekdayActual = new Date( + parsedInput[0], + parsedInput[1], + parsedInput[2] + ).getDay(); + if (weekdayProvided !== weekdayActual) { + getParsingFlags(config).weekdayMismatch = true; + config._isValid = false; + return false; + } + } + return true; + } + + function calculateOffset(obsOffset, militaryOffset, numOffset) { + if (obsOffset) { + return obsOffsets[obsOffset]; + } else if (militaryOffset) { + // the only allowed military tz is Z + return 0; + } else { + var hm = parseInt(numOffset, 10), + m = hm % 100, + h = (hm - m) / 100; + return h * 60 + m; + } + } + + // date and time from ref 2822 format + function configFromRFC2822(config) { + var match = rfc2822.exec(preprocessRFC2822(config._i)), + parsedArray; + if (match) { + parsedArray = extractFromRFC2822Strings( + match[4], + match[3], + match[2], + match[5], + match[6], + match[7] + ); + if (!checkWeekday(match[1], parsedArray, config)) { + return; + } + + config._a = parsedArray; + config._tzm = calculateOffset(match[8], match[9], match[10]); + + config._d = createUTCDate.apply(null, config._a); + config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); + + getParsingFlags(config).rfc2822 = true; + } else { + config._isValid = false; + } + } + + // date from 1) ASP.NET, 2) ISO, 3) RFC 2822 formats, or 4) optional fallback if parsing isn't strict + function configFromString(config) { + var matched = aspNetJsonRegex.exec(config._i); + if (matched !== null) { + config._d = new Date(+matched[1]); + return; + } + + configFromISO(config); + if (config._isValid === false) { + delete config._isValid; + } else { + return; + } + + configFromRFC2822(config); + if (config._isValid === false) { + delete config._isValid; + } else { + return; + } + + if (config._strict) { + config._isValid = false; + } else { + // Final attempt, use Input Fallback + hooks.createFromInputFallback(config); + } + } + + 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. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.', + function (config) { + config._d = new Date(config._i + (config._useUTC ? ' UTC' : '')); + } + ); + + // Pick the first defined of two or three arguments. + function defaults(a, b, c) { + if (a != null) { + return a; + } + if (b != null) { + return b; + } + return c; + } + + function currentDateArray(config) { + // hooks is actually the exported moment object + var nowValue = new Date(hooks.now()); + if (config._useUTC) { + return [ + nowValue.getUTCFullYear(), + nowValue.getUTCMonth(), + nowValue.getUTCDate(), + ]; + } + return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()]; + } + + // convert an array to a date. + // the array should mirror the parameters below + // note: all values past the year are optional and will default to the lowest possible value. + // [year, month, day , hour, minute, second, millisecond] + function configFromArray(config) { + var i, + date, + input = [], + currentDate, + expectedWeekday, + yearToUse; + + if (config._d) { + return; + } + + currentDate = currentDateArray(config); + + //compute day of the year from weeks and weekdays + if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { + dayOfYearFromWeekInfo(config); + } + + //if the day of the year is set, figure out what it is + if (config._dayOfYear != null) { + yearToUse = defaults(config._a[YEAR], currentDate[YEAR]); + + if ( + config._dayOfYear > daysInYear(yearToUse) || + config._dayOfYear === 0 + ) { + getParsingFlags(config)._overflowDayOfYear = true; + } + + date = createUTCDate(yearToUse, 0, config._dayOfYear); + config._a[MONTH] = date.getUTCMonth(); + config._a[DATE] = date.getUTCDate(); + } + + // Default to current date. + // * if no year, month, day of month are given, default to today + // * if day of month is given, default month and year + // * if month is given, default only year + // * if year is given, don't default anything + for (i = 0; i < 3 && config._a[i] == null; ++i) { + config._a[i] = input[i] = currentDate[i]; + } + + // Zero out whatever was not defaulted, including time + for (; i < 7; i++) { + config._a[i] = input[i] = + config._a[i] == null ? (i === 2 ? 1 : 0) : config._a[i]; + } + + // Check for 24:00:00.000 + if ( + config._a[HOUR] === 24 && + config._a[MINUTE] === 0 && + config._a[SECOND] === 0 && + config._a[MILLISECOND] === 0 + ) { + config._nextDay = true; + config._a[HOUR] = 0; + } + + config._d = (config._useUTC ? createUTCDate : createDate).apply( + null, + input + ); + expectedWeekday = config._useUTC + ? config._d.getUTCDay() + : config._d.getDay(); + + // Apply timezone offset from input. The actual utcOffset can be changed + // with parseZone. + if (config._tzm != null) { + config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); + } + + if (config._nextDay) { + config._a[HOUR] = 24; + } + + // check for mismatching day of week + if ( + config._w && + typeof config._w.d !== 'undefined' && + config._w.d !== expectedWeekday + ) { + getParsingFlags(config).weekdayMismatch = true; + } + } + + function dayOfYearFromWeekInfo(config) { + var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow, curWeek; + + w = config._w; + if (w.GG != null || w.W != null || w.E != null) { + dow = 1; + doy = 4; + + // TODO: We need to take the current isoWeekYear, but that depends on + // how we interpret now (local, utc, fixed offset). So create + // a now version of current config (take local/utc/offset flags, and + // create now). + weekYear = defaults( + w.GG, + config._a[YEAR], + weekOfYear(createLocal(), 1, 4).year + ); + week = defaults(w.W, 1); + weekday = defaults(w.E, 1); + if (weekday < 1 || weekday > 7) { + weekdayOverflow = true; + } + } else { + dow = config._locale._week.dow; + doy = config._locale._week.doy; + + curWeek = weekOfYear(createLocal(), dow, doy); + + weekYear = defaults(w.gg, config._a[YEAR], curWeek.year); + + // Default to current week. + week = defaults(w.w, curWeek.week); + + if (w.d != null) { + // weekday -- low day numbers are considered next week + weekday = w.d; + if (weekday < 0 || weekday > 6) { + weekdayOverflow = true; + } + } else if (w.e != null) { + // local weekday -- counting starts from beginning of week + weekday = w.e + dow; + if (w.e < 0 || w.e > 6) { + weekdayOverflow = true; + } + } else { + // default to beginning of week + weekday = dow; + } + } + if (week < 1 || week > weeksInYear(weekYear, dow, doy)) { + getParsingFlags(config)._overflowWeeks = true; + } else if (weekdayOverflow != null) { + getParsingFlags(config)._overflowWeekday = true; + } else { + temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy); + config._a[YEAR] = temp.year; + config._dayOfYear = temp.dayOfYear; + } + } + + // constant that refers to the ISO standard + hooks.ISO_8601 = function () {}; + + // constant that refers to the RFC 2822 form + hooks.RFC_2822 = function () {}; + + // date from string and format string + function configFromStringAndFormat(config) { + // TODO: Move this to another part of the creation flow to prevent circular deps + if (config._f === hooks.ISO_8601) { + configFromISO(config); + return; + } + if (config._f === hooks.RFC_2822) { + configFromRFC2822(config); + return; + } + config._a = []; + getParsingFlags(config).empty = true; + + // This array is used to make a Date, either with `new Date` or `Date.UTC` + var string = '' + config._i, + i, + parsedInput, + tokens, + token, + skipped, + stringLength = string.length, + totalParsedInputLength = 0, + era, + tokenLen; + + tokens = + expandFormat(config._f, config._locale).match(formattingTokens) || []; + tokenLen = tokens.length; + for (i = 0; i < tokenLen; i++) { + token = tokens[i]; + parsedInput = (string.match(getParseRegexForToken(token, config)) || + [])[0]; + if (parsedInput) { + skipped = string.substr(0, string.indexOf(parsedInput)); + if (skipped.length > 0) { + getParsingFlags(config).unusedInput.push(skipped); + } + string = string.slice( + string.indexOf(parsedInput) + parsedInput.length + ); + totalParsedInputLength += parsedInput.length; + } + // don't parse if it's not a known token + if (formatTokenFunctions[token]) { + if (parsedInput) { + getParsingFlags(config).empty = false; + } else { + getParsingFlags(config).unusedTokens.push(token); + } + addTimeToArrayFromToken(token, parsedInput, config); + } else if (config._strict && !parsedInput) { + getParsingFlags(config).unusedTokens.push(token); + } + } + + // add remaining unparsed input length to the string + getParsingFlags(config).charsLeftOver = + stringLength - totalParsedInputLength; + if (string.length > 0) { + getParsingFlags(config).unusedInput.push(string); + } + + // clear _12h flag if hour is <= 12 + if ( + config._a[HOUR] <= 12 && + getParsingFlags(config).bigHour === true && + config._a[HOUR] > 0 + ) { + getParsingFlags(config).bigHour = undefined; + } + + getParsingFlags(config).parsedDateParts = config._a.slice(0); + getParsingFlags(config).meridiem = config._meridiem; + // handle meridiem + config._a[HOUR] = meridiemFixWrap( + config._locale, + config._a[HOUR], + config._meridiem + ); + + // handle era + era = getParsingFlags(config).era; + if (era !== null) { + config._a[YEAR] = config._locale.erasConvertYear(era, config._a[YEAR]); + } + + configFromArray(config); + checkOverflow(config); + } + + function meridiemFixWrap(locale, hour, meridiem) { + var isPm; + + if (meridiem == null) { + // nothing to do + return hour; + } + if (locale.meridiemHour != null) { + return locale.meridiemHour(hour, meridiem); + } else if (locale.isPM != null) { + // Fallback + isPm = locale.isPM(meridiem); + if (isPm && hour < 12) { + hour += 12; + } + if (!isPm && hour === 12) { + hour = 0; + } + return hour; + } else { + // this is not supposed to happen + return hour; + } + } + + // date from string and array of format strings + function configFromStringAndArray(config) { + var tempConfig, + bestMoment, + scoreToBeat, + i, + currentScore, + validFormatFound, + bestFormatIsValid = false, + configfLen = config._f.length; + + if (configfLen === 0) { + getParsingFlags(config).invalidFormat = true; + config._d = new Date(NaN); + return; + } + + for (i = 0; i < configfLen; i++) { + currentScore = 0; + validFormatFound = false; + tempConfig = copyConfig({}, config); + if (config._useUTC != null) { + tempConfig._useUTC = config._useUTC; + } + tempConfig._f = config._f[i]; + configFromStringAndFormat(tempConfig); + + if (isValid(tempConfig)) { + validFormatFound = true; + } + + // if there is any input that was not parsed add a penalty for that format + currentScore += getParsingFlags(tempConfig).charsLeftOver; + + //or tokens + currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10; + + getParsingFlags(tempConfig).score = currentScore; + + if (!bestFormatIsValid) { + if ( + scoreToBeat == null || + currentScore < scoreToBeat || + validFormatFound + ) { + scoreToBeat = currentScore; + bestMoment = tempConfig; + if (validFormatFound) { + bestFormatIsValid = true; + } + } + } else { + if (currentScore < scoreToBeat) { + scoreToBeat = currentScore; + bestMoment = tempConfig; + } + } + } + + extend(config, bestMoment || tempConfig); + } + + function configFromObject(config) { + if (config._d) { + return; + } + + var i = normalizeObjectUnits(config._i), + dayOrDate = i.day === undefined ? i.date : i.day; + config._a = map( + [i.year, i.month, dayOrDate, i.hour, i.minute, i.second, i.millisecond], + function (obj) { + return obj && parseInt(obj, 10); + } + ); + + configFromArray(config); + } + + function createFromConfig(config) { + var res = new Moment(checkOverflow(prepareConfig(config))); + if (res._nextDay) { + // Adding is smart enough around DST + res.add(1, 'd'); + res._nextDay = undefined; + } + + return res; + } + + function prepareConfig(config) { + var input = config._i, + format = config._f; + + config._locale = config._locale || getLocale(config._l); + + if (input === null || (format === undefined && input === '')) { + return createInvalid({ nullInput: true }); + } + + if (typeof input === 'string') { + config._i = input = config._locale.preparse(input); + } + + if (isMoment(input)) { + return new Moment(checkOverflow(input)); + } else if (isDate(input)) { + config._d = input; + } else if (isArray(format)) { + configFromStringAndArray(config); + } else if (format) { + configFromStringAndFormat(config); + } else { + configFromInput(config); + } + + if (!isValid(config)) { + config._d = null; + } + + return config; + } + + function configFromInput(config) { + var input = config._i; + if (isUndefined(input)) { + config._d = new Date(hooks.now()); + } else if (isDate(input)) { + config._d = new Date(input.valueOf()); + } else if (typeof input === 'string') { + configFromString(config); + } else if (isArray(input)) { + config._a = map(input.slice(0), function (obj) { + return parseInt(obj, 10); + }); + configFromArray(config); + } else if (isObject(input)) { + configFromObject(config); + } else if (isNumber(input)) { + // from milliseconds + config._d = new Date(input); + } else { + hooks.createFromInputFallback(config); + } + } + + function createLocalOrUTC(input, format, locale, strict, isUTC) { + var c = {}; + + if (format === true || format === false) { + strict = format; + format = undefined; + } + + if (locale === true || locale === false) { + strict = locale; + locale = undefined; + } + + if ( + (isObject(input) && isObjectEmpty(input)) || + (isArray(input) && input.length === 0) + ) { + input = undefined; + } + // object construction must be done this way. + // https://github.com/moment/moment/issues/1423 + c._isAMomentObject = true; + c._useUTC = c._isUTC = isUTC; + c._l = locale; + c._i = input; + c._f = format; + c._strict = strict; + + return createFromConfig(c); + } + + function createLocal(input, format, locale, strict) { + return createLocalOrUTC(input, format, locale, strict, false); + } + + var prototypeMin = deprecate( + 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/', + function () { + var other = createLocal.apply(null, arguments); + if (this.isValid() && other.isValid()) { + return other < this ? this : other; + } else { + return createInvalid(); + } + } + ), + prototypeMax = deprecate( + 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/', + function () { + var other = createLocal.apply(null, arguments); + if (this.isValid() && other.isValid()) { + return other > this ? this : other; + } else { + return createInvalid(); + } + } + ); + + // Pick a moment m from moments so that m[fn](other) is true for all + // other. This relies on the function fn to be transitive. + // + // moments should either be an array of moment objects or an array, whose + // first element is an array of moment objects. + function pickBy(fn, moments) { + var res, i; + if (moments.length === 1 && isArray(moments[0])) { + moments = moments[0]; + } + if (!moments.length) { + return createLocal(); + } + res = moments[0]; + for (i = 1; i < moments.length; ++i) { + if (!moments[i].isValid() || moments[i][fn](res)) { + res = moments[i]; + } + } + return res; + } + + // TODO: Use [].sort instead? + function min() { + var args = [].slice.call(arguments, 0); + + return pickBy('isBefore', args); + } + + function max() { + var args = [].slice.call(arguments, 0); + + return pickBy('isAfter', args); + } + + var now = function () { + return Date.now ? Date.now() : +new Date(); + }; + + var ordering = [ + 'year', + 'quarter', + 'month', + 'week', + 'day', + 'hour', + 'minute', + 'second', + 'millisecond', + ]; + + function isDurationValid(m) { + var key, + unitHasDecimal = false, + i, + orderLen = ordering.length; + for (key in m) { + if ( + hasOwnProp(m, key) && + !( + indexOf.call(ordering, key) !== -1 && + (m[key] == null || !isNaN(m[key])) + ) + ) { + return false; + } + } + + for (i = 0; i < orderLen; ++i) { + if (m[ordering[i]]) { + if (unitHasDecimal) { + return false; // only allow non-integers for smallest unit + } + if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) { + unitHasDecimal = true; + } + } + } + + return true; + } + + function isValid$1() { + return this._isValid; + } + + function createInvalid$1() { + return createDuration(NaN); + } + + function Duration(duration) { + var normalizedInput = normalizeObjectUnits(duration), + years = normalizedInput.year || 0, + quarters = normalizedInput.quarter || 0, + months = normalizedInput.month || 0, + weeks = normalizedInput.week || normalizedInput.isoWeek || 0, + days = normalizedInput.day || 0, + hours = normalizedInput.hour || 0, + minutes = normalizedInput.minute || 0, + seconds = normalizedInput.second || 0, + milliseconds = normalizedInput.millisecond || 0; + + this._isValid = isDurationValid(normalizedInput); + + // representation for dateAddRemove + this._milliseconds = + +milliseconds + + seconds * 1e3 + // 1000 + minutes * 6e4 + // 1000 * 60 + hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978 + // Because of dateAddRemove treats 24 hours as different from a + // day when working around DST, we need to store them separately + this._days = +days + weeks * 7; + // It is impossible to translate months into days without knowing + // which months you are are talking about, so we have to store + // it separately. + this._months = +months + quarters * 3 + years * 12; + + this._data = {}; + + this._locale = getLocale(); + + this._bubble(); + } + + function isDuration(obj) { + return obj instanceof Duration; + } + + function absRound(number) { + if (number < 0) { + return Math.round(-1 * number) * -1; + } else { + return Math.round(number); + } + } + + // compare two arrays, return the number of differences + function compareArrays(array1, array2, dontConvert) { + var len = Math.min(array1.length, array2.length), + lengthDiff = Math.abs(array1.length - array2.length), + diffs = 0, + i; + for (i = 0; i < len; i++) { + if ( + (dontConvert && array1[i] !== array2[i]) || + (!dontConvert && toInt(array1[i]) !== toInt(array2[i])) + ) { + diffs++; + } + } + return diffs + lengthDiff; + } + + // FORMATTING + + function offset(token, separator) { + addFormatToken(token, 0, 0, function () { + var offset = this.utcOffset(), + sign = '+'; + if (offset < 0) { + offset = -offset; + sign = '-'; + } + return ( + sign + + zeroFill(~~(offset / 60), 2) + + separator + + zeroFill(~~offset % 60, 2) + ); + }); + } + + offset('Z', ':'); + offset('ZZ', ''); + + // PARSING + + addRegexToken('Z', matchShortOffset); + addRegexToken('ZZ', matchShortOffset); + addParseToken(['Z', 'ZZ'], function (input, array, config) { + config._useUTC = true; + config._tzm = offsetFromString(matchShortOffset, input); + }); + + // HELPERS + + // timezone chunker + // '+10:00' > ['10', '00'] + // '-1530' > ['-15', '30'] + var chunkOffset = /([\+\-]|\d\d)/gi; + + function offsetFromString(matcher, string) { + var matches = (string || '').match(matcher), + chunk, + parts, + minutes; + + if (matches === null) { + return null; + } + + chunk = matches[matches.length - 1] || []; + parts = (chunk + '').match(chunkOffset) || ['-', 0, 0]; + minutes = +(parts[1] * 60) + toInt(parts[2]); + + return minutes === 0 ? 0 : parts[0] === '+' ? minutes : -minutes; + } + + // Return a moment from input, that is local/utc/zone equivalent to model. + function cloneWithOffset(input, model) { + var res, diff; + if (model._isUTC) { + res = model.clone(); + diff = + (isMoment(input) || isDate(input) + ? input.valueOf() + : createLocal(input).valueOf()) - res.valueOf(); + // Use low-level api, because this fn is low-level api. + res._d.setTime(res._d.valueOf() + diff); + hooks.updateOffset(res, false); + return res; + } else { + return createLocal(input).local(); + } + } + + function getDateOffset(m) { + // On Firefox.24 Date#getTimezoneOffset returns a floating point. + // https://github.com/moment/moment/pull/1871 + return -Math.round(m._d.getTimezoneOffset()); + } + + // HOOKS + + // This function will be called whenever a moment is mutated. + // It is intended to keep the offset in sync with the timezone. + hooks.updateOffset = function () {}; + + // MOMENTS + + // keepLocalTime = true means only change the timezone, without + // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]--> + // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset + // +0200, so we adjust the time as needed, to be valid. + // + // Keeping the time actually adds/subtracts (one hour) + // from the actual represented time. That is why we call updateOffset + // a second time. In case it wants us to change the offset again + // _changeInProgress == true case, then we have to adjust, because + // there is no such time in the given timezone. + function getSetOffset(input, keepLocalTime, keepMinutes) { + var offset = this._offset || 0, + localAdjust; + if (!this.isValid()) { + return input != null ? this : NaN; + } + if (input != null) { + if (typeof input === 'string') { + input = offsetFromString(matchShortOffset, input); + if (input === null) { + return this; + } + } else if (Math.abs(input) < 16 && !keepMinutes) { + input = input * 60; + } + if (!this._isUTC && keepLocalTime) { + localAdjust = getDateOffset(this); + } + this._offset = input; + this._isUTC = true; + if (localAdjust != null) { + this.add(localAdjust, 'm'); + } + if (offset !== input) { + if (!keepLocalTime || this._changeInProgress) { + addSubtract( + this, + createDuration(input - offset, 'm'), + 1, + false + ); + } else if (!this._changeInProgress) { + this._changeInProgress = true; + hooks.updateOffset(this, true); + this._changeInProgress = null; + } + } + return this; + } else { + return this._isUTC ? offset : getDateOffset(this); + } + } + + function getSetZone(input, keepLocalTime) { + if (input != null) { + if (typeof input !== 'string') { + input = -input; + } + + this.utcOffset(input, keepLocalTime); + + return this; + } else { + return -this.utcOffset(); + } + } + + function setOffsetToUTC(keepLocalTime) { + return this.utcOffset(0, keepLocalTime); + } + + function setOffsetToLocal(keepLocalTime) { + if (this._isUTC) { + this.utcOffset(0, keepLocalTime); + this._isUTC = false; + + if (keepLocalTime) { + this.subtract(getDateOffset(this), 'm'); + } + } + return this; + } + + function setOffsetToParsedOffset() { + if (this._tzm != null) { + this.utcOffset(this._tzm, false, true); + } else if (typeof this._i === 'string') { + var tZone = offsetFromString(matchOffset, this._i); + if (tZone != null) { + this.utcOffset(tZone); + } else { + this.utcOffset(0, true); + } + } + return this; + } + + function hasAlignedHourOffset(input) { + if (!this.isValid()) { + return false; + } + input = input ? createLocal(input).utcOffset() : 0; + + return (this.utcOffset() - input) % 60 === 0; + } + + function isDaylightSavingTime() { + return ( + this.utcOffset() > this.clone().month(0).utcOffset() || + this.utcOffset() > this.clone().month(5).utcOffset() + ); + } + + function isDaylightSavingTimeShifted() { + if (!isUndefined(this._isDSTShifted)) { + return this._isDSTShifted; + } + + var c = {}, + other; + + copyConfig(c, this); + c = prepareConfig(c); + + if (c._a) { + other = c._isUTC ? createUTC(c._a) : createLocal(c._a); + this._isDSTShifted = + this.isValid() && compareArrays(c._a, other.toArray()) > 0; + } else { + this._isDSTShifted = false; + } + + return this._isDSTShifted; + } + + function isLocal() { + return this.isValid() ? !this._isUTC : false; + } + + function isUtcOffset() { + return this.isValid() ? this._isUTC : false; + } + + function isUtc() { + return this.isValid() ? this._isUTC && this._offset === 0 : false; + } + + // ASP.NET json date format regex + var aspNetRegex = /^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/, + // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html + // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere + // and further modified to allow for strings containing both week and day + isoRegex = + /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; + + function createDuration(input, key) { + var duration = input, + // matching against regexp is expensive, do it on demand + match = null, + sign, + ret, + diffRes; + + if (isDuration(input)) { + duration = { + ms: input._milliseconds, + d: input._days, + M: input._months, + }; + } else if (isNumber(input) || !isNaN(+input)) { + duration = {}; + if (key) { + duration[key] = +input; + } else { + duration.milliseconds = +input; + } + } else if ((match = aspNetRegex.exec(input))) { + sign = match[1] === '-' ? -1 : 1; + duration = { + y: 0, + d: toInt(match[DATE]) * sign, + h: toInt(match[HOUR]) * sign, + m: toInt(match[MINUTE]) * sign, + s: toInt(match[SECOND]) * sign, + ms: toInt(absRound(match[MILLISECOND] * 1000)) * sign, // the millisecond decimal point is included in the match + }; + } else if ((match = isoRegex.exec(input))) { + sign = match[1] === '-' ? -1 : 1; + duration = { + y: parseIso(match[2], sign), + M: parseIso(match[3], sign), + w: parseIso(match[4], sign), + d: parseIso(match[5], sign), + h: parseIso(match[6], sign), + m: parseIso(match[7], sign), + s: parseIso(match[8], sign), + }; + } else if (duration == null) { + // checks for null or undefined + duration = {}; + } else if ( + typeof duration === 'object' && + ('from' in duration || 'to' in duration) + ) { + diffRes = momentsDifference( + createLocal(duration.from), + createLocal(duration.to) + ); + + duration = {}; + duration.ms = diffRes.milliseconds; + duration.M = diffRes.months; + } + + ret = new Duration(duration); + + if (isDuration(input) && hasOwnProp(input, '_locale')) { + ret._locale = input._locale; + } + + if (isDuration(input) && hasOwnProp(input, '_isValid')) { + ret._isValid = input._isValid; + } + + return ret; + } + + createDuration.fn = Duration.prototype; + createDuration.invalid = createInvalid$1; + + function parseIso(inp, sign) { + // We'd normally use ~~inp for this, but unfortunately it also + // converts floats to ints. + // inp may be undefined, so careful calling replace on it. + var res = inp && parseFloat(inp.replace(',', '.')); + // apply sign while we're at it + return (isNaN(res) ? 0 : res) * sign; + } + + function positiveMomentsDifference(base, other) { + var res = {}; + + res.months = + other.month() - base.month() + (other.year() - base.year()) * 12; + if (base.clone().add(res.months, 'M').isAfter(other)) { + --res.months; + } + + res.milliseconds = +other - +base.clone().add(res.months, 'M'); + + return res; + } + + function momentsDifference(base, other) { + var res; + if (!(base.isValid() && other.isValid())) { + return { milliseconds: 0, months: 0 }; + } + + other = cloneWithOffset(other, base); + if (base.isBefore(other)) { + res = positiveMomentsDifference(base, other); + } else { + res = positiveMomentsDifference(other, base); + res.milliseconds = -res.milliseconds; + res.months = -res.months; + } + + return res; + } + + // TODO: remove 'name' arg after deprecation is removed + function createAdder(direction, name) { + return function (val, period) { + var dur, tmp; + //invert the arguments, but complain about it + if (period !== null && !isNaN(+period)) { + 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.' + ); + tmp = val; + val = period; + period = tmp; + } + + dur = createDuration(val, period); + addSubtract(this, dur, direction); + return this; + }; + } + + function addSubtract(mom, duration, isAdding, updateOffset) { + var milliseconds = duration._milliseconds, + days = absRound(duration._days), + months = absRound(duration._months); + + if (!mom.isValid()) { + // No op + return; + } + + updateOffset = updateOffset == null ? true : updateOffset; + + if (months) { + setMonth(mom, get(mom, 'Month') + months * isAdding); + } + if (days) { + set$1(mom, 'Date', get(mom, 'Date') + days * isAdding); + } + if (milliseconds) { + mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding); + } + if (updateOffset) { + hooks.updateOffset(mom, days || months); + } + } + + var add = createAdder(1, 'add'), + subtract = createAdder(-1, 'subtract'); + + function isString(input) { + return typeof input === 'string' || input instanceof String; + } + + // type MomentInput = Moment | Date | string | number | (number | string)[] | MomentInputObject | void; // null | undefined + function isMomentInput(input) { + return ( + isMoment(input) || + isDate(input) || + isString(input) || + isNumber(input) || + isNumberOrStringArray(input) || + isMomentInputObject(input) || + input === null || + input === undefined + ); + } + + function isMomentInputObject(input) { + var objectTest = isObject(input) && !isObjectEmpty(input), + propertyTest = false, + properties = [ + 'years', + 'year', + 'y', + 'months', + 'month', + 'M', + 'days', + 'day', + 'd', + 'dates', + 'date', + 'D', + 'hours', + 'hour', + 'h', + 'minutes', + 'minute', + 'm', + 'seconds', + 'second', + 's', + 'milliseconds', + 'millisecond', + 'ms', + ], + i, + property, + propertyLen = properties.length; + + for (i = 0; i < propertyLen; i += 1) { + property = properties[i]; + propertyTest = propertyTest || hasOwnProp(input, property); + } + + return objectTest && propertyTest; + } + + function isNumberOrStringArray(input) { + var arrayTest = isArray(input), + dataTypeTest = false; + if (arrayTest) { + dataTypeTest = + input.filter(function (item) { + return !isNumber(item) && isString(input); + }).length === 0; + } + return arrayTest && dataTypeTest; + } + + function isCalendarSpec(input) { + var objectTest = isObject(input) && !isObjectEmpty(input), + propertyTest = false, + properties = [ + 'sameDay', + 'nextDay', + 'lastDay', + 'nextWeek', + 'lastWeek', + 'sameElse', + ], + i, + property; + + for (i = 0; i < properties.length; i += 1) { + property = properties[i]; + propertyTest = propertyTest || hasOwnProp(input, property); + } + + return objectTest && propertyTest; + } + + function getCalendarFormat(myMoment, now) { + var diff = myMoment.diff(now, 'days', true); + return diff < -6 + ? 'sameElse' + : diff < -1 + ? 'lastWeek' + : diff < 0 + ? 'lastDay' + : diff < 1 + ? 'sameDay' + : diff < 2 + ? 'nextDay' + : diff < 7 + ? 'nextWeek' + : 'sameElse'; + } + + function calendar$1(time, formats) { + // Support for single parameter, formats only overload to the calendar function + if (arguments.length === 1) { + if (!arguments[0]) { + time = undefined; + formats = undefined; + } else if (isMomentInput(arguments[0])) { + time = arguments[0]; + formats = undefined; + } else if (isCalendarSpec(arguments[0])) { + formats = arguments[0]; + time = undefined; + } + } + // We want to compare the start of today, vs this. + // Getting start-of-today depends on whether we're local/utc/offset or not. + var now = time || createLocal(), + sod = cloneWithOffset(now, this).startOf('day'), + format = hooks.calendarFormat(this, sod) || 'sameElse', + output = + formats && + (isFunction(formats[format]) + ? formats[format].call(this, now) + : formats[format]); + + return this.format( + output || this.localeData().calendar(format, this, createLocal(now)) + ); + } + + function clone() { + return new Moment(this); + } + + function isAfter(input, units) { + var localInput = isMoment(input) ? input : createLocal(input); + if (!(this.isValid() && localInput.isValid())) { + return false; + } + units = normalizeUnits(units) || 'millisecond'; + if (units === 'millisecond') { + return this.valueOf() > localInput.valueOf(); + } else { + return localInput.valueOf() < this.clone().startOf(units).valueOf(); + } + } + + function isBefore(input, units) { + var localInput = isMoment(input) ? input : createLocal(input); + if (!(this.isValid() && localInput.isValid())) { + return false; + } + units = normalizeUnits(units) || 'millisecond'; + if (units === 'millisecond') { + return this.valueOf() < localInput.valueOf(); + } else { + return this.clone().endOf(units).valueOf() < localInput.valueOf(); + } + } + + function isBetween(from, to, units, inclusivity) { + var localFrom = isMoment(from) ? from : createLocal(from), + localTo = isMoment(to) ? to : createLocal(to); + if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) { + return false; + } + inclusivity = inclusivity || '()'; + return ( + (inclusivity[0] === '(' + ? this.isAfter(localFrom, units) + : !this.isBefore(localFrom, units)) && + (inclusivity[1] === ')' + ? this.isBefore(localTo, units) + : !this.isAfter(localTo, units)) + ); + } + + function isSame(input, units) { + var localInput = isMoment(input) ? input : createLocal(input), + inputMs; + if (!(this.isValid() && localInput.isValid())) { + return false; + } + units = normalizeUnits(units) || 'millisecond'; + if (units === 'millisecond') { + return this.valueOf() === localInput.valueOf(); + } else { + inputMs = localInput.valueOf(); + return ( + this.clone().startOf(units).valueOf() <= inputMs && + inputMs <= this.clone().endOf(units).valueOf() + ); + } + } + + function isSameOrAfter(input, units) { + return this.isSame(input, units) || this.isAfter(input, units); + } + + function isSameOrBefore(input, units) { + return this.isSame(input, units) || this.isBefore(input, units); + } + + function diff(input, units, asFloat) { + var that, zoneDelta, output; + + if (!this.isValid()) { + return NaN; + } + + that = cloneWithOffset(input, this); + + if (!that.isValid()) { + return NaN; + } + + zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4; + + units = normalizeUnits(units); + + switch (units) { + case 'year': + output = monthDiff(this, that) / 12; + break; + case 'month': + output = monthDiff(this, that); + break; + case 'quarter': + output = monthDiff(this, that) / 3; + break; + case 'second': + output = (this - that) / 1e3; + break; // 1000 + case 'minute': + output = (this - that) / 6e4; + break; // 1000 * 60 + case 'hour': + output = (this - that) / 36e5; + break; // 1000 * 60 * 60 + case 'day': + output = (this - that - zoneDelta) / 864e5; + break; // 1000 * 60 * 60 * 24, negate dst + case 'week': + output = (this - that - zoneDelta) / 6048e5; + break; // 1000 * 60 * 60 * 24 * 7, negate dst + default: + output = this - that; + } + + return asFloat ? output : absFloor(output); + } + + function monthDiff(a, b) { + if (a.date() < b.date()) { + // end-of-month calculations work correct when the start month has more + // days than the end month. + return -monthDiff(b, a); + } + // difference in months + var wholeMonthDiff = (b.year() - a.year()) * 12 + (b.month() - a.month()), + // b is in (anchor - 1 month, anchor + 1 month) + anchor = a.clone().add(wholeMonthDiff, 'months'), + anchor2, + adjust; + + if (b - anchor < 0) { + anchor2 = a.clone().add(wholeMonthDiff - 1, 'months'); + // linear across the month + adjust = (b - anchor) / (anchor - anchor2); + } else { + anchor2 = a.clone().add(wholeMonthDiff + 1, 'months'); + // linear across the month + adjust = (b - anchor) / (anchor2 - anchor); + } + + //check for negative zero, return zero if negative zero + return -(wholeMonthDiff + adjust) || 0; + } + + hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ'; + hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]'; + + function toString() { + return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); + } + + function toISOString(keepOffset) { + if (!this.isValid()) { + return null; + } + var utc = keepOffset !== true, + m = utc ? this.clone().utc() : this; + if (m.year() < 0 || m.year() > 9999) { + return formatMoment( + m, + utc + ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]' + : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ' + ); + } + if (isFunction(Date.prototype.toISOString)) { + // native implementation is ~50x faster, use it when we can + if (utc) { + return this.toDate().toISOString(); + } else { + return new Date(this.valueOf() + this.utcOffset() * 60 * 1000) + .toISOString() + .replace('Z', formatMoment(m, 'Z')); + } + } + return formatMoment( + m, + utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ' + ); + } + + /** + * Return a human readable representation of a moment that can + * also be evaluated to get a new moment which is the same + * + * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects + */ + function inspect() { + if (!this.isValid()) { + return 'moment.invalid(/* ' + this._i + ' */)'; + } + var func = 'moment', + zone = '', + prefix, + year, + datetime, + suffix; + if (!this.isLocal()) { + func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone'; + zone = 'Z'; + } + prefix = '[' + func + '("]'; + year = 0 <= this.year() && this.year() <= 9999 ? 'YYYY' : 'YYYYYY'; + datetime = '-MM-DD[T]HH:mm:ss.SSS'; + suffix = zone + '[")]'; + + return this.format(prefix + year + datetime + suffix); + } + + function format(inputString) { + if (!inputString) { + inputString = this.isUtc() + ? hooks.defaultFormatUtc + : hooks.defaultFormat; + } + var output = formatMoment(this, inputString); + return this.localeData().postformat(output); + } + + function from(time, withoutSuffix) { + if ( + this.isValid() && + ((isMoment(time) && time.isValid()) || createLocal(time).isValid()) + ) { + return createDuration({ to: this, from: time }) + .locale(this.locale()) + .humanize(!withoutSuffix); + } else { + return this.localeData().invalidDate(); + } + } + + function fromNow(withoutSuffix) { + return this.from(createLocal(), withoutSuffix); + } + + function to(time, withoutSuffix) { + if ( + this.isValid() && + ((isMoment(time) && time.isValid()) || createLocal(time).isValid()) + ) { + return createDuration({ from: this, to: time }) + .locale(this.locale()) + .humanize(!withoutSuffix); + } else { + return this.localeData().invalidDate(); + } + } + + function toNow(withoutSuffix) { + return this.to(createLocal(), withoutSuffix); + } + + // If passed a locale key, it will set the locale for this + // instance. Otherwise, it will return the locale configuration + // variables for this instance. + function locale(key) { + var newLocaleData; + + if (key === undefined) { + return this._locale._abbr; + } else { + newLocaleData = getLocale(key); + if (newLocaleData != null) { + this._locale = newLocaleData; + } + return this; + } + } + + var lang = deprecate( + 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', + function (key) { + if (key === undefined) { + return this.localeData(); + } else { + return this.locale(key); + } + } + ); + + function localeData() { + return this._locale; + } + + var MS_PER_SECOND = 1000, + MS_PER_MINUTE = 60 * MS_PER_SECOND, + MS_PER_HOUR = 60 * MS_PER_MINUTE, + MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR; + + // actual modulo - handles negative numbers (for dates before 1970): + function mod$1(dividend, divisor) { + return ((dividend % divisor) + divisor) % divisor; + } + + function localStartOfDate(y, m, d) { + // the date constructor remaps years 0-99 to 1900-1999 + if (y < 100 && y >= 0) { + // preserve leap years using a full 400 year cycle, then reset + return new Date(y + 400, m, d) - MS_PER_400_YEARS; + } else { + return new Date(y, m, d).valueOf(); + } + } + + function utcStartOfDate(y, m, d) { + // Date.UTC remaps years 0-99 to 1900-1999 + if (y < 100 && y >= 0) { + // preserve leap years using a full 400 year cycle, then reset + return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS; + } else { + return Date.UTC(y, m, d); + } + } + + function startOf(units) { + var time, startOfDate; + units = normalizeUnits(units); + if (units === undefined || units === 'millisecond' || !this.isValid()) { + return this; + } + + startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate; + + switch (units) { + case 'year': + time = startOfDate(this.year(), 0, 1); + break; + case 'quarter': + time = startOfDate( + this.year(), + this.month() - (this.month() % 3), + 1 + ); + break; + case 'month': + time = startOfDate(this.year(), this.month(), 1); + break; + case 'week': + time = startOfDate( + this.year(), + this.month(), + this.date() - this.weekday() + ); + break; + case 'isoWeek': + time = startOfDate( + this.year(), + this.month(), + this.date() - (this.isoWeekday() - 1) + ); + break; + case 'day': + case 'date': + time = startOfDate(this.year(), this.month(), this.date()); + break; + case 'hour': + time = this._d.valueOf(); + time -= mod$1( + time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), + MS_PER_HOUR + ); + break; + case 'minute': + time = this._d.valueOf(); + time -= mod$1(time, MS_PER_MINUTE); + break; + case 'second': + time = this._d.valueOf(); + time -= mod$1(time, MS_PER_SECOND); + break; + } + + this._d.setTime(time); + hooks.updateOffset(this, true); + return this; + } + + function endOf(units) { + var time, startOfDate; + units = normalizeUnits(units); + if (units === undefined || units === 'millisecond' || !this.isValid()) { + return this; + } + + startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate; + + switch (units) { + case 'year': + time = startOfDate(this.year() + 1, 0, 1) - 1; + break; + case 'quarter': + time = + startOfDate( + this.year(), + this.month() - (this.month() % 3) + 3, + 1 + ) - 1; + break; + case 'month': + time = startOfDate(this.year(), this.month() + 1, 1) - 1; + break; + case 'week': + time = + startOfDate( + this.year(), + this.month(), + this.date() - this.weekday() + 7 + ) - 1; + break; + case 'isoWeek': + time = + startOfDate( + this.year(), + this.month(), + this.date() - (this.isoWeekday() - 1) + 7 + ) - 1; + break; + case 'day': + case 'date': + time = startOfDate(this.year(), this.month(), this.date() + 1) - 1; + break; + case 'hour': + time = this._d.valueOf(); + time += + MS_PER_HOUR - + mod$1( + time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), + MS_PER_HOUR + ) - + 1; + break; + case 'minute': + time = this._d.valueOf(); + time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1; + break; + case 'second': + time = this._d.valueOf(); + time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1; + break; + } + + this._d.setTime(time); + hooks.updateOffset(this, true); + return this; + } + + function valueOf() { + return this._d.valueOf() - (this._offset || 0) * 60000; + } + + function unix() { + return Math.floor(this.valueOf() / 1000); + } + + function toDate() { + return new Date(this.valueOf()); + } + + function toArray() { + var m = this; + return [ + m.year(), + m.month(), + m.date(), + m.hour(), + m.minute(), + m.second(), + m.millisecond(), + ]; + } + + function toObject() { + var m = this; + return { + years: m.year(), + months: m.month(), + date: m.date(), + hours: m.hours(), + minutes: m.minutes(), + seconds: m.seconds(), + milliseconds: m.milliseconds(), + }; + } + + function toJSON() { + // new Date(NaN).toJSON() === null + return this.isValid() ? this.toISOString() : null; + } + + function isValid$2() { + return isValid(this); + } + + function parsingFlags() { + return extend({}, getParsingFlags(this)); + } + + function invalidAt() { + return getParsingFlags(this).overflow; + } + + function creationData() { + return { + input: this._i, + format: this._f, + locale: this._locale, + isUTC: this._isUTC, + strict: this._strict, + }; + } + + addFormatToken('N', 0, 0, 'eraAbbr'); + addFormatToken('NN', 0, 0, 'eraAbbr'); + addFormatToken('NNN', 0, 0, 'eraAbbr'); + addFormatToken('NNNN', 0, 0, 'eraName'); + addFormatToken('NNNNN', 0, 0, 'eraNarrow'); + + addFormatToken('y', ['y', 1], 'yo', 'eraYear'); + addFormatToken('y', ['yy', 2], 0, 'eraYear'); + addFormatToken('y', ['yyy', 3], 0, 'eraYear'); + addFormatToken('y', ['yyyy', 4], 0, 'eraYear'); + + addRegexToken('N', matchEraAbbr); + addRegexToken('NN', matchEraAbbr); + addRegexToken('NNN', matchEraAbbr); + addRegexToken('NNNN', matchEraName); + addRegexToken('NNNNN', matchEraNarrow); + + addParseToken( + ['N', 'NN', 'NNN', 'NNNN', 'NNNNN'], + function (input, array, config, token) { + var era = config._locale.erasParse(input, token, config._strict); + if (era) { + getParsingFlags(config).era = era; + } else { + getParsingFlags(config).invalidEra = input; + } + } + ); + + addRegexToken('y', matchUnsigned); + addRegexToken('yy', matchUnsigned); + addRegexToken('yyy', matchUnsigned); + addRegexToken('yyyy', matchUnsigned); + addRegexToken('yo', matchEraYearOrdinal); + + addParseToken(['y', 'yy', 'yyy', 'yyyy'], YEAR); + addParseToken(['yo'], function (input, array, config, token) { + var match; + if (config._locale._eraYearOrdinalRegex) { + match = input.match(config._locale._eraYearOrdinalRegex); + } + + if (config._locale.eraYearOrdinalParse) { + array[YEAR] = config._locale.eraYearOrdinalParse(input, match); + } else { + array[YEAR] = parseInt(input, 10); + } + }); + + function localeEras(m, format) { + var i, + l, + date, + eras = this._eras || getLocale('en')._eras; + for (i = 0, l = eras.length; i < l; ++i) { + switch (typeof eras[i].since) { + case 'string': + // truncate time + date = hooks(eras[i].since).startOf('day'); + eras[i].since = date.valueOf(); + break; + } + + switch (typeof eras[i].until) { + case 'undefined': + eras[i].until = +Infinity; + break; + case 'string': + // truncate time + date = hooks(eras[i].until).startOf('day').valueOf(); + eras[i].until = date.valueOf(); + break; + } + } + return eras; + } + + function localeErasParse(eraName, format, strict) { + var i, + l, + eras = this.eras(), + name, + abbr, + narrow; + eraName = eraName.toUpperCase(); + + for (i = 0, l = eras.length; i < l; ++i) { + name = eras[i].name.toUpperCase(); + abbr = eras[i].abbr.toUpperCase(); + narrow = eras[i].narrow.toUpperCase(); + + if (strict) { + switch (format) { + case 'N': + case 'NN': + case 'NNN': + if (abbr === eraName) { + return eras[i]; + } + break; + + case 'NNNN': + if (name === eraName) { + return eras[i]; + } + break; + + case 'NNNNN': + if (narrow === eraName) { + return eras[i]; + } + break; + } + } else if ([name, abbr, narrow].indexOf(eraName) >= 0) { + return eras[i]; + } + } + } + + function localeErasConvertYear(era, year) { + var dir = era.since <= era.until ? +1 : -1; + if (year === undefined) { + return hooks(era.since).year(); + } else { + return hooks(era.since).year() + (year - era.offset) * dir; + } + } + + function getEraName() { + var i, + l, + val, + eras = this.localeData().eras(); + for (i = 0, l = eras.length; i < l; ++i) { + // truncate time + val = this.clone().startOf('day').valueOf(); + + if (eras[i].since <= val && val <= eras[i].until) { + return eras[i].name; + } + if (eras[i].until <= val && val <= eras[i].since) { + return eras[i].name; + } + } + + return ''; + } + + function getEraNarrow() { + var i, + l, + val, + eras = this.localeData().eras(); + for (i = 0, l = eras.length; i < l; ++i) { + // truncate time + val = this.clone().startOf('day').valueOf(); + + if (eras[i].since <= val && val <= eras[i].until) { + return eras[i].narrow; + } + if (eras[i].until <= val && val <= eras[i].since) { + return eras[i].narrow; + } + } + + return ''; + } + + function getEraAbbr() { + var i, + l, + val, + eras = this.localeData().eras(); + for (i = 0, l = eras.length; i < l; ++i) { + // truncate time + val = this.clone().startOf('day').valueOf(); + + if (eras[i].since <= val && val <= eras[i].until) { + return eras[i].abbr; + } + if (eras[i].until <= val && val <= eras[i].since) { + return eras[i].abbr; + } + } + + return ''; + } + + function getEraYear() { + var i, + l, + dir, + val, + eras = this.localeData().eras(); + for (i = 0, l = eras.length; i < l; ++i) { + dir = eras[i].since <= eras[i].until ? +1 : -1; + + // truncate time + val = this.clone().startOf('day').valueOf(); + + if ( + (eras[i].since <= val && val <= eras[i].until) || + (eras[i].until <= val && val <= eras[i].since) + ) { + return ( + (this.year() - hooks(eras[i].since).year()) * dir + + eras[i].offset + ); + } + } + + return this.year(); + } + + function erasNameRegex(isStrict) { + if (!hasOwnProp(this, '_erasNameRegex')) { + computeErasParse.call(this); + } + return isStrict ? this._erasNameRegex : this._erasRegex; + } + + function erasAbbrRegex(isStrict) { + if (!hasOwnProp(this, '_erasAbbrRegex')) { + computeErasParse.call(this); + } + return isStrict ? this._erasAbbrRegex : this._erasRegex; + } + + function erasNarrowRegex(isStrict) { + if (!hasOwnProp(this, '_erasNarrowRegex')) { + computeErasParse.call(this); + } + return isStrict ? this._erasNarrowRegex : this._erasRegex; + } + + function matchEraAbbr(isStrict, locale) { + return locale.erasAbbrRegex(isStrict); + } + + function matchEraName(isStrict, locale) { + return locale.erasNameRegex(isStrict); + } + + function matchEraNarrow(isStrict, locale) { + return locale.erasNarrowRegex(isStrict); + } + + function matchEraYearOrdinal(isStrict, locale) { + return locale._eraYearOrdinalRegex || matchUnsigned; + } + + function computeErasParse() { + var abbrPieces = [], + namePieces = [], + narrowPieces = [], + mixedPieces = [], + i, + l, + eras = this.eras(); + + for (i = 0, l = eras.length; i < l; ++i) { + namePieces.push(regexEscape(eras[i].name)); + abbrPieces.push(regexEscape(eras[i].abbr)); + narrowPieces.push(regexEscape(eras[i].narrow)); + + mixedPieces.push(regexEscape(eras[i].name)); + mixedPieces.push(regexEscape(eras[i].abbr)); + mixedPieces.push(regexEscape(eras[i].narrow)); + } + + this._erasRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); + this._erasNameRegex = new RegExp('^(' + namePieces.join('|') + ')', 'i'); + this._erasAbbrRegex = new RegExp('^(' + abbrPieces.join('|') + ')', 'i'); + this._erasNarrowRegex = new RegExp( + '^(' + narrowPieces.join('|') + ')', + 'i' + ); + } + + // FORMATTING + + addFormatToken(0, ['gg', 2], 0, function () { + return this.weekYear() % 100; + }); + + addFormatToken(0, ['GG', 2], 0, function () { + return this.isoWeekYear() % 100; + }); + + function addWeekYearFormatToken(token, getter) { + addFormatToken(0, [token, token.length], 0, getter); + } + + addWeekYearFormatToken('gggg', 'weekYear'); + addWeekYearFormatToken('ggggg', 'weekYear'); + addWeekYearFormatToken('GGGG', 'isoWeekYear'); + addWeekYearFormatToken('GGGGG', 'isoWeekYear'); + + // ALIASES + + addUnitAlias('weekYear', 'gg'); + addUnitAlias('isoWeekYear', 'GG'); + + // PRIORITY + + addUnitPriority('weekYear', 1); + addUnitPriority('isoWeekYear', 1); + + // PARSING + + addRegexToken('G', matchSigned); + addRegexToken('g', matchSigned); + addRegexToken('GG', match1to2, match2); + addRegexToken('gg', match1to2, match2); + addRegexToken('GGGG', match1to4, match4); + addRegexToken('gggg', match1to4, match4); + addRegexToken('GGGGG', match1to6, match6); + addRegexToken('ggggg', match1to6, match6); + + addWeekParseToken( + ['gggg', 'ggggg', 'GGGG', 'GGGGG'], + function (input, week, config, token) { + week[token.substr(0, 2)] = toInt(input); + } + ); + + addWeekParseToken(['gg', 'GG'], function (input, week, config, token) { + week[token] = hooks.parseTwoDigitYear(input); + }); + + // MOMENTS + + function getSetWeekYear(input) { + return getSetWeekYearHelper.call( + this, + input, + this.week(), + this.weekday(), + this.localeData()._week.dow, + this.localeData()._week.doy + ); + } + + function getSetISOWeekYear(input) { + return getSetWeekYearHelper.call( + this, + input, + this.isoWeek(), + this.isoWeekday(), + 1, + 4 + ); + } + + function getISOWeeksInYear() { + return weeksInYear(this.year(), 1, 4); + } + + function getISOWeeksInISOWeekYear() { + return weeksInYear(this.isoWeekYear(), 1, 4); + } + + function getWeeksInYear() { + var weekInfo = this.localeData()._week; + return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); + } + + function getWeeksInWeekYear() { + var weekInfo = this.localeData()._week; + return weeksInYear(this.weekYear(), weekInfo.dow, weekInfo.doy); + } + + function getSetWeekYearHelper(input, week, weekday, dow, doy) { + var weeksTarget; + if (input == null) { + return weekOfYear(this, dow, doy).year; + } else { + weeksTarget = weeksInYear(input, dow, doy); + if (week > weeksTarget) { + week = weeksTarget; + } + return setWeekAll.call(this, input, week, weekday, dow, doy); + } + } + + function setWeekAll(weekYear, week, weekday, dow, doy) { + var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy), + date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear); + + this.year(date.getUTCFullYear()); + this.month(date.getUTCMonth()); + this.date(date.getUTCDate()); + return this; + } + + // FORMATTING + + addFormatToken('Q', 0, 'Qo', 'quarter'); + + // ALIASES + + addUnitAlias('quarter', 'Q'); + + // PRIORITY + + addUnitPriority('quarter', 7); + + // PARSING + + addRegexToken('Q', match1); + addParseToken('Q', function (input, array) { + array[MONTH] = (toInt(input) - 1) * 3; + }); + + // MOMENTS + + function getSetQuarter(input) { + return input == null + ? Math.ceil((this.month() + 1) / 3) + : this.month((input - 1) * 3 + (this.month() % 3)); + } + + // FORMATTING + + addFormatToken('D', ['DD', 2], 'Do', 'date'); + + // ALIASES + + addUnitAlias('date', 'D'); + + // PRIORITY + addUnitPriority('date', 9); + + // PARSING + + addRegexToken('D', match1to2); + addRegexToken('DD', match1to2, match2); + addRegexToken('Do', function (isStrict, locale) { + // TODO: Remove "ordinalParse" fallback in next major release. + return isStrict + ? locale._dayOfMonthOrdinalParse || locale._ordinalParse + : locale._dayOfMonthOrdinalParseLenient; + }); + + addParseToken(['D', 'DD'], DATE); + addParseToken('Do', function (input, array) { + array[DATE] = toInt(input.match(match1to2)[0]); + }); + + // MOMENTS + + var getSetDayOfMonth = makeGetSet('Date', true); + + // FORMATTING + + addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear'); + + // ALIASES + + addUnitAlias('dayOfYear', 'DDD'); + + // PRIORITY + addUnitPriority('dayOfYear', 4); + + // PARSING + + addRegexToken('DDD', match1to3); + addRegexToken('DDDD', match3); + addParseToken(['DDD', 'DDDD'], function (input, array, config) { + config._dayOfYear = toInt(input); + }); + + // HELPERS + + // MOMENTS + + function getSetDayOfYear(input) { + var dayOfYear = + Math.round( + (this.clone().startOf('day') - this.clone().startOf('year')) / 864e5 + ) + 1; + return input == null ? dayOfYear : this.add(input - dayOfYear, 'd'); + } + + // FORMATTING + + addFormatToken('m', ['mm', 2], 0, 'minute'); + + // ALIASES + + addUnitAlias('minute', 'm'); + + // PRIORITY + + addUnitPriority('minute', 14); + + // PARSING + + addRegexToken('m', match1to2); + addRegexToken('mm', match1to2, match2); + addParseToken(['m', 'mm'], MINUTE); + + // MOMENTS + + var getSetMinute = makeGetSet('Minutes', false); + + // FORMATTING + + addFormatToken('s', ['ss', 2], 0, 'second'); + + // ALIASES + + addUnitAlias('second', 's'); + + // PRIORITY + + addUnitPriority('second', 15); + + // PARSING + + addRegexToken('s', match1to2); + addRegexToken('ss', match1to2, match2); + addParseToken(['s', 'ss'], SECOND); + + // MOMENTS + + var getSetSecond = makeGetSet('Seconds', false); + + // FORMATTING + + addFormatToken('S', 0, 0, function () { + return ~~(this.millisecond() / 100); + }); + + addFormatToken(0, ['SS', 2], 0, function () { + return ~~(this.millisecond() / 10); + }); + + addFormatToken(0, ['SSS', 3], 0, 'millisecond'); + addFormatToken(0, ['SSSS', 4], 0, function () { + return this.millisecond() * 10; + }); + addFormatToken(0, ['SSSSS', 5], 0, function () { + return this.millisecond() * 100; + }); + addFormatToken(0, ['SSSSSS', 6], 0, function () { + return this.millisecond() * 1000; + }); + addFormatToken(0, ['SSSSSSS', 7], 0, function () { + return this.millisecond() * 10000; + }); + addFormatToken(0, ['SSSSSSSS', 8], 0, function () { + return this.millisecond() * 100000; + }); + addFormatToken(0, ['SSSSSSSSS', 9], 0, function () { + return this.millisecond() * 1000000; + }); + + // ALIASES + + addUnitAlias('millisecond', 'ms'); + + // PRIORITY + + addUnitPriority('millisecond', 16); + + // PARSING + + addRegexToken('S', match1to3, match1); + addRegexToken('SS', match1to3, match2); + addRegexToken('SSS', match1to3, match3); + + var token, getSetMillisecond; + for (token = 'SSSS'; token.length <= 9; token += 'S') { + addRegexToken(token, matchUnsigned); + } + + function parseMs(input, array) { + array[MILLISECOND] = toInt(('0.' + input) * 1000); + } + + for (token = 'S'; token.length <= 9; token += 'S') { + addParseToken(token, parseMs); + } + + getSetMillisecond = makeGetSet('Milliseconds', false); + + // FORMATTING + + addFormatToken('z', 0, 0, 'zoneAbbr'); + addFormatToken('zz', 0, 0, 'zoneName'); + + // MOMENTS + + function getZoneAbbr() { + return this._isUTC ? 'UTC' : ''; + } + + function getZoneName() { + return this._isUTC ? 'Coordinated Universal Time' : ''; + } + + var proto = Moment.prototype; + + proto.add = add; + proto.calendar = calendar$1; + proto.clone = clone; + proto.diff = diff; + proto.endOf = endOf; + proto.format = format; + proto.from = from; + proto.fromNow = fromNow; + proto.to = to; + proto.toNow = toNow; + proto.get = stringGet; + proto.invalidAt = invalidAt; + proto.isAfter = isAfter; + proto.isBefore = isBefore; + proto.isBetween = isBetween; + proto.isSame = isSame; + proto.isSameOrAfter = isSameOrAfter; + proto.isSameOrBefore = isSameOrBefore; + proto.isValid = isValid$2; + proto.lang = lang; + proto.locale = locale; + proto.localeData = localeData; + proto.max = prototypeMax; + proto.min = prototypeMin; + proto.parsingFlags = parsingFlags; + proto.set = stringSet; + proto.startOf = startOf; + proto.subtract = subtract; + proto.toArray = toArray; + proto.toObject = toObject; + proto.toDate = toDate; + proto.toISOString = toISOString; + proto.inspect = inspect; + if (typeof Symbol !== 'undefined' && Symbol.for != null) { + proto[Symbol.for('nodejs.util.inspect.custom')] = function () { + return 'Moment<' + this.format() + '>'; + }; + } + proto.toJSON = toJSON; + proto.toString = toString; + proto.unix = unix; + proto.valueOf = valueOf; + proto.creationData = creationData; + proto.eraName = getEraName; + proto.eraNarrow = getEraNarrow; + proto.eraAbbr = getEraAbbr; + proto.eraYear = getEraYear; + proto.year = getSetYear; + proto.isLeapYear = getIsLeapYear; + proto.weekYear = getSetWeekYear; + proto.isoWeekYear = getSetISOWeekYear; + proto.quarter = proto.quarters = getSetQuarter; + proto.month = getSetMonth; + proto.daysInMonth = getDaysInMonth; + proto.week = proto.weeks = getSetWeek; + proto.isoWeek = proto.isoWeeks = getSetISOWeek; + proto.weeksInYear = getWeeksInYear; + proto.weeksInWeekYear = getWeeksInWeekYear; + proto.isoWeeksInYear = getISOWeeksInYear; + proto.isoWeeksInISOWeekYear = getISOWeeksInISOWeekYear; + proto.date = getSetDayOfMonth; + proto.day = proto.days = getSetDayOfWeek; + proto.weekday = getSetLocaleDayOfWeek; + proto.isoWeekday = getSetISODayOfWeek; + proto.dayOfYear = getSetDayOfYear; + proto.hour = proto.hours = getSetHour; + proto.minute = proto.minutes = getSetMinute; + proto.second = proto.seconds = getSetSecond; + proto.millisecond = proto.milliseconds = getSetMillisecond; + proto.utcOffset = getSetOffset; + proto.utc = setOffsetToUTC; + proto.local = setOffsetToLocal; + proto.parseZone = setOffsetToParsedOffset; + proto.hasAlignedHourOffset = hasAlignedHourOffset; + proto.isDST = isDaylightSavingTime; + proto.isLocal = isLocal; + proto.isUtcOffset = isUtcOffset; + proto.isUtc = isUtc; + proto.isUTC = isUtc; + proto.zoneAbbr = getZoneAbbr; + proto.zoneName = getZoneName; + proto.dates = deprecate( + 'dates accessor is deprecated. Use date instead.', + getSetDayOfMonth + ); + proto.months = deprecate( + 'months accessor is deprecated. Use month instead', + getSetMonth + ); + proto.years = deprecate( + 'years accessor is deprecated. Use year instead', + getSetYear + ); + proto.zone = deprecate( + 'moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', + getSetZone + ); + proto.isDSTShifted = deprecate( + 'isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', + isDaylightSavingTimeShifted + ); + + function createUnix(input) { + return createLocal(input * 1000); + } + + function createInZone() { + return createLocal.apply(null, arguments).parseZone(); + } + + function preParsePostFormat(string) { + return string; + } + + var proto$1 = Locale.prototype; + + proto$1.calendar = calendar; + proto$1.longDateFormat = longDateFormat; + proto$1.invalidDate = invalidDate; + proto$1.ordinal = ordinal; + proto$1.preparse = preParsePostFormat; + proto$1.postformat = preParsePostFormat; + proto$1.relativeTime = relativeTime; + proto$1.pastFuture = pastFuture; + proto$1.set = set; + proto$1.eras = localeEras; + proto$1.erasParse = localeErasParse; + proto$1.erasConvertYear = localeErasConvertYear; + proto$1.erasAbbrRegex = erasAbbrRegex; + proto$1.erasNameRegex = erasNameRegex; + proto$1.erasNarrowRegex = erasNarrowRegex; + + proto$1.months = localeMonths; + proto$1.monthsShort = localeMonthsShort; + proto$1.monthsParse = localeMonthsParse; + proto$1.monthsRegex = monthsRegex; + proto$1.monthsShortRegex = monthsShortRegex; + proto$1.week = localeWeek; + proto$1.firstDayOfYear = localeFirstDayOfYear; + proto$1.firstDayOfWeek = localeFirstDayOfWeek; + + proto$1.weekdays = localeWeekdays; + proto$1.weekdaysMin = localeWeekdaysMin; + proto$1.weekdaysShort = localeWeekdaysShort; + proto$1.weekdaysParse = localeWeekdaysParse; + + proto$1.weekdaysRegex = weekdaysRegex; + proto$1.weekdaysShortRegex = weekdaysShortRegex; + proto$1.weekdaysMinRegex = weekdaysMinRegex; + + proto$1.isPM = localeIsPM; + proto$1.meridiem = localeMeridiem; + + function get$1(format, index, field, setter) { + var locale = getLocale(), + utc = createUTC().set(setter, index); + return locale[field](utc, format); + } + + function listMonthsImpl(format, index, field) { + if (isNumber(format)) { + index = format; + format = undefined; + } + + format = format || ''; + + if (index != null) { + return get$1(format, index, field, 'month'); + } + + var i, + out = []; + for (i = 0; i < 12; i++) { + out[i] = get$1(format, i, field, 'month'); + } + return out; + } + + // () + // (5) + // (fmt, 5) + // (fmt) + // (true) + // (true, 5) + // (true, fmt, 5) + // (true, fmt) + function listWeekdaysImpl(localeSorted, format, index, field) { + if (typeof localeSorted === 'boolean') { + if (isNumber(format)) { + index = format; + format = undefined; + } + + format = format || ''; + } else { + format = localeSorted; + index = format; + localeSorted = false; + + if (isNumber(format)) { + index = format; + format = undefined; + } + + format = format || ''; + } + + var locale = getLocale(), + shift = localeSorted ? locale._week.dow : 0, + i, + out = []; + + if (index != null) { + return get$1(format, (index + shift) % 7, field, 'day'); + } + + for (i = 0; i < 7; i++) { + out[i] = get$1(format, (i + shift) % 7, field, 'day'); + } + return out; + } + + function listMonths(format, index) { + return listMonthsImpl(format, index, 'months'); + } + + function listMonthsShort(format, index) { + return listMonthsImpl(format, index, 'monthsShort'); + } + + function listWeekdays(localeSorted, format, index) { + return listWeekdaysImpl(localeSorted, format, index, 'weekdays'); + } + + function listWeekdaysShort(localeSorted, format, index) { + return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort'); + } + + function listWeekdaysMin(localeSorted, format, index) { + return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin'); + } + + getSetGlobalLocale('en', { + eras: [ + { + since: '0001-01-01', + until: +Infinity, + offset: 1, + name: 'Anno Domini', + narrow: 'AD', + abbr: 'AD', + }, + { + since: '0000-12-31', + until: -Infinity, + offset: 1, + name: 'Before Christ', + narrow: 'BC', + abbr: 'BC', + }, + ], + dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, + ordinal: function (number) { + var b = number % 10, + output = + toInt((number % 100) / 10) === 1 + ? 'th' + : b === 1 + ? 'st' + : b === 2 + ? 'nd' + : b === 3 + ? 'rd' + : 'th'; + return number + output; + }, + }); + + // Side effect imports + + hooks.lang = deprecate( + 'moment.lang is deprecated. Use moment.locale instead.', + getSetGlobalLocale + ); + hooks.langData = deprecate( + 'moment.langData is deprecated. Use moment.localeData instead.', + getLocale + ); + + var mathAbs = Math.abs; + + function abs() { + var data = this._data; + + this._milliseconds = mathAbs(this._milliseconds); + this._days = mathAbs(this._days); + this._months = mathAbs(this._months); + + data.milliseconds = mathAbs(data.milliseconds); + data.seconds = mathAbs(data.seconds); + data.minutes = mathAbs(data.minutes); + data.hours = mathAbs(data.hours); + data.months = mathAbs(data.months); + data.years = mathAbs(data.years); + + return this; + } + + function addSubtract$1(duration, input, value, direction) { + var other = createDuration(input, value); + + duration._milliseconds += direction * other._milliseconds; + duration._days += direction * other._days; + duration._months += direction * other._months; + + return duration._bubble(); + } + + // supports only 2.0-style add(1, 's') or add(duration) + function add$1(input, value) { + return addSubtract$1(this, input, value, 1); + } + + // supports only 2.0-style subtract(1, 's') or subtract(duration) + function subtract$1(input, value) { + return addSubtract$1(this, input, value, -1); + } + + function absCeil(number) { + if (number < 0) { + return Math.floor(number); + } else { + return Math.ceil(number); + } + } + + function bubble() { + var milliseconds = this._milliseconds, + days = this._days, + months = this._months, + data = this._data, + seconds, + minutes, + hours, + years, + monthsFromDays; + + // if we have a mix of positive and negative values, bubble down first + // check: https://github.com/moment/moment/issues/2166 + if ( + !( + (milliseconds >= 0 && days >= 0 && months >= 0) || + (milliseconds <= 0 && days <= 0 && months <= 0) + ) + ) { + milliseconds += absCeil(monthsToDays(months) + days) * 864e5; + days = 0; + months = 0; + } + + // The following code bubbles up values, see the tests for + // examples of what that means. + data.milliseconds = milliseconds % 1000; + + seconds = absFloor(milliseconds / 1000); + data.seconds = seconds % 60; + + minutes = absFloor(seconds / 60); + data.minutes = minutes % 60; + + hours = absFloor(minutes / 60); + data.hours = hours % 24; + + days += absFloor(hours / 24); + + // convert days to months + monthsFromDays = absFloor(daysToMonths(days)); + months += monthsFromDays; + days -= absCeil(monthsToDays(monthsFromDays)); + + // 12 months -> 1 year + years = absFloor(months / 12); + months %= 12; + + data.days = days; + data.months = months; + data.years = years; + + return this; + } + + function daysToMonths(days) { + // 400 years have 146097 days (taking into account leap year rules) + // 400 years have 12 months === 4800 + return (days * 4800) / 146097; + } + + function monthsToDays(months) { + // the reverse of daysToMonths + return (months * 146097) / 4800; + } + + function as(units) { + if (!this.isValid()) { + return NaN; + } + var days, + months, + milliseconds = this._milliseconds; + + units = normalizeUnits(units); + + if (units === 'month' || units === 'quarter' || units === 'year') { + days = this._days + milliseconds / 864e5; + months = this._months + daysToMonths(days); + switch (units) { + case 'month': + return months; + case 'quarter': + return months / 3; + case 'year': + return months / 12; + } + } else { + // handle milliseconds separately because of floating point math errors (issue #1867) + days = this._days + Math.round(monthsToDays(this._months)); + switch (units) { + case 'week': + return days / 7 + milliseconds / 6048e5; + case 'day': + return days + milliseconds / 864e5; + case 'hour': + return days * 24 + milliseconds / 36e5; + case 'minute': + return days * 1440 + milliseconds / 6e4; + case 'second': + return days * 86400 + milliseconds / 1000; + // Math.floor prevents floating point math errors here + case 'millisecond': + return Math.floor(days * 864e5) + milliseconds; + default: + throw new Error('Unknown unit ' + units); + } + } + } + + // TODO: Use this.as('ms')? + function valueOf$1() { + if (!this.isValid()) { + return NaN; + } + return ( + this._milliseconds + + this._days * 864e5 + + (this._months % 12) * 2592e6 + + toInt(this._months / 12) * 31536e6 + ); + } + + function makeAs(alias) { + return function () { + return this.as(alias); + }; + } + + var asMilliseconds = makeAs('ms'), + asSeconds = makeAs('s'), + asMinutes = makeAs('m'), + asHours = makeAs('h'), + asDays = makeAs('d'), + asWeeks = makeAs('w'), + asMonths = makeAs('M'), + asQuarters = makeAs('Q'), + asYears = makeAs('y'); + + function clone$1() { + return createDuration(this); + } + + function get$2(units) { + units = normalizeUnits(units); + return this.isValid() ? this[units + 's']() : NaN; + } + + function makeGetter(name) { + return function () { + return this.isValid() ? this._data[name] : NaN; + }; + } + + var milliseconds = makeGetter('milliseconds'), + seconds = makeGetter('seconds'), + minutes = makeGetter('minutes'), + hours = makeGetter('hours'), + days = makeGetter('days'), + months = makeGetter('months'), + years = makeGetter('years'); + + function weeks() { + return absFloor(this.days() / 7); + } + + var round = Math.round, + thresholds = { + ss: 44, // a few seconds to seconds + s: 45, // seconds to minute + m: 45, // minutes to hour + h: 22, // hours to day + d: 26, // days to month/week + w: null, // weeks to month + M: 11, // months to year + }; + + // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize + function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) { + return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); + } + + function relativeTime$1(posNegDuration, withoutSuffix, thresholds, locale) { + var duration = createDuration(posNegDuration).abs(), + seconds = round(duration.as('s')), + minutes = round(duration.as('m')), + hours = round(duration.as('h')), + days = round(duration.as('d')), + months = round(duration.as('M')), + weeks = round(duration.as('w')), + years = round(duration.as('y')), + 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]); + + if (thresholds.w != null) { + a = + a || + (weeks <= 1 && ['w']) || + (weeks < thresholds.w && ['ww', weeks]); + } + a = a || + (months <= 1 && ['M']) || + (months < thresholds.M && ['MM', months]) || + (years <= 1 && ['y']) || ['yy', years]; + + a[2] = withoutSuffix; + a[3] = +posNegDuration > 0; + a[4] = locale; + return substituteTimeAgo.apply(null, a); + } + + // This function allows you to set the rounding function for relative time strings + function getSetRelativeTimeRounding(roundingFunction) { + if (roundingFunction === undefined) { + return round; + } + if (typeof roundingFunction === 'function') { + round = roundingFunction; + return true; + } + return false; + } + + // This function allows you to set a threshold for relative time strings + function getSetRelativeTimeThreshold(threshold, limit) { + if (thresholds[threshold] === undefined) { + return false; + } + if (limit === undefined) { + return thresholds[threshold]; + } + thresholds[threshold] = limit; + if (threshold === 's') { + thresholds.ss = limit - 1; + } + return true; + } + + function humanize(argWithSuffix, argThresholds) { + if (!this.isValid()) { + return this.localeData().invalidDate(); + } + + var withSuffix = false, + th = thresholds, + locale, + output; + + if (typeof argWithSuffix === 'object') { + argThresholds = argWithSuffix; + argWithSuffix = false; + } + if (typeof argWithSuffix === 'boolean') { + withSuffix = argWithSuffix; + } + if (typeof argThresholds === 'object') { + th = Object.assign({}, thresholds, argThresholds); + if (argThresholds.s != null && argThresholds.ss == null) { + th.ss = argThresholds.s - 1; + } + } + + locale = this.localeData(); + output = relativeTime$1(this, !withSuffix, th, locale); + + if (withSuffix) { + output = locale.pastFuture(+this, output); + } + + return locale.postformat(output); + } + + var abs$1 = Math.abs; + + function sign(x) { + return (x > 0) - (x < 0) || +x; + } + + function toISOString$1() { + // for ISO strings we do not use the normal bubbling rules: + // * milliseconds bubble up until they become hours + // * days do not bubble at all + // * months bubble up until they become years + // This is because there is no context-free conversion between hours and days + // (think of clock changes) + // and also not between days and months (28-31 days per month) + if (!this.isValid()) { + return this.localeData().invalidDate(); + } + + var seconds = abs$1(this._milliseconds) / 1000, + days = abs$1(this._days), + months = abs$1(this._months), + minutes, + hours, + years, + s, + total = this.asSeconds(), + totalSign, + ymSign, + daysSign, + hmsSign; + + if (!total) { + // this is the same as C#'s (Noda) and python (isodate)... + // but not other JS (goog.date) + return 'P0D'; + } + + // 3600 seconds -> 60 minutes -> 1 hour + minutes = absFloor(seconds / 60); + hours = absFloor(minutes / 60); + seconds %= 60; + minutes %= 60; + + // 12 months -> 1 year + years = absFloor(months / 12); + months %= 12; + + // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js + s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : ''; + + totalSign = total < 0 ? '-' : ''; + ymSign = sign(this._months) !== sign(total) ? '-' : ''; + daysSign = sign(this._days) !== sign(total) ? '-' : ''; + hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : ''; + + return ( + totalSign + + 'P' + + (years ? ymSign + years + 'Y' : '') + + (months ? ymSign + months + 'M' : '') + + (days ? daysSign + days + 'D' : '') + + (hours || minutes || seconds ? 'T' : '') + + (hours ? hmsSign + hours + 'H' : '') + + (minutes ? hmsSign + minutes + 'M' : '') + + (seconds ? hmsSign + s + 'S' : '') + ); + } + + var proto$2 = Duration.prototype; + + proto$2.isValid = isValid$1; + proto$2.abs = abs; + proto$2.add = add$1; + proto$2.subtract = subtract$1; + proto$2.as = as; + proto$2.asMilliseconds = asMilliseconds; + proto$2.asSeconds = asSeconds; + proto$2.asMinutes = asMinutes; + proto$2.asHours = asHours; + proto$2.asDays = asDays; + proto$2.asWeeks = asWeeks; + proto$2.asMonths = asMonths; + proto$2.asQuarters = asQuarters; + proto$2.asYears = asYears; + proto$2.valueOf = valueOf$1; + proto$2._bubble = bubble; + proto$2.clone = clone$1; + proto$2.get = get$2; + proto$2.milliseconds = milliseconds; + proto$2.seconds = seconds; + proto$2.minutes = minutes; + proto$2.hours = hours; + proto$2.days = days; + proto$2.weeks = weeks; + proto$2.months = months; + proto$2.years = years; + proto$2.humanize = humanize; + proto$2.toISOString = toISOString$1; + proto$2.toString = toISOString$1; + proto$2.toJSON = toISOString$1; + proto$2.locale = locale; + proto$2.localeData = localeData; + + proto$2.toIsoString = deprecate( + 'toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', + toISOString$1 + ); + proto$2.lang = lang; + + // FORMATTING + + addFormatToken('X', 0, 0, 'unix'); + addFormatToken('x', 0, 0, 'valueOf'); + + // PARSING + + addRegexToken('x', matchSigned); + addRegexToken('X', matchTimestamp); + addParseToken('X', function (input, array, config) { + config._d = new Date(parseFloat(input) * 1000); + }); + addParseToken('x', function (input, array, config) { + config._d = new Date(toInt(input)); + }); + + //! moment.js + + hooks.version = '2.29.4'; + + setHookCallback(createLocal); + + hooks.fn = proto; + hooks.min = min; + hooks.max = max; + hooks.now = now; + hooks.utc = createUTC; + hooks.unix = createUnix; + hooks.months = listMonths; + hooks.isDate = isDate; + hooks.locale = getSetGlobalLocale; + hooks.invalid = createInvalid; + hooks.duration = createDuration; + hooks.isMoment = isMoment; + hooks.weekdays = listWeekdays; + hooks.parseZone = createInZone; + hooks.localeData = getLocale; + hooks.isDuration = isDuration; + hooks.monthsShort = listMonthsShort; + hooks.weekdaysMin = listWeekdaysMin; + hooks.defineLocale = defineLocale; + hooks.updateLocale = updateLocale; + hooks.locales = listLocales; + hooks.weekdaysShort = listWeekdaysShort; + hooks.normalizeUnits = normalizeUnits; + hooks.relativeTimeRounding = getSetRelativeTimeRounding; + hooks.relativeTimeThreshold = getSetRelativeTimeThreshold; + hooks.calendarFormat = getCalendarFormat; + hooks.prototype = proto; + + // currently HTML5 input type only supports 24-hour formats + hooks.HTML5_FMT = { + DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', // + DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', // + DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', // + DATE: 'YYYY-MM-DD', // + TIME: 'HH:mm', // + TIME_SECONDS: 'HH:mm:ss', // + TIME_MS: 'HH:mm:ss.SSS', // + WEEK: 'GGGG-[W]WW', // + MONTH: 'YYYY-MM', // + }; + + return hooks; + + }))); +} (moment$1)); + +var momentExports = moment$1.exports; +var moment = /*@__PURE__*/getDefaultExportFromCjs(momentExports); + +var DefaultContext = { + color: undefined, + size: undefined, + className: undefined, + style: undefined, + attr: undefined +}; +var IconContext = React.createContext && React.createContext(DefaultContext); + +var __assign = undefined && undefined.__assign || function () { + __assign = Object.assign || function (t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +var __rest = undefined && undefined.__rest || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; + } + return t; +}; +function Tree2Element(tree) { + return tree && tree.map(function (node, i) { + return React.createElement(node.tag, __assign({ + key: i + }, node.attr), Tree2Element(node.child)); + }); +} +function GenIcon(data) { + // eslint-disable-next-line react/display-name + return function (props) { + return React.createElement(IconBase, __assign({ + attr: __assign({}, data.attr) + }, props), Tree2Element(data.child)); + }; +} +function IconBase(props) { + var elem = function (conf) { + var attr = props.attr, + size = props.size, + title = props.title, + svgProps = __rest(props, ["attr", "size", "title"]); + var computedSize = size || conf.size || "1em"; + var className; + if (conf.className) className = conf.className; + if (props.className) className = (className ? className + " " : "") + props.className; + return React.createElement("svg", __assign({ + stroke: "currentColor", + fill: "currentColor", + strokeWidth: "0" + }, conf.attr, attr, svgProps, { + className: className, + style: __assign(__assign({ + color: props.color || conf.color + }, conf.style), props.style), + height: computedSize, + width: computedSize, + xmlns: "http://www.w3.org/2000/svg" + }), title && React.createElement("title", null, title), props.children); + }; + return IconContext !== undefined ? React.createElement(IconContext.Consumer, null, function (conf) { + return elem(conf); + }) : elem(DefaultContext); +} + +// THIS FILE IS AUTO GENERATED +function GoChevronDown (props) { + return GenIcon({"tag":"svg","attr":{"viewBox":"0 0 10 16"},"child":[{"tag":"path","attr":{"fillRule":"evenodd","d":"M5 11L0 6l1.5-1.5L5 8.25 8.5 4.5 10 6l-5 5z"}}]})(props); +}function GoChevronUp (props) { + return GenIcon({"tag":"svg","attr":{"viewBox":"0 0 10 16"},"child":[{"tag":"path","attr":{"fillRule":"evenodd","d":"M10 10l-1.5 1.5L5 7.75 1.5 11.5 0 10l5-5 5 5z"}}]})(props); +} + +// THIS FILE IS AUTO GENERATED +function TiMinus (props) { + return GenIcon({"tag":"svg","attr":{"version":"1.2","baseProfile":"tiny","viewBox":"0 0 24 24"},"child":[{"tag":"path","attr":{"d":"M18 11h-12c-1.104 0-2 .896-2 2s.896 2 2 2h12c1.104 0 2-.896 2-2s-.896-2-2-2z"}}]})(props); +} + +var reactTable = {exports: {}}; + +var reactTable_production_min = {exports: {}}; + +(function (module, exports) { + !function(e,t){t(exports,reactExports);}(commonjsGlobal,(function(e,t){function n(e,t,n,o,r,i,u){try{var l=e[i](u),s=l.value;}catch(e){return void n(e)}l.done?t(s):Promise.resolve(s).then(o,r);}function o(e){return function(){var t=this,o=arguments;return new Promise((function(r,i){var u=e.apply(t,o);function l(e){n(u,r,i,l,s,"next",e);}function s(e){n(u,r,i,l,s,"throw",e);}l(void 0);}))}}function r(){return (r=Object.assign||function(e){for(var t=1;t=0||(r[n]=e[n]);return r}function u(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var o=n.call(e,t||"default");if("object"!=typeof o)return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return ("string"===t?String:Number)(e)}(e,"string");return "symbol"==typeof t?t:String(t)}t=t&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t;var l={init:"init"},s=function(e){var t=e.value;return void 0===t?"":t},a=function(){return t.createElement(t.Fragment,null," ")},c={Cell:s,width:150,minWidth:0,maxWidth:Number.MAX_SAFE_INTEGER};function d(){for(var e=arguments.length,t=new Array(e),n=0;n(i="number"==typeof i?i:1/0)){var u=r;r=i,i=u;}return e.filter((function(e){return t.some((function(t){var n=e.values[t];return n>=r&&n<=i}))}))};Ce.autoRemove=function(e){return !e||"number"!=typeof e[0]&&"number"!=typeof e[1]};var xe=Object.freeze({__proto__:null,text:ge,exactText:ve,exactTextCase:me,includes:he,includesAll:ye,includesSome:we,includesValue:Re,exact:be,equals:Se,between:Ce});l.resetFilters="resetFilters",l.setFilter="setFilter",l.setAllFilters="setAllFilters";var Pe=function(e){e.stateReducers.push(Be),e.useInstance.push(Ee);};function Be(e,t,n,o){if(t.type===l.init)return r({filters:[]},e);if(t.type===l.resetFilters)return r({},e,{filters:o.initialState.filters||[]});if(t.type===l.setFilter){var i=t.columnId,u=t.filterValue,s=o.allColumns,a=o.filterTypes,c=s.find((function(e){return e.id===i}));if(!c)throw new Error("React-Table: Could not find a column with id: "+i);var d=k(c.filter,a||{},xe),f=e.filters.find((function(e){return e.id===i})),p=m(u,f&&f.value);return H(d.autoRemove,p,c)?r({},e,{filters:e.filters.filter((function(e){return e.id!==i}))}):r({},e,f?{filters:e.filters.map((function(e){return e.id===i?{id:i,value:p}:e}))}:{filters:[].concat(e.filters,[{id:i,value:p}])})}if(t.type===l.setAllFilters){var g=t.filters,v=o.allColumns,h=o.filterTypes;return r({},e,{filters:m(g,e.filters).filter((function(e){var t=v.find((function(t){return t.id===e.id}));return !H(k(t.filter,h||{},xe).autoRemove,e.value,t)}))})}}function Ee(e){var n=e.data,o=e.rows,r=e.flatRows,i=e.rowsById,u=e.allColumns,s=e.filterTypes,a=e.manualFilters,c=e.defaultCanFilter,d=void 0!==c&&c,f=e.disableFilters,p=e.state.filters,g=e.dispatch,v=e.autoResetFilters,m=void 0===v||v,y=t.useCallback((function(e,t){g({type:l.setFilter,columnId:e,filterValue:t});}),[g]),R=t.useCallback((function(e){g({type:l.setAllFilters,filters:e});}),[g]);u.forEach((function(e){var t=e.id,n=e.accessor,o=e.defaultCanFilter,r=e.disableFilters;e.canFilter=n?I(!0!==r&&void 0,!0!==f&&void 0,!0):I(o,d,!1),e.setFilter=function(t){return y(e.id,t)};var i=p.find((function(e){return e.id===t}));e.filterValue=i&&i.value;}));var b=t.useMemo((function(){if(a||!p.length)return [o,r,i];var e=[],t={};return [function n(o,r){void 0===r&&(r=0);var i=o;return (i=p.reduce((function(e,t){var n=t.id,o=t.value,i=u.find((function(e){return e.id===n}));if(!i)return e;0===r&&(i.preFilteredRows=e);var l=k(i.filter,s||{},xe);return l?(i.filteredRows=l(e,[n],o),i.filteredRows):(console.warn("Could not find a valid 'column.filter' for column with the ID: "+i.id+"."),e)}),o)).forEach((function(o){e.push(o),t[o.id]=o,o.subRows&&(o.subRows=o.subRows&&o.subRows.length>0?n(o.subRows,r+1):o.subRows);})),i}(o),e,t]}),[a,p,o,r,i,u,s]),S=b[0],C=b[1],x=b[2];t.useMemo((function(){u.filter((function(e){return !p.find((function(t){return t.id===e.id}))})).forEach((function(e){e.preFilteredRows=S,e.filteredRows=S;}));}),[S,p,u]);var P=h(m);w((function(){P()&&g({type:l.resetFilters});}),[g,a?null:n]),Object.assign(e,{preFilteredRows:o,preFilteredFlatRows:r,preFilteredRowsById:i,filteredRows:S,filteredFlatRows:C,filteredRowsById:x,rows:S,flatRows:C,rowsById:x,setFilter:y,setAllFilters:R});}Pe.pluginName="useFilters",l.resetGlobalFilter="resetGlobalFilter",l.setGlobalFilter="setGlobalFilter";var Ie=function(e){e.stateReducers.push(Fe),e.useInstance.push(Ge);};function Fe(e,t,n,o){if(t.type===l.resetGlobalFilter)return r({},e,{globalFilter:o.initialState.globalFilter||void 0});if(t.type===l.setGlobalFilter){var u=t.filterValue,s=o.userFilterTypes,a=k(o.globalFilter,s||{},xe),c=m(u,e.globalFilter);if(H(a.autoRemove,c)){e.globalFilter;return i(e,["globalFilter"])}return r({},e,{globalFilter:c})}}function Ge(e){var n=e.data,o=e.rows,r=e.flatRows,i=e.rowsById,u=e.allColumns,s=e.filterTypes,a=e.globalFilter,c=e.manualGlobalFilter,d=e.state.globalFilter,f=e.dispatch,p=e.autoResetGlobalFilter,g=void 0===p||p,v=e.disableGlobalFilter,m=t.useCallback((function(e){f({type:l.setGlobalFilter,filterValue:e});}),[f]),y=t.useMemo((function(){if(c||void 0===d)return [o,r,i];var e=[],t={},n=k(a,s||{},xe);if(!n)return console.warn("Could not find a valid 'globalFilter' option."),o;u.forEach((function(e){var t=e.disableGlobalFilter;e.canFilter=I(!0!==t&&void 0,!0!==v&&void 0,!0);}));var l=u.filter((function(e){return !0===e.canFilter}));return [function o(r){return (r=n(r,l.map((function(e){return e.id})),d)).forEach((function(n){e.push(n),t[n.id]=n,n.subRows=n.subRows&&n.subRows.length?o(n.subRows):n.subRows;})),r}(o),e,t]}),[c,d,a,s,u,o,r,i,v]),R=y[0],b=y[1],S=y[2],C=h(g);w((function(){C()&&f({type:l.resetGlobalFilter});}),[f,c?null:n]),Object.assign(e,{preGlobalFilteredRows:o,preGlobalFilteredFlatRows:r,preGlobalFilteredRowsById:i,globalFilteredRows:R,globalFilteredFlatRows:b,globalFilteredRowsById:S,rows:R,flatRows:b,rowsById:S,setGlobalFilter:m,disableGlobalFilter:v});}function Ae(e,t){return t.reduce((function(e,t){return e+("number"==typeof t?t:0)}),0)}Ie.pluginName="useGlobalFilter";var ke=Object.freeze({__proto__:null,sum:Ae,min:function(e){var t=e[0]||0;return e.forEach((function(e){"number"==typeof e&&(t=Math.min(t,e));})),t},max:function(e){var t=e[0]||0;return e.forEach((function(e){"number"==typeof e&&(t=Math.max(t,e));})),t},minMax:function(e){var t=e[0]||0,n=e[0]||0;return e.forEach((function(e){"number"==typeof e&&(t=Math.min(t,e),n=Math.max(n,e));})),t+".."+n},average:function(e){return Ae(0,e)/e.length},median:function(e){if(!e.length)return null;var t=Math.floor(e.length/2),n=[].concat(e).sort((function(e,t){return e-t}));return e.length%2!=0?n[t]:(n[t-1]+n[t])/2},unique:function(e){return Array.from(new Set(e).values())},uniqueCount:function(e){return new Set(e).size},count:function(e){return e.length}}),He=[],We={};l.resetGroupBy="resetGroupBy",l.setGroupBy="setGroupBy",l.toggleGroupBy="toggleGroupBy";var ze=function(e){e.getGroupByToggleProps=[Te],e.stateReducers.push(Oe),e.visibleColumnsDeps.push((function(e,t){var n=t.instance;return [].concat(e,[n.state.groupBy])})),e.visibleColumns.push(Me),e.useInstance.push(Le),e.prepareRow.push(Ne);};ze.pluginName="useGroupBy";var Te=function(e,t){var n=t.header;return [e,{onClick:n.canGroupBy?function(e){e.persist(),n.toggleGroupBy();}:void 0,style:{cursor:n.canGroupBy?"pointer":void 0},title:"Toggle GroupBy"}]};function Oe(e,t,n,o){if(t.type===l.init)return r({groupBy:[]},e);if(t.type===l.resetGroupBy)return r({},e,{groupBy:o.initialState.groupBy||[]});if(t.type===l.setGroupBy)return r({},e,{groupBy:t.value});if(t.type===l.toggleGroupBy){var i=t.columnId,u=t.value,s=void 0!==u?u:!e.groupBy.includes(i);return r({},e,s?{groupBy:[].concat(e.groupBy,[i])}:{groupBy:e.groupBy.filter((function(e){return e!==i}))})}}function Me(e,t){var n=t.instance.state.groupBy,o=n.map((function(t){return e.find((function(e){return e.id===t}))})).filter(Boolean),r=e.filter((function(e){return !n.includes(e.id)}));return (e=[].concat(o,r)).forEach((function(e){e.isGrouped=n.includes(e.id),e.groupedIndex=n.indexOf(e.id);})),e}var je={};function Le(e){var n=e.data,o=e.rows,i=e.flatRows,u=e.rowsById,s=e.allColumns,a=e.flatHeaders,c=e.groupByFn,d=void 0===c?De:c,p=e.manualGroupBy,g=e.aggregations,m=void 0===g?je:g,y=e.plugins,R=e.state.groupBy,b=e.dispatch,S=e.autoResetGroupBy,C=void 0===S||S,x=e.disableGroupBy,P=e.defaultCanGroupBy,B=e.getHooks;v(y,["useColumnOrder","useFilters"],"useGroupBy");var E=h(e);s.forEach((function(t){var n=t.accessor,o=t.defaultGroupBy,r=t.disableGroupBy;t.canGroupBy=n?I(t.canGroupBy,!0!==r&&void 0,!0!==x&&void 0,!0):I(t.canGroupBy,o,P,!1),t.canGroupBy&&(t.toggleGroupBy=function(){return e.toggleGroupBy(t.id)}),t.Aggregated=t.Aggregated||t.Cell;}));var F=t.useCallback((function(e,t){b({type:l.toggleGroupBy,columnId:e,value:t});}),[b]),A=t.useCallback((function(e){b({type:l.setGroupBy,value:e});}),[b]);a.forEach((function(e){e.getGroupByToggleProps=f(B().getGroupByToggleProps,{instance:E(),header:e});}));var k=t.useMemo((function(){if(p||!R.length)return [o,i,u,He,We,i,u];var e=R.filter((function(e){return s.find((function(t){return t.id===e}))})),t=[],n={},l=[],a={},c=[],f={},g=function o(i,u,p){if(void 0===u&&(u=0),u===e.length)return i.map((function(e){return r({},e,{depth:u})}));var g=e[u],v=d(i,g);return Object.entries(v).map((function(r,i){var d=r[0],v=r[1],h=g+":"+d,y=o(v,u+1,h=p?p+">"+h:h),w=u?G(v,"leafRows"):v,R=function(t,n,o){var r={};return s.forEach((function(i){if(e.includes(i.id))r[i.id]=n[0]?n[0].values[i.id]:null;else {var u="function"==typeof i.aggregate?i.aggregate:m[i.aggregate]||ke[i.aggregate];if(u){var l=n.map((function(e){return e.values[i.id]})),s=t.map((function(e){var t=e.values[i.id];if(!o&&i.aggregateValue){var n="function"==typeof i.aggregateValue?i.aggregateValue:m[i.aggregateValue]||ke[i.aggregateValue];if(!n)throw console.info({column:i}),new Error("React Table: Invalid column.aggregateValue option for column listed above");t=n(t,e,i);}return t}));r[i.id]=u(s,l);}else {if(i.aggregate)throw console.info({column:i}),new Error("React Table: Invalid column.aggregate option for column listed above");r[i.id]=null;}}})),r}(w,v,u),b={id:h,isGrouped:!0,groupByID:g,groupByVal:d,values:R,subRows:y,leafRows:w,depth:u,index:i};return y.forEach((function(e){t.push(e),n[e.id]=e,e.isGrouped?(l.push(e),a[e.id]=e):(c.push(e),f[e.id]=e);})),b}))}(o);return g.forEach((function(e){t.push(e),n[e.id]=e,e.isGrouped?(l.push(e),a[e.id]=e):(c.push(e),f[e.id]=e);})),[g,t,n,l,a,c,f]}),[p,R,o,i,u,s,m,d]),H=k[0],W=k[1],z=k[2],T=k[3],O=k[4],M=k[5],j=k[6],L=h(C);w((function(){L()&&b({type:l.resetGroupBy});}),[b,p?null:n]),Object.assign(e,{preGroupedRows:o,preGroupedFlatRow:i,preGroupedRowsById:u,groupedRows:H,groupedFlatRows:W,groupedRowsById:z,onlyGroupedFlatRows:T,onlyGroupedRowsById:O,nonGroupedFlatRows:M,nonGroupedRowsById:j,rows:H,flatRows:W,rowsById:z,toggleGroupBy:F,setGroupBy:A});}function Ne(e){e.allCells.forEach((function(t){var n;t.isGrouped=t.column.isGrouped&&t.column.id===e.groupByID,t.isPlaceholder=!t.isGrouped&&t.column.isGrouped,t.isAggregated=!t.isGrouped&&!t.isPlaceholder&&(null==(n=e.subRows)?void 0:n.length);}));}function De(e,t){return e.reduce((function(e,n,o){var r=""+n.values[t];return e[r]=Array.isArray(e[r])?e[r]:[],e[r].push(n),e}),{})}var Ve=/([0-9]+)/gm;function _e(e,t){return e===t?0:e>t?1:-1}function Xe(e,t,n){return [e.values[n],t.values[n]]}function qe(e){return "number"==typeof e?isNaN(e)||e===1/0||e===-1/0?"":String(e):"string"==typeof e?e:""}var Ke=Object.freeze({__proto__:null,alphanumeric:function(e,t,n){var o=Xe(e,t,n),r=o[0],i=o[1];for(r=qe(r),i=qe(i),r=r.split(Ve).filter(Boolean),i=i.split(Ve).filter(Boolean);r.length&&i.length;){var u=r.shift(),l=i.shift(),s=parseInt(u,10),a=parseInt(l,10),c=[s,a].sort();if(isNaN(c[0])){if(u>l)return 1;if(l>u)return -1}else {if(isNaN(c[1]))return isNaN(s)?-1:1;if(s>a)return 1;if(a>s)return -1}}return r.length-i.length},datetime:function(e,t,n){var o=Xe(e,t,n),r=o[0],i=o[1];return _e(r=r.getTime(),i=i.getTime())},basic:function(e,t,n){var o=Xe(e,t,n);return _e(o[0],o[1])},string:function(e,t,n){var o=Xe(e,t,n),r=o[0],i=o[1];for(r=r.split("").filter(Boolean),i=i.split("").filter(Boolean);r.length&&i.length;){var u=r.shift(),l=i.shift(),s=u.toLowerCase(),a=l.toLowerCase();if(s>a)return 1;if(a>s)return -1;if(u>l)return 1;if(l>u)return -1}return r.length-i.length},number:function(e,t,n){var o=Xe(e,t,n),r=o[0],i=o[1],u=/[^0-9.]/gi;return _e(r=Number(String(r).replace(u,"")),i=Number(String(i).replace(u,"")))}});l.resetSortBy="resetSortBy",l.setSortBy="setSortBy",l.toggleSortBy="toggleSortBy",l.clearSortBy="clearSortBy",c.sortType="alphanumeric",c.sortDescFirst=!1;var Ue=function(e){e.getSortByToggleProps=[$e],e.stateReducers.push(Je),e.useInstance.push(Ye);};Ue.pluginName="useSortBy";var $e=function(e,t){var n=t.instance,o=t.column,r=n.isMultiSortEvent,i=void 0===r?function(e){return e.shiftKey}:r;return [e,{onClick:o.canSort?function(e){e.persist(),o.toggleSortBy(void 0,!n.disableMultiSort&&i(e));}:void 0,style:{cursor:o.canSort?"pointer":void 0},title:o.canSort?"Toggle SortBy":void 0}]};function Je(e,t,n,o){if(t.type===l.init)return r({sortBy:[]},e);if(t.type===l.resetSortBy)return r({},e,{sortBy:o.initialState.sortBy||[]});if(t.type===l.clearSortBy)return r({},e,{sortBy:e.sortBy.filter((function(e){return e.id!==t.columnId}))});if(t.type===l.setSortBy)return r({},e,{sortBy:t.sortBy});if(t.type===l.toggleSortBy){var i,u=t.columnId,s=t.desc,a=t.multi,c=o.allColumns,d=o.disableMultiSort,f=o.disableSortRemove,p=o.disableMultiRemove,g=o.maxMultiSortColCount,v=void 0===g?Number.MAX_SAFE_INTEGER:g,m=e.sortBy,h=c.find((function(e){return e.id===u})).sortDescFirst,y=m.find((function(e){return e.id===u})),w=m.findIndex((function(e){return e.id===u})),R=null!=s,b=[];return "toggle"!==(i=!d&&a?y?"toggle":"add":w!==m.length-1||1!==m.length?"replace":y?"toggle":"replace")||f||R||a&&p||!(y&&y.desc&&!h||!y.desc&&h)||(i="remove"),"replace"===i?b=[{id:u,desc:R?s:h}]:"add"===i?(b=[].concat(m,[{id:u,desc:R?s:h}])).splice(0,b.length-v):"toggle"===i?b=m.map((function(e){return e.id===u?r({},e,{desc:R?s:!y.desc}):e})):"remove"===i&&(b=m.filter((function(e){return e.id!==u}))),r({},e,{sortBy:b})}}function Ye(e){var n=e.data,o=e.rows,r=e.flatRows,i=e.allColumns,u=e.orderByFn,s=void 0===u?Qe:u,a=e.sortTypes,c=e.manualSortBy,d=e.defaultCanSort,p=e.disableSortBy,g=e.flatHeaders,m=e.state.sortBy,y=e.dispatch,R=e.plugins,b=e.getHooks,S=e.autoResetSortBy,C=void 0===S||S;v(R,["useFilters","useGlobalFilter","useGroupBy","usePivotColumns"],"useSortBy");var x=t.useCallback((function(e){y({type:l.setSortBy,sortBy:e});}),[y]),P=t.useCallback((function(e,t,n){y({type:l.toggleSortBy,columnId:e,desc:t,multi:n});}),[y]),B=h(e);g.forEach((function(e){var t=e.accessor,n=e.canSort,o=e.disableSortBy,r=e.id,i=t?I(!0!==o&&void 0,!0!==p&&void 0,!0):I(d,n,!1);e.canSort=i,e.canSort&&(e.toggleSortBy=function(t,n){return P(e.id,t,n)},e.clearSortBy=function(){y({type:l.clearSortBy,columnId:e.id});}),e.getSortByToggleProps=f(b().getSortByToggleProps,{instance:B(),column:e});var u=m.find((function(e){return e.id===r}));e.isSorted=!!u,e.sortedIndex=m.findIndex((function(e){return e.id===r})),e.isSortedDesc=e.isSorted?u.desc:void 0;}));var E=t.useMemo((function(){if(c||!m.length)return [o,r];var e=[],t=m.filter((function(e){return i.find((function(t){return t.id===e.id}))}));return [function n(o){var r=s(o,t.map((function(e){var t=i.find((function(t){return t.id===e.id}));if(!t)throw new Error("React-Table: Could not find a column with id: "+e.id+" while sorting");var n=t.sortType,o=F(n)||(a||{})[n]||Ke[n];if(!o)throw new Error("React-Table: Could not find a valid sortType of '"+n+"' for column '"+e.id+"'.");return function(t,n){return o(t,n,e.id,e.desc)}})),t.map((function(e){var t=i.find((function(t){return t.id===e.id}));return t&&t.sortInverted?e.desc:!e.desc})));return r.forEach((function(t){e.push(t),t.subRows&&0!==t.subRows.length&&(t.subRows=n(t.subRows));})),r}(o),e]}),[c,m,o,r,i,s,a]),G=E[0],A=E[1],k=h(C);w((function(){k()&&y({type:l.resetSortBy});}),[c?null:n]),Object.assign(e,{preSortedRows:o,preSortedFlatRows:r,sortedRows:G,sortedFlatRows:A,rows:G,flatRows:A,setSortBy:x,toggleSortBy:P});}function Qe(e,t,n){return [].concat(e).sort((function(e,o){for(var r=0;re.pageIndex?a=-1===i?u.length>=e.pageSize:s-1),a?r({},e,{pageIndex:s}):e}if(t.type===l.setPageSize){var c=t.pageSize,d=e.pageSize*e.pageIndex;return r({},e,{pageIndex:Math.floor(d/c),pageSize:c})}}function tt(e){var n=e.rows,o=e.autoResetPage,r=void 0===o||o,i=e.manualExpandedKey,u=void 0===i?"expanded":i,s=e.plugins,a=e.pageCount,c=e.paginateExpandedRows,d=void 0===c||c,f=e.expandSubRows,p=void 0===f||f,g=e.state,m=g.pageSize,y=g.pageIndex,R=g.expanded,b=g.globalFilter,S=g.filters,C=g.groupBy,x=g.sortBy,P=e.dispatch,B=e.data,E=e.manualPagination;v(s,["useGlobalFilter","useFilters","useGroupBy","useSortBy","useExpanded"],"usePagination");var I=h(r);w((function(){I()&&P({type:l.resetPage});}),[P,E?null:B,b,S,C,x]);var F=E?a:Math.ceil(n.length/m),G=t.useMemo((function(){return F>0?[].concat(new Array(F)).fill(null).map((function(e,t){return t})):[]}),[F]),k=t.useMemo((function(){var e;if(E)e=n;else {var t=m*y,o=t+m;e=n.slice(t,o);}return d?e:A(e,{manualExpandedKey:u,expanded:R,expandSubRows:p})}),[p,R,u,E,y,m,d,n]),H=y>0,W=-1===F?k.length>=m:y-1&&i.push(r.splice(t,1)[0]);};r.length&&o.length;)u();return [].concat(i,r)}function At(e){var n=e.dispatch;e.setColumnOrder=t.useCallback((function(e){return n({type:l.setColumnOrder,columnOrder:e})}),[n]);}It.pluginName="useColumnOrder",c.canResize=!0,l.columnStartResizing="columnStartResizing",l.columnResizing="columnResizing",l.columnDoneResizing="columnDoneResizing",l.resetResize="resetResize";var kt=function(e){e.getResizerProps=[Ht],e.getHeaderProps.push({style:{position:"relative"}}),e.stateReducers.push(Wt),e.useInstance.push(Tt),e.useInstanceBeforeDimensions.push(zt);},Ht=function(e,t){var n=t.instance,o=t.header,r=n.dispatch,i=function(e,t){var n=!1;if("touchstart"===e.type){if(e.touches&&e.touches.length>1)return;n=!0;}var o,i,u=function(e){var t=[];return function e(n){n.columns&&n.columns.length&&n.columns.map(e);t.push(n);}(e),t}(t).map((function(e){return [e.id,e.totalWidth]})),s=n?Math.round(e.touches[0].clientX):e.clientX,a=function(){window.cancelAnimationFrame(o),o=null,r({type:l.columnDoneResizing});},c=function(){window.cancelAnimationFrame(o),o=null,r({type:l.columnResizing,clientX:i});},d=function(e){i=e,o||(o=window.requestAnimationFrame(c));},f={mouse:{moveEvent:"mousemove",moveHandler:function(e){return d(e.clientX)},upEvent:"mouseup",upHandler:function(e){document.removeEventListener("mousemove",f.mouse.moveHandler),document.removeEventListener("mouseup",f.mouse.upHandler),a();}},touch:{moveEvent:"touchmove",moveHandler:function(e){return e.cancelable&&(e.preventDefault(),e.stopPropagation()),d(e.touches[0].clientX),!1},upEvent:"touchend",upHandler:function(e){document.removeEventListener(f.touch.moveEvent,f.touch.moveHandler),document.removeEventListener(f.touch.upEvent,f.touch.moveHandler),a();}}},p=n?f.touch:f.mouse,g=!!function(){if("boolean"==typeof z)return z;var e=!1;try{var t={get passive(){return e=!0,!1}};window.addEventListener("test",null,t),window.removeEventListener("test",null,t);}catch(t){e=!1;}return z=e}()&&{passive:!1};document.addEventListener(p.moveEvent,p.moveHandler,g),document.addEventListener(p.upEvent,p.upHandler,g),r({type:l.columnStartResizing,columnId:t.id,columnWidth:t.totalWidth,headerIdWidths:u,clientX:s});};return [e,{onMouseDown:function(e){return e.persist()||i(e,o)},onTouchStart:function(e){return e.persist()||i(e,o)},style:{cursor:"col-resize"},draggable:!1,role:"separator"}]};function Wt(e,t){if(t.type===l.init)return r({columnResizing:{columnWidths:{}}},e);if(t.type===l.resetResize)return r({},e,{columnResizing:{columnWidths:{}}});if(t.type===l.columnStartResizing){var n=t.clientX,o=t.columnId,i=t.columnWidth,u=t.headerIdWidths;return r({},e,{columnResizing:r({},e.columnResizing,{startX:n,headerIdWidths:u,columnWidth:i,isResizingColumn:o})})}if(t.type===l.columnResizing){var s=t.clientX,a=e.columnResizing,c=a.startX,d=a.columnWidth,f=a.headerIdWidths,p=(s-c)/d,g={};return (void 0===f?[]:f).forEach((function(e){var t=e[0],n=e[1];g[t]=Math.max(n+n*p,0);})),r({},e,{columnResizing:r({},e.columnResizing,{columnWidths:r({},e.columnResizing.columnWidths,{},g)})})}return t.type===l.columnDoneResizing?r({},e,{columnResizing:r({},e.columnResizing,{startX:null,isResizingColumn:null})}):void 0}kt.pluginName="useResizeColumns";var zt=function(e){var t=e.flatHeaders,n=e.disableResizing,o=e.getHooks,r=e.state.columnResizing,i=h(e);t.forEach((function(e){var t=I(!0!==e.disableResizing&&void 0,!0!==n&&void 0,!0);e.canResize=t,e.width=r.columnWidths[e.id]||e.originalWidth||e.width,e.isResizing=r.isResizingColumn===e.id,t&&(e.getResizerProps=f(o().getResizerProps,{instance:i(),header:e}));}));};function Tt(e){var n=e.plugins,o=e.dispatch,r=e.autoResetResize,i=void 0===r||r,u=e.columns;v(n,["useAbsoluteLayout"],"useResizeColumns");var s=h(i);w((function(){s()&&o({type:l.resetResize});}),[u]);var a=t.useCallback((function(){return o({type:l.resetResize})}),[o]);Object.assign(e,{resetResizing:a});}var Ot={position:"absolute",top:0},Mt=function(e){e.getTableBodyProps.push(jt),e.getRowProps.push(jt),e.getHeaderGroupProps.push(jt),e.getFooterGroupProps.push(jt),e.getHeaderProps.push((function(e,t){var n=t.column;return [e,{style:r({},Ot,{left:n.totalLeft+"px",width:n.totalWidth+"px"})}]})),e.getCellProps.push((function(e,t){var n=t.cell;return [e,{style:r({},Ot,{left:n.column.totalLeft+"px",width:n.column.totalWidth+"px"})}]})),e.getFooterProps.push((function(e,t){var n=t.column;return [e,{style:r({},Ot,{left:n.totalLeft+"px",width:n.totalWidth+"px"})}]}));};Mt.pluginName="useAbsoluteLayout";var jt=function(e,t){return [e,{style:{position:"relative",width:t.instance.totalColumnsWidth+"px"}}]},Lt={display:"inline-block",boxSizing:"border-box"},Nt=function(e,t){return [e,{style:{display:"flex",width:t.instance.totalColumnsWidth+"px"}}]},Dt=function(e){e.getRowProps.push(Nt),e.getHeaderGroupProps.push(Nt),e.getFooterGroupProps.push(Nt),e.getHeaderProps.push((function(e,t){var n=t.column;return [e,{style:r({},Lt,{width:n.totalWidth+"px"})}]})),e.getCellProps.push((function(e,t){var n=t.cell;return [e,{style:r({},Lt,{width:n.column.totalWidth+"px"})}]})),e.getFooterProps.push((function(e,t){var n=t.column;return [e,{style:r({},Lt,{width:n.totalWidth+"px"})}]}));};function Vt(e){e.getTableProps.push(_t),e.getRowProps.push(Xt),e.getHeaderGroupProps.push(Xt),e.getFooterGroupProps.push(Xt),e.getHeaderProps.push(qt),e.getCellProps.push(Kt),e.getFooterProps.push(Ut);}Dt.pluginName="useBlockLayout",Vt.pluginName="useFlexLayout";var _t=function(e,t){return [e,{style:{minWidth:t.instance.totalColumnsMinWidth+"px"}}]},Xt=function(e,t){return [e,{style:{display:"flex",flex:"1 0 auto",minWidth:t.instance.totalColumnsMinWidth+"px"}}]},qt=function(e,t){var n=t.column;return [e,{style:{boxSizing:"border-box",flex:n.totalFlexWidth?n.totalFlexWidth+" 0 auto":void 0,minWidth:n.totalMinWidth+"px",width:n.totalWidth+"px"}}]},Kt=function(e,t){var n=t.cell;return [e,{style:{boxSizing:"border-box",flex:n.column.totalFlexWidth+" 0 auto",minWidth:n.column.totalMinWidth+"px",width:n.column.totalWidth+"px"}}]},Ut=function(e,t){var n=t.column;return [e,{style:{boxSizing:"border-box",flex:n.totalFlexWidth?n.totalFlexWidth+" 0 auto":void 0,minWidth:n.totalMinWidth+"px",width:n.totalWidth+"px"}}]};function $t(e){e.stateReducers.push(Zt),e.getTableProps.push(Jt),e.getHeaderProps.push(Yt),e.getRowProps.push(Qt);}l.columnStartResizing="columnStartResizing",l.columnResizing="columnResizing",l.columnDoneResizing="columnDoneResizing",l.resetResize="resetResize",$t.pluginName="useGridLayout";var Jt=function(e,t){var n=t.instance;return [e,{style:{display:"grid",gridTemplateColumns:n.visibleColumns.map((function(e){var t;return n.state.gridLayout.columnWidths[e.id]?n.state.gridLayout.columnWidths[e.id]+"px":(null==(t=n.state.columnResizing)?void 0:t.isResizingColumn)?n.state.gridLayout.startWidths[e.id]+"px":"number"==typeof e.width?e.width+"px":e.width})).join(" ")}}]},Yt=function(e,t){var n=t.column;return [e,{id:"header-cell-"+n.id,style:{position:"sticky",gridColumn:"span "+n.totalVisibleHeaderCount}}]},Qt=function(e,t){var n=t.row;return n.isExpanded?[e,{style:{gridColumn:"1 / "+(n.cells.length+1)}}]:[e,{}]};function Zt(e,t,n,o){if(t.type===l.init)return r({gridLayout:{columnWidths:{}}},e);if(t.type===l.resetResize)return r({},e,{gridLayout:{columnWidths:{}}});if(t.type===l.columnStartResizing){var i=t.columnId,u=t.headerIdWidths,s=en(i);if(void 0!==s){var a=o.visibleColumns.reduce((function(e,t){var n;return r({},e,((n={})[t.id]=en(t.id),n))}),{}),c=o.visibleColumns.reduce((function(e,t){var n;return r({},e,((n={})[t.id]=t.minWidth,n))}),{}),d=o.visibleColumns.reduce((function(e,t){var n;return r({},e,((n={})[t.id]=t.maxWidth,n))}),{}),f=u.map((function(e){var t=e[0];return [t,en(t)]}));return r({},e,{gridLayout:r({},e.gridLayout,{startWidths:a,minWidths:c,maxWidths:d,headerIdGridWidths:f,columnWidth:s})})}return e}if(t.type===l.columnResizing){var p=t.clientX,g=e.columnResizing.startX,v=e.gridLayout,m=v.columnWidth,h=v.minWidths,y=v.maxWidths,w=v.headerIdGridWidths,R=(p-g)/m,b={};return (void 0===w?[]:w).forEach((function(e){var t=e[0],n=e[1];b[t]=Math.min(Math.max(h[t],n+n*R),y[t]);})),r({},e,{gridLayout:r({},e.gridLayout,{columnWidths:r({},e.gridLayout.columnWidths,{},b)})})}return t.type===l.columnDoneResizing?r({},e,{gridLayout:r({},e.gridLayout,{startWidths:{},minWidths:{},maxWidths:{}})}):void 0}function en(e){var t,n=null==(t=document.getElementById("header-cell-"+e))?void 0:t.offsetWidth;if(void 0!==n)return n}e._UNSTABLE_usePivotColumns=nt,e.actions=l,e.defaultColumn=c,e.defaultGroupByFn=De,e.defaultOrderByFn=Qe,e.defaultRenderer=s,e.emptyRenderer=a,e.ensurePluginOrder=v,e.flexRender=b,e.functionalUpdate=m,e.loopHooks=g,e.makePropGetter=f,e.makeRenderer=R,e.reduceHooks=p,e.safeUseLayoutEffect=y,e.useAbsoluteLayout=Mt,e.useAsyncDebounce=function(e,n){void 0===n&&(n=0);var r=t.useRef({}),i=h(e),u=h(n);return t.useCallback(function(){var e=o(regeneratorRuntime.mark((function e(){var t,n,l,s=arguments;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:for(t=s.length,n=new Array(t),l=0;l1?n-1:0),i=1;i value === null || value === undefined; + +// eslint-disable-next-line unicorn/prefer-code-point +const strictUriEncode = string => encodeURIComponent(string).replace(/[!'()*]/g, x => `%${x.charCodeAt(0).toString(16).toUpperCase()}`); + +const encodeFragmentIdentifier = Symbol('encodeFragmentIdentifier'); + +function encoderForArrayFormat(options) { + switch (options.arrayFormat) { + case 'index': { + return key => (result, value) => { + const index = result.length; + + if ( + value === undefined + || (options.skipNull && value === null) + || (options.skipEmptyString && value === '') + ) { + return result; + } + + if (value === null) { + return [ + ...result, [encode(key, options), '[', index, ']'].join(''), + ]; + } + + return [ + ...result, + [encode(key, options), '[', encode(index, options), ']=', encode(value, options)].join(''), + ]; + }; + } + + case 'bracket': { + return key => (result, value) => { + if ( + value === undefined + || (options.skipNull && value === null) + || (options.skipEmptyString && value === '') + ) { + return result; + } + + if (value === null) { + return [ + ...result, + [encode(key, options), '[]'].join(''), + ]; + } + + return [ + ...result, + [encode(key, options), '[]=', encode(value, options)].join(''), + ]; + }; + } + + case 'colon-list-separator': { + return key => (result, value) => { + if ( + value === undefined + || (options.skipNull && value === null) + || (options.skipEmptyString && value === '') + ) { + return result; + } + + if (value === null) { + return [ + ...result, + [encode(key, options), ':list='].join(''), + ]; + } + + return [ + ...result, + [encode(key, options), ':list=', encode(value, options)].join(''), + ]; + }; + } + + case 'comma': + case 'separator': + case 'bracket-separator': { + const keyValueSep = options.arrayFormat === 'bracket-separator' + ? '[]=' + : '='; + + return key => (result, value) => { + if ( + value === undefined + || (options.skipNull && value === null) + || (options.skipEmptyString && value === '') + ) { + return result; + } + + // Translate null to an empty string so that it doesn't serialize as 'null' + value = value === null ? '' : value; + + if (result.length === 0) { + return [[encode(key, options), keyValueSep, encode(value, options)].join('')]; + } + + return [[result, encode(value, options)].join(options.arrayFormatSeparator)]; + }; + } + + default: { + return key => (result, value) => { + if ( + value === undefined + || (options.skipNull && value === null) + || (options.skipEmptyString && value === '') + ) { + return result; + } + + if (value === null) { + return [ + ...result, + encode(key, options), + ]; + } + + return [ + ...result, + [encode(key, options), '=', encode(value, options)].join(''), + ]; + }; + } + } +} + +function parserForArrayFormat(options) { + let result; + + switch (options.arrayFormat) { + case 'index': { + return (key, value, accumulator) => { + result = /\[(\d*)]$/.exec(key); + + key = key.replace(/\[\d*]$/, ''); + + if (!result) { + accumulator[key] = value; + return; + } + + if (accumulator[key] === undefined) { + accumulator[key] = {}; + } + + accumulator[key][result[1]] = value; + }; + } + + case 'bracket': { + return (key, value, accumulator) => { + result = /(\[])$/.exec(key); + key = key.replace(/\[]$/, ''); + + if (!result) { + accumulator[key] = value; + return; + } + + if (accumulator[key] === undefined) { + accumulator[key] = [value]; + return; + } + + accumulator[key] = [...accumulator[key], value]; + }; + } + + case 'colon-list-separator': { + return (key, value, accumulator) => { + result = /(:list)$/.exec(key); + key = key.replace(/:list$/, ''); + + if (!result) { + accumulator[key] = value; + return; + } + + if (accumulator[key] === undefined) { + accumulator[key] = [value]; + return; + } + + accumulator[key] = [...accumulator[key], value]; + }; + } + + case 'comma': + case 'separator': { + return (key, value, accumulator) => { + const isArray = typeof value === 'string' && value.includes(options.arrayFormatSeparator); + const isEncodedArray = (typeof value === 'string' && !isArray && decode(value, options).includes(options.arrayFormatSeparator)); + value = isEncodedArray ? decode(value, options) : value; + const newValue = isArray || isEncodedArray ? value.split(options.arrayFormatSeparator).map(item => decode(item, options)) : (value === null ? value : decode(value, options)); + accumulator[key] = newValue; + }; + } + + case 'bracket-separator': { + return (key, value, accumulator) => { + const isArray = /(\[])$/.test(key); + key = key.replace(/\[]$/, ''); + + if (!isArray) { + accumulator[key] = value ? decode(value, options) : value; + return; + } + + const arrayValue = value === null + ? [] + : value.split(options.arrayFormatSeparator).map(item => decode(item, options)); + + if (accumulator[key] === undefined) { + accumulator[key] = arrayValue; + return; + } + + accumulator[key] = [...accumulator[key], ...arrayValue]; + }; + } + + default: { + return (key, value, accumulator) => { + if (accumulator[key] === undefined) { + accumulator[key] = value; + return; + } + + accumulator[key] = [...[accumulator[key]].flat(), value]; + }; + } + } +} + +function validateArrayFormatSeparator(value) { + if (typeof value !== 'string' || value.length !== 1) { + throw new TypeError('arrayFormatSeparator must be single character string'); + } +} + +function encode(value, options) { + if (options.encode) { + return options.strict ? strictUriEncode(value) : encodeURIComponent(value); + } + + return value; +} + +function decode(value, options) { + if (options.decode) { + return decodeUriComponent(value); + } + + return value; +} + +function keysSorter(input) { + if (Array.isArray(input)) { + return input.sort(); + } + + if (typeof input === 'object') { + return keysSorter(Object.keys(input)) + .sort((a, b) => Number(a) - Number(b)) + .map(key => input[key]); + } + + return input; +} + +function removeHash(input) { + const hashStart = input.indexOf('#'); + if (hashStart !== -1) { + input = input.slice(0, hashStart); + } + + return input; +} + +function getHash(url) { + let hash = ''; + const hashStart = url.indexOf('#'); + if (hashStart !== -1) { + hash = url.slice(hashStart); + } + + return hash; +} + +function parseValue(value, options) { + if (options.parseNumbers && !Number.isNaN(Number(value)) && (typeof value === 'string' && value.trim() !== '')) { + value = Number(value); + } else if (options.parseBooleans && value !== null && (value.toLowerCase() === 'true' || value.toLowerCase() === 'false')) { + value = value.toLowerCase() === 'true'; + } + + return value; +} + +function extract(input) { + input = removeHash(input); + const queryStart = input.indexOf('?'); + if (queryStart === -1) { + return ''; + } + + return input.slice(queryStart + 1); +} + +function parse$2(query, options) { + options = { + decode: true, + sort: true, + arrayFormat: 'none', + arrayFormatSeparator: ',', + parseNumbers: false, + parseBooleans: false, + ...options, + }; + + validateArrayFormatSeparator(options.arrayFormatSeparator); + + const formatter = parserForArrayFormat(options); + + // Create an object with no prototype + const returnValue = Object.create(null); + + if (typeof query !== 'string') { + return returnValue; + } + + query = query.trim().replace(/^[?#&]/, ''); + + if (!query) { + return returnValue; + } + + for (const parameter of query.split('&')) { + if (parameter === '') { + continue; + } + + const parameter_ = options.decode ? parameter.replace(/\+/g, ' ') : parameter; + + let [key, value] = splitOnFirst(parameter_, '='); + + if (key === undefined) { + key = parameter_; + } + + // Missing `=` should be `null`: + // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters + value = value === undefined ? null : (['comma', 'separator', 'bracket-separator'].includes(options.arrayFormat) ? value : decode(value, options)); + formatter(decode(key, options), value, returnValue); + } + + for (const [key, value] of Object.entries(returnValue)) { + if (typeof value === 'object' && value !== null) { + for (const [key2, value2] of Object.entries(value)) { + value[key2] = parseValue(value2, options); + } + } else { + returnValue[key] = parseValue(value, options); + } + } + + if (options.sort === false) { + return returnValue; + } + + // TODO: Remove the use of `reduce`. + // eslint-disable-next-line unicorn/no-array-reduce + return (options.sort === true ? Object.keys(returnValue).sort() : Object.keys(returnValue).sort(options.sort)).reduce((result, key) => { + const value = returnValue[key]; + if (Boolean(value) && typeof value === 'object' && !Array.isArray(value)) { + // Sort object keys, not values + result[key] = keysSorter(value); + } else { + result[key] = value; + } + + return result; + }, Object.create(null)); +} + +function stringify(object, options) { + if (!object) { + return ''; + } + + options = {encode: true, + strict: true, + arrayFormat: 'none', + arrayFormatSeparator: ',', ...options}; + + validateArrayFormatSeparator(options.arrayFormatSeparator); + + const shouldFilter = key => ( + (options.skipNull && isNullOrUndefined(object[key])) + || (options.skipEmptyString && object[key] === '') + ); + + const formatter = encoderForArrayFormat(options); + + const objectCopy = {}; + + for (const [key, value] of Object.entries(object)) { + if (!shouldFilter(key)) { + objectCopy[key] = value; + } + } + + const keys = Object.keys(objectCopy); + + if (options.sort !== false) { + keys.sort(options.sort); + } + + return keys.map(key => { + const value = object[key]; + + if (value === undefined) { + return ''; + } + + if (value === null) { + return encode(key, options); + } + + if (Array.isArray(value)) { + if (value.length === 0 && options.arrayFormat === 'bracket-separator') { + return encode(key, options) + '[]'; + } + + return value + .reduce(formatter(key), []) + .join('&'); + } + + return encode(key, options) + '=' + encode(value, options); + }).filter(x => x.length > 0).join('&'); +} + +function parseUrl(url, options) { + options = { + decode: true, + ...options, + }; + + let [url_, hash] = splitOnFirst(url, '#'); + + if (url_ === undefined) { + url_ = url; + } + + return { + url: url_?.split('?')?.[0] ?? '', + query: parse$2(extract(url), options), + ...(options && options.parseFragmentIdentifier && hash ? {fragmentIdentifier: decode(hash, options)} : {}), + }; +} + +function stringifyUrl(object, options) { + options = { + encode: true, + strict: true, + [encodeFragmentIdentifier]: true, + ...options, + }; + + const url = removeHash(object.url).split('?')[0] || ''; + const queryFromUrl = extract(object.url); + + const query = { + ...parse$2(queryFromUrl, {sort: false}), + ...object.query, + }; + + let queryString = stringify(query, options); + if (queryString) { + queryString = `?${queryString}`; + } + + let hash = getHash(object.url); + if (object.fragmentIdentifier) { + const urlObjectForFragmentEncode = new URL(url); + urlObjectForFragmentEncode.hash = object.fragmentIdentifier; + hash = options[encodeFragmentIdentifier] ? urlObjectForFragmentEncode.hash : `#${object.fragmentIdentifier}`; + } + + return `${url}${queryString}${hash}`; +} + +function pick(input, filter, options) { + options = { + parseFragmentIdentifier: true, + [encodeFragmentIdentifier]: false, + ...options, + }; + + const {url, query, fragmentIdentifier} = parseUrl(input, options); + + return stringifyUrl({ + url, + query: includeKeys(query, filter), + fragmentIdentifier, + }, options); +} + +function exclude(input, filter, options) { + const exclusionFilter = Array.isArray(filter) ? key => !filter.includes(key) : (key, value) => !filter(key, value); + + return pick(input, exclusionFilter, options); +} + +var queryString = /*#__PURE__*/Object.freeze({ + __proto__: null, + exclude: exclude, + extract: extract, + parse: parse$2, + parseUrl: parseUrl, + pick: pick, + stringify: stringify, + stringifyUrl: stringifyUrl +}); + +var asctime = function (duration) { + var milliseconds = parseInt("".concat((duration % 1000) / 100), 10), seconds = Math.floor((duration / 1000) % 60), minutes = Math.floor((duration / (1000 * 60)) % 60), hours = Math.floor((duration / (1000 * 60 * 60)) % 24); + var hours_ = hours < 10 ? '0' + hours : hours; + var minutes_ = minutes < 10 ? '0' + minutes : minutes; + var seconds_ = seconds < 10 ? '0' + seconds : seconds; + return hours_ + ':' + minutes_ + ':' + seconds_ + '.' + milliseconds; +}; +var SETTINGS_KEY = 'minimal-history-plugin'; +var loadSettings = function () { + var parsed = queryString.parse(location.hash.substring(location.hash.split('?', 1)[0].length + 1)); + try { + var raw = JSON.parse(localStorage.getItem(SETTINGS_KEY) || '{}'); + return { + showHistoricBadges: !!(raw === null || raw === void 0 ? void 0 : raw.showHistoricBadges) || !!parsed.showHistoricBadges, + showSequenceFlow: !!(raw === null || raw === void 0 ? void 0 : raw.showSequenceFlow) || !!parsed.showSequenceFlow, + leftPaneSize: !!(raw === null || raw === void 0 ? void 0 : raw.leftPaneSize) ? raw.leftPaneSize : null, + topPaneSize: !!(raw === null || raw === void 0 ? void 0 : raw.topPaneSize) ? raw.topPaneSize : null, + }; + } + catch (e) { + return { + showHistoricBadges: false, + showSequenceFlow: false, + leftPaneSize: null, + topPaneSize: null, + }; + } +}; +var saveSettings = function (settings) { + localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings)); +}; + +var Component = {}; + +var toggleSelection = function () { + var selection = document.getSelection(); + if (!selection.rangeCount) { + return function () {}; + } + var active = document.activeElement; + + var ranges = []; + for (var i = 0; i < selection.rangeCount; i++) { + ranges.push(selection.getRangeAt(i)); + } + + switch (active.tagName.toUpperCase()) { // .toUpperCase handles XHTML + case 'INPUT': + case 'TEXTAREA': + active.blur(); + break; + + default: + active = null; + break; + } + + selection.removeAllRanges(); + return function () { + selection.type === 'Caret' && + selection.removeAllRanges(); + + if (!selection.rangeCount) { + ranges.forEach(function(range) { + selection.addRange(range); + }); + } + + active && + active.focus(); + }; +}; + +var deselectCurrent = toggleSelection; + +var clipboardToIE11Formatting = { + "text/plain": "Text", + "text/html": "Url", + "default": "Text" +}; + +var defaultMessage = "Copy to clipboard: #{key}, Enter"; + +function format(message) { + var copyKey = (/mac os x/i.test(navigator.userAgent) ? "⌘" : "Ctrl") + "+C"; + return message.replace(/#{\s*key\s*}/g, copyKey); +} + +function copy(text, options) { + var debug, + message, + reselectPrevious, + range, + selection, + mark, + success = false; + if (!options) { + options = {}; + } + debug = options.debug || false; + try { + reselectPrevious = deselectCurrent(); + + range = document.createRange(); + selection = document.getSelection(); + + mark = document.createElement("span"); + mark.textContent = text; + // avoid screen readers from reading out loud the text + mark.ariaHidden = "true"; + // reset user styles for span element + mark.style.all = "unset"; + // prevents scrolling to the end of the page + mark.style.position = "fixed"; + mark.style.top = 0; + mark.style.clip = "rect(0, 0, 0, 0)"; + // used to preserve spaces and line breaks + mark.style.whiteSpace = "pre"; + // do not inherit user-select (it may be `none`) + mark.style.webkitUserSelect = "text"; + mark.style.MozUserSelect = "text"; + mark.style.msUserSelect = "text"; + mark.style.userSelect = "text"; + mark.addEventListener("copy", function(e) { + e.stopPropagation(); + if (options.format) { + e.preventDefault(); + if (typeof e.clipboardData === "undefined") { // IE 11 + debug && console.warn("unable to use e.clipboardData"); + debug && console.warn("trying IE specific stuff"); + window.clipboardData.clearData(); + var format = clipboardToIE11Formatting[options.format] || clipboardToIE11Formatting["default"]; + window.clipboardData.setData(format, text); + } else { // all other browsers + e.clipboardData.clearData(); + e.clipboardData.setData(options.format, text); + } + } + if (options.onCopy) { + e.preventDefault(); + options.onCopy(e.clipboardData); + } + }); + + document.body.appendChild(mark); + + range.selectNodeContents(mark); + selection.addRange(range); + + var successful = document.execCommand("copy"); + if (!successful) { + throw new Error("copy command was unsuccessful"); + } + success = true; + } catch (err) { + debug && console.error("unable to copy using execCommand: ", err); + debug && console.warn("trying IE specific stuff"); + try { + window.clipboardData.setData(options.format || "text", text); + options.onCopy && options.onCopy(window.clipboardData); + success = true; + } catch (err) { + debug && console.error("unable to copy using clipboardData: ", err); + debug && console.error("falling back to prompt"); + message = format("message" in options ? options.message : defaultMessage); + window.prompt(message, text); + } + } finally { + if (selection) { + if (typeof selection.removeRange == "function") { + selection.removeRange(range); + } else { + selection.removeAllRanges(); + } + } + + if (mark) { + document.body.removeChild(mark); + } + reselectPrevious(); + } + + return success; +} + +var copyToClipboard = copy; + +function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } + +Object.defineProperty(Component, "__esModule", { + value: true +}); +Component.CopyToClipboard = void 0; + +var _react = _interopRequireDefault(reactExports); + +var _copyToClipboard = _interopRequireDefault(copyToClipboard); + +var _excluded = ["text", "onCopy", "options", "children"]; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } + +function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } + +function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +var CopyToClipboard$2 = /*#__PURE__*/function (_React$PureComponent) { + _inherits(CopyToClipboard, _React$PureComponent); + + var _super = _createSuper(CopyToClipboard); + + function CopyToClipboard() { + var _this; + + _classCallCheck(this, CopyToClipboard); + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + _this = _super.call.apply(_super, [this].concat(args)); + + _defineProperty(_assertThisInitialized(_this), "onClick", function (event) { + var _this$props = _this.props, + text = _this$props.text, + onCopy = _this$props.onCopy, + children = _this$props.children, + options = _this$props.options; + + var elem = _react["default"].Children.only(children); + + var result = (0, _copyToClipboard["default"])(text, options); + + if (onCopy) { + onCopy(text, result); + } // Bypass onClick if it was present + + + if (elem && elem.props && typeof elem.props.onClick === 'function') { + elem.props.onClick(event); + } + }); + + return _this; + } + + _createClass(CopyToClipboard, [{ + key: "render", + value: function render() { + var _this$props2 = this.props; + _this$props2.text; + _this$props2.onCopy; + _this$props2.options; + var children = _this$props2.children, + props = _objectWithoutProperties(_this$props2, _excluded); + + var elem = _react["default"].Children.only(children); + + return /*#__PURE__*/_react["default"].cloneElement(elem, _objectSpread(_objectSpread({}, props), {}, { + onClick: this.onClick + })); + } + }]); + + return CopyToClipboard; +}(_react["default"].PureComponent); + +Component.CopyToClipboard = CopyToClipboard$2; + +_defineProperty(CopyToClipboard$2, "defaultProps", { + onCopy: undefined, + options: undefined +}); + +var _require = Component, + CopyToClipboard = _require.CopyToClipboard; + +CopyToClipboard.CopyToClipboard = CopyToClipboard; +var lib = CopyToClipboard; + +var CopyToClipboard$1 = /*@__PURE__*/getDefaultExportFromCjs(lib); + +// THIS FILE IS AUTO GENERATED +function HiCheck (props) { + return GenIcon({"tag":"svg","attr":{"viewBox":"0 0 20 20","fill":"currentColor","aria-hidden":"true"},"child":[{"tag":"path","attr":{"fillRule":"evenodd","d":"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z","clipRule":"evenodd"}}]})(props); +}function HiClipboardCopy (props) { + return GenIcon({"tag":"svg","attr":{"viewBox":"0 0 20 20","fill":"currentColor","aria-hidden":"true"},"child":[{"tag":"path","attr":{"d":"M8 2a1 1 0 000 2h2a1 1 0 100-2H8z"}},{"tag":"path","attr":{"d":"M3 5a2 2 0 012-2 3 3 0 003 3h2a3 3 0 003-3 2 2 0 012 2v6h-4.586l1.293-1.293a1 1 0 00-1.414-1.414l-3 3a1 1 0 000 1.414l3 3a1 1 0 001.414-1.414L10.414 13H15v3a2 2 0 01-2 2H5a2 2 0 01-2-2V5zM15 11h2a1 1 0 110 2h-2v-2z"}}]})(props); +} + +var Clippy = function (_a) { + var value = _a.value, children = _a.children; + var _b = reactExports.useState(false), mouseOver = _b[0], setMouseOver = _b[1]; + var _c = reactExports.useState(false), copied = _c[0], setCopied = _c[1]; + return (React.createElement("span", { onMouseOver: function () { + if (!mouseOver) { + setMouseOver(true); + } + }, onMouseLeave: function () { + setMouseOver(false); + setCopied(false); + }, style: { display: 'flex', alignItems: 'center' } }, + children, + mouseOver ? (React.createElement(CopyToClipboard$1, { text: value, onCopy: function () { return setCopied(true); } }, + React.createElement("a", { href: "#", onClick: function (e) { + e.preventDefault(); + }, style: { fontSize: '120%', paddingLeft: '0.2em' } }, copied ? (React.createElement(HiCheck, { style: { color: 'green', display: 'flex' } })) : (React.createElement(HiClipboardCopy, { style: { display: 'flex' } }))))) : (React.createElement("span", { style: { fontSize: '120%', width: '1.2em' } })))); +}; + +var AuditLogTable = function (_a) { + var activities = _a.activities, decisions = _a.decisions; + var columns = React.useMemo(function () { return [ + { + Header: 'Activity Name', + accessor: 'activityName', + Cell: function (_a) { + var value = _a.value; + var baseUrl = "".concat(window.location.href.split('#')[0], "/") + .replace(/\/+$/, '/') + .replace(/\/app\/tasklist\//, '/app/cockpit/'); + if (value.activityType === 'businessRuleTask' && decisions.has(value.id)) { + return React.createElement("a", { href: "".concat(baseUrl, "#/decision-instance/").concat(decisions.get(value.id)) }, value.activityName); + } + else if (value.activityType === 'callActivity' && value.calledProcessInstanceId && value.endTime) { + return (React.createElement("a", { href: "".concat(baseUrl, "#/history/process-instance/").concat(value.calledProcessInstanceId) }, value.activityName)); + } + else if (value.activityType === 'callActivity' && value.calledProcessInstanceId) { + return (React.createElement("a", { href: "".concat(baseUrl, "#/process-instance/").concat(value.calledProcessInstanceId, "/runtime") }, value.activityName)); + } + return React.createElement(Clippy, { value: value.activityName }, value.activityName); + }, + }, + { + Header: 'Start Time', + accessor: 'startDate', + Cell: function (_a) { + var value = _a.value; + return (React.createElement(Clippy, { value: value ? value.format('YYYY-MM-DDTHH:mm:ss') : value }, value ? value.format('YYYY-MM-DDTHH:mm:ss') : value)); + }, + }, + { + Header: 'End Time', + accessor: 'endDate', + Cell: function (_a) { + var value = _a.value; + return (React.createElement(Clippy, { value: value ? value.format('YYYY-MM-DDTHH:mm:ss') : value }, value ? value.format('YYYY-MM-DDTHH:mm:ss') : value)); + }, + }, + { + Header: 'Duration', + accessor: 'duration', + Cell: function (_a) { + var value = _a.value; + return React.createElement(Clippy, { value: value }, value); + }, + }, + { + Header: 'Type', + accessor: 'type', + Cell: function (_a) { + var value = _a.value; + return React.createElement(Clippy, { value: value }, value); + }, + }, + { + Header: 'User', + accessor: 'assignee', + Cell: function (_a) { + var value = _a.value; + return React.createElement(Clippy, { value: value }, value); + }, + }, + { + Header: 'Canceled', + accessor: 'canceled', + Cell: function (_a) { + var value = _a.value; + return React.createElement(Clippy, { value: value }, value); + }, + }, + ]; }, [activities, decisions]); + var data = React.useMemo(function () { + return activities.map(function (activity) { + return { + activityName: activity, + startDate: moment(activity.startTime), + endDate: activity.endTime ? moment(activity.endTime) : '', + duration: activity.endTime + ? asctime(new Date(activity.endTime).getTime() - new Date(activity.startTime).getTime()) + : '', + type: activity.activityType, + assignee: activity.assignee, + canceled: activity.canceled ? 'true' : 'false', + }; + }); + }, [activities, decisions]); + var tableInstance = reactTableExports.useTable({ columns: columns, data: data }, reactTableExports.useSortBy); + var getTableProps = tableInstance.getTableProps, getTableBodyProps = tableInstance.getTableBodyProps, headerGroups = tableInstance.headerGroups, rows = tableInstance.rows, prepareRow = tableInstance.prepareRow; + return (React.createElement("table", __assign$1({ className: "cam-table" }, getTableProps()), + React.createElement("thead", null, headerGroups.map(function (headerGroup) { return (React.createElement("tr", __assign$1({}, headerGroup.getHeaderGroupProps()), headerGroup.headers.map(function (column) { return ( + /* @ts-ignore */ + React.createElement("th", __assign$1({}, column.getHeaderProps(column.getSortByToggleProps())), + column.render('Header'), + React.createElement("span", { style: { position: 'absolute', fontSize: '125%' } }, + /* @ts-ignore */ + column.isSorted ? ( + /* @ts-ignore */ + column.isSortedDesc ? (React.createElement(GoChevronDown, { style: { color: '#155cb5' } })) : (React.createElement(GoChevronUp, { style: { color: '#155cb5' } }))) : (React.createElement(TiMinus, { style: { color: '#155cb5' } }))))); }))); })), + React.createElement("tbody", __assign$1({}, getTableBodyProps()), rows.map(function (row) { + prepareRow(row); + return (React.createElement("tr", __assign$1({}, row.getRowProps()), row.cells.map(function (cell) { + return React.createElement("td", __assign$1({}, cell.getCellProps()), cell.render('Cell')); + }))); + })))); +}; + +___$insertStylesToHeader(".toggle-sequence-flow-button {\n background: #ffffff;\n border-radius: 1px;\n border: 1px solid #cccccc;\n padding: 0;\n width: 30px;\n height: 30px;\n display: flex;\n margin-bottom: 15px;\n align-items: center;\n justify-content: center;\n}\n.toggle-sequence-flow-button:hover {\n background: #e6e6e6;\n}"); + +// THIS FILE IS AUTO GENERATED +function GiStrikingArrows (props) { + return GenIcon({"tag":"svg","attr":{"viewBox":"0 0 512 512"},"child":[{"tag":"path","attr":{"d":"M136.564 31.01l239.67 149.595c-12.418 21.234-20.756 28.302-45.027 46.936l156.3-26.33-85.603-125.474c4.936 24.85 8.85 38.5.75 60.49L136.568 31.01h-.004zM21.524 42.75l83.13 325.893c-21.017 5.232-30.98 3.262-58.875-3.96l124.046 113.45 13.426-166.844c-10.836 23.322-15.94 37.197-34.342 46.82L21.523 42.75zm64.353.215l252.2 353.16c-23.285 16.947-36.38 19.583-73.83 24.9l200.66 71.74L407.7 286.944c-2.477 33.743-2.313 53.14-20.37 74.09L85.877 42.965z"}}]})(props); +} + +var ToggleSequenceFlowButton = function (_a) { + var onToggleSequenceFlow = _a.onToggleSequenceFlow; + var _b = reactExports.useState(loadSettings().showSequenceFlow), showSequenceFlow = _b[0], setShowSequenceFlow = _b[1]; + reactExports.useEffect(function () { + onToggleSequenceFlow(showSequenceFlow); + saveSettings(__assign$1(__assign$1({}, loadSettings()), { showSequenceFlow: showSequenceFlow })); + }, [showSequenceFlow]); + return (React.createElement("button", { className: "toggle-sequence-flow-button", title: !showSequenceFlow ? 'Show sequence flow' : 'Hide sequence flow', "aria-label": !showSequenceFlow ? 'Show sequence flow' : 'Hide sequence flow', onClick: function () { return setShowSequenceFlow(!showSequenceFlow); } }, + React.createElement(GiStrikingArrows, { style: { opacity: !showSequenceFlow ? '0.33' : '1.0', fontSize: '133%' } }))); +}; + +var headers = function (api) { + return { + Accept: 'application/json', + 'Content-Type': 'application/json', + 'X-XSRF-TOKEN': api.CSRFToken, + }; +}; +var get = function (api, path, params) { return __awaiter(void 0, void 0, void 0, function () { + var query, res, _a, _b, _c, _d, _e, _f, _g; + return __generator(this, function (_h) { + switch (_h.label) { + case 0: + // XXX: Workaround a possible bug where engine api has been parsed wrong + if (api.engine.match(/\/#\//)) { + api.engine = api.engine.split('/#/')[0].replace(/.*\//g, ''); + api.engineApi = api.baseApi + '/engine/' + api.engine; + } + params = params || {}; + if (['/history/activity-instance', '/history/variable-instance', '/history/decision-instance'].includes(path) && + !(params === null || params === void 0 ? void 0 : params.maxResults)) { + params.maxResults = '1000'; + } + query = new URLSearchParams(params).toString(); + if (!query) return [3 /*break*/, 2]; + return [4 /*yield*/, fetch("".concat(api.engineApi).concat(path, "?").concat(query), { + method: 'get', + headers: headers(api), + })]; + case 1: + _a = _h.sent(); + return [3 /*break*/, 4]; + case 2: return [4 /*yield*/, fetch("".concat(api.engineApi).concat(path), { + method: 'get', + headers: headers(api), + })]; + case 3: + _a = _h.sent(); + _h.label = 4; + case 4: + res = _a; + if (!(res.status === 200 && (res.headers.get('Content-Type') || '').startsWith('application/json'))) return [3 /*break*/, 6]; + return [4 /*yield*/, res.json()]; + case 5: return [2 /*return*/, _h.sent()]; + case 6: + if (!(res.headers.get('Content-Type') || '').startsWith('application/json')) return [3 /*break*/, 8]; + _c = (_b = console).debug; + _d = [res.status, path]; + return [4 /*yield*/, res.json()]; + case 7: + _c.apply(_b, _d.concat([_h.sent()])); + return [3 /*break*/, 10]; + case 8: + _f = (_e = console).debug; + _g = [res.status, path]; + return [4 /*yield*/, res.text()]; + case 9: + _f.apply(_e, _g.concat([_h.sent()])); + _h.label = 10; + case 10: return [2 /*return*/, []]; + } + }); +}); }; + +/** + * Flatten array, one level deep. + * + * @template T + * + * @param {T[][]} arr + * + * @return {T[]} + */ + +const nativeToString$1 = Object.prototype.toString; +const nativeHasOwnProperty$1 = Object.prototype.hasOwnProperty; + +function isUndefined$1(obj) { + return obj === undefined; +} + +function isArray$1(obj) { + return nativeToString$1.call(obj) === '[object Array]'; +} + +/** + * @param {any} obj + * + * @return {boolean} + */ +function isFunction(obj) { + const tag = nativeToString$1.call(obj); + + return ( + tag === '[object Function]' || + tag === '[object AsyncFunction]' || + tag === '[object GeneratorFunction]' || + tag === '[object AsyncGeneratorFunction]' || + tag === '[object Proxy]' + ); +} + +/** + * Return true, if target owns a property with the given key. + * + * @param {Object} target + * @param {String} key + * + * @return {Boolean} + */ +function has$1(target, key) { + return nativeHasOwnProperty$1.call(target, key); +} + + +/** + * Filter elements in collection. + * + * @template T + * @param {Collection} collection + * @param {Matcher} matcher + * + * @return {T[]} result + */ +function filter(collection, matcher) { + + const matchFn = toMatcher(matcher); + + let result = []; + + forEach$1(collection, function(val, key) { + if (matchFn(val, key)) { + result.push(val); + } + }); + + return result; +} + + +/** + * Iterate over collection; returning something + * (non-undefined) will stop iteration. + * + * @template T + * @param {Collection} collection + * @param { ((item: T, idx: number) => (boolean|void)) | ((item: T, key: string) => (boolean|void)) } iterator + * + * @return {T} return result that stopped the iteration + */ +function forEach$1(collection, iterator) { + + let val, + result; + + if (isUndefined$1(collection)) { + return; + } + + const convertKey = isArray$1(collection) ? toNum$1 : identity$1; + + for (let key in collection) { + + if (has$1(collection, key)) { + val = collection[key]; + + result = iterator(val, convertKey(key)); + + if (result === false) { + return val; + } + } + } +} + + +/** + * Transform a collection into another collection + * by piping each member through the given fn. + * + * @param {Object|Array} collection + * @param {Function} fn + * + * @return {Array} transformed collection + */ +function map$1(collection, fn) { + + let result = []; + + forEach$1(collection, function(val, key) { + result.push(fn(val, key)); + }); + + return result; +} + + +/** + * Group collection members by attribute. + * + * @param {Object|Array} collection + * @param {Extractor} extractor + * + * @return {Object} map with { attrValue => [ a, b, c ] } + */ +function groupBy(collection, extractor, grouped = {}) { + + extractor = toExtractor(extractor); + + forEach$1(collection, function(val) { + let discriminator = extractor(val) || '_'; + + let group = grouped[discriminator]; + + if (!group) { + group = grouped[discriminator] = []; + } + + group.push(val); + }); + + return grouped; +} + + +function uniqueBy(extractor, ...collections) { + + extractor = toExtractor(extractor); + + let grouped = {}; + + forEach$1(collections, (c) => groupBy(c, extractor, grouped)); + + let result = map$1(grouped, function(val, key) { + return val[0]; + }); + + return result; +} + + +/** + * @param {string | ((e: any) => any) } extractor + * + * @return { (e: any) => any } + */ +function toExtractor(extractor) { + + /** + * @satisfies { (e: any) => any } + */ + return isFunction(extractor) ? extractor : (e) => { + + // @ts-ignore: just works + return e[extractor]; + }; +} + + +/** + * @template T + * @param {Matcher} matcher + * + * @return {MatchFn} + */ +function toMatcher(matcher) { + return isFunction(matcher) ? matcher : (e) => { + return e === matcher; + }; +} + + +function identity$1(arg) { + return arg; +} + +function toNum$1(arg) { + return Number(arg); +} + +var bugTestDiv; +if (typeof document !== 'undefined') { + bugTestDiv = document.createElement('div'); + // Setup + bugTestDiv.innerHTML = '
a'; + // Make sure that link elements get serialized correctly by innerHTML + // This requires a wrapper element in IE + !bugTestDiv.getElementsByTagName('link').length; + bugTestDiv = undefined; +} + +function query(selector, el) { + el = el || document; + + return el.querySelector(selector); +} + +/** + * Flatten array, one level deep. + * + * @param {Array} arr + * + * @return {Array} + */ + +var nativeToString = Object.prototype.toString; +var nativeHasOwnProperty = Object.prototype.hasOwnProperty; +function isUndefined(obj) { + return obj === undefined; +} +function isArray(obj) { + return nativeToString.call(obj) === '[object Array]'; +} +/** + * Return true, if target owns a property with the given key. + * + * @param {Object} target + * @param {String} key + * + * @return {Boolean} + */ + +function has(target, key) { + return nativeHasOwnProperty.call(target, key); +} +/** + * Iterate over collection; returning something + * (non-undefined) will stop iteration. + * + * @param {Array|Object} collection + * @param {Function} iterator + * + * @return {Object} return result that stopped the iteration + */ + +function forEach(collection, iterator) { + var val, result; + + if (isUndefined(collection)) { + return; + } + + var convertKey = isArray(collection) ? toNum : identity; + + for (var key in collection) { + if (has(collection, key)) { + val = collection[key]; + result = iterator(val, convertKey(key)); + + if (result === false) { + return val; + } + } + } +} +/** + * Transform a collection into another collection + * by piping each member through the given fn. + * + * @param {Object|Array} collection + * @param {Function} fn + * + * @return {Array} transformed collection + */ + +function map(collection, fn) { + var result = []; + forEach(collection, function (val, key) { + result.push(fn(val, key)); + }); + return result; +} + +function identity(arg) { + return arg; +} + +function toNum(arg) { + return Number(arg); +} + +function _extends() { + _extends = Object.assign || function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + + return target; + }; + + return _extends.apply(this, arguments); +} + +/** + * Convenience wrapper for `Object.assign`. + * + * @param {Object} target + * @param {...Object} others + * + * @return {Object} the target + */ + +function assign(target) { + for (var _len = arguments.length, others = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + others[_key - 1] = arguments[_key]; + } + + return _extends.apply(void 0, [target].concat(others)); +} + +/** + * attribute accessor utility + */ + +var LENGTH_ATTR$1 = 2; + +var CSS_PROPERTIES$1 = { + 'alignment-baseline': 1, + 'baseline-shift': 1, + 'clip': 1, + 'clip-path': 1, + 'clip-rule': 1, + 'color': 1, + 'color-interpolation': 1, + 'color-interpolation-filters': 1, + 'color-profile': 1, + 'color-rendering': 1, + 'cursor': 1, + 'direction': 1, + 'display': 1, + 'dominant-baseline': 1, + 'enable-background': 1, + 'fill': 1, + 'fill-opacity': 1, + 'fill-rule': 1, + 'filter': 1, + 'flood-color': 1, + 'flood-opacity': 1, + 'font': 1, + 'font-family': 1, + 'font-size': LENGTH_ATTR$1, + 'font-size-adjust': 1, + 'font-stretch': 1, + 'font-style': 1, + 'font-variant': 1, + 'font-weight': 1, + 'glyph-orientation-horizontal': 1, + 'glyph-orientation-vertical': 1, + 'image-rendering': 1, + 'kerning': 1, + 'letter-spacing': 1, + 'lighting-color': 1, + 'marker': 1, + 'marker-end': 1, + 'marker-mid': 1, + 'marker-start': 1, + 'mask': 1, + 'opacity': 1, + 'overflow': 1, + 'pointer-events': 1, + 'shape-rendering': 1, + 'stop-color': 1, + 'stop-opacity': 1, + 'stroke': 1, + 'stroke-dasharray': 1, + 'stroke-dashoffset': 1, + 'stroke-linecap': 1, + 'stroke-linejoin': 1, + 'stroke-miterlimit': 1, + 'stroke-opacity': 1, + 'stroke-width': LENGTH_ATTR$1, + 'text-anchor': 1, + 'text-decoration': 1, + 'text-rendering': 1, + 'unicode-bidi': 1, + 'visibility': 1, + 'word-spacing': 1, + 'writing-mode': 1 +}; + + +function getAttribute$1(node, name) { + if (CSS_PROPERTIES$1[name]) { + return node.style[name]; + } else { + return node.getAttributeNS(null, name); + } +} + +function setAttribute$1(node, name, value) { + var hyphenated = name.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); + + var type = CSS_PROPERTIES$1[hyphenated]; + + if (type) { + // append pixel unit, unless present + if (type === LENGTH_ATTR$1 && typeof value === 'number') { + value = String(value) + 'px'; + } + + node.style[hyphenated] = value; + } else { + node.setAttributeNS(null, name, value); + } +} + +function setAttributes$1(node, attrs) { + + var names = Object.keys(attrs), i, name; + + for (i = 0, name; (name = names[i]); i++) { + setAttribute$1(node, name, attrs[name]); + } +} + +/** + * Gets or sets raw attributes on a node. + * + * @param {SVGElement} node + * @param {Object} [attrs] + * @param {String} [name] + * @param {String} [value] + * + * @return {String} + */ +function attr$1(node, name, value) { + if (typeof name === 'string') { + if (value !== undefined) { + setAttribute$1(node, name, value); + } else { + return getAttribute$1(node, name); + } + } else { + setAttributes$1(node, name); + } + + return node; +} + +var ns$1 = { + svg: 'http://www.w3.org/2000/svg' +}; + +/** + * DOM parsing utility + */ + +var SVG_START$1 = '' + svg + ''; + unwrap = true; + } + + var parsed = parseDocument$1(svg); + + if (!unwrap) { + return parsed; + } + + var fragment = document.createDocumentFragment(); + + var parent = parsed.firstChild; + + while (parent.firstChild) { + fragment.appendChild(parent.firstChild); + } + + return fragment; +} + +function parseDocument$1(svg) { + + var parser; + + // parse + parser = new DOMParser(); + parser.async = false; + + return parser.parseFromString(svg, 'text/xml'); +} + +/** + * Create utility for SVG elements + */ + + +/** + * Create a specific type from name or SVG markup. + * + * @param {String} name the name or markup of the element + * @param {Object} [attrs] attributes to set on the element + * + * @returns {SVGElement} + */ +function create$1(name, attrs) { + var element; + + if (name.charAt(0) === '<') { + element = parse$1(name).firstChild; + element = document.importNode(element, true); + } else { + element = document.createElementNS(ns$1.svg, name); + } + + if (attrs) { + attr$1(element, attrs); + } + + return element; +} + +var DEFAULT_ATTRS = { + fill: 'none', + stroke: 'black', + strokeWidth: 2 +}; + +/** + * @typedef {Object} Point + * + * @param {number} point.x + * @param {number} point.y + */ + +/** + * Create SVG curve. + * + * @param {Array} points + * @param {Object} [attrs] + */ +function createCurve(points, attrs = {}) { + var path = create$1('path'); + + var data = getData(points); + + attr$1(path, assign({}, DEFAULT_ATTRS, attrs, { + d: data + })); + + return path; +} + +function getData(points) { + var segments = getSegments(points); + + if (segments.length === 1) { + return getSingleSegmentData(segments[0]); + } + + var startSegment = segments.shift(); + + return [ + moveTo(startSegment.start), + quadraticCurve(startSegment.controlPoint, startSegment.end) + ].concat(map(segments, function(segment) { + return sameCurve(segment.controlPoint, segment.end); + })).join(' '); +} + +function getSingleSegmentData(segment) { + var { start, controlPoint, end } = segment; + + return [ + moveTo(start), + quadraticCurve(controlPoint, end) + ].join(' '); +} + +function getSegments(points) { + if (points.length === 2) { + return [ + { + start: points[0], + controlPoint: getMid$1(points[0], points[1]), + end: points[1] + } + ]; + } + + if (points.length === 3) { + return [ + { + start: points[0], + controlPoint: points[1], + end: points[2] + } + ]; + } + + return [ getStartSegment(points) ] + .concat(getMiddleSegments(points)) + .concat([ getEndSegment(points) ]); +} + +function getStartSegment(points) { + return { + start: points[0], + controlPoint: points[1], + end: getMid$1(points[1], points[2]) + }; +} + +function getMiddleSegments(points) { + var segments = []; + + for (var i = 1; i < points.length - 3; i++) { + segments.push({ + start: getMid$1(points[ i ], points[ i + 1 ]), + controlPoint: points[ i + 1 ], + end: getMid$1(points[ i + 1 ], points[ i + 2 ]) + }); + } + + return segments; +} + +function getEndSegment(points) { + return { + start: getMid$1(points[points.length - 3], points[points.length - 2]), + controlPoint: points[points.length - 2], + end: points[points.length - 1] + }; +} + +function moveTo(a) { + return [ 'M', a.x, a.y ].join(' '); +} + +function quadraticCurve(a, b) { + return [ 'Q', a.x, a.y, b.x, b.y ].join(' '); +} + +function sameCurve(a, b) { + return [ 'S', a.x, a.y, b.x, b.y ].join(' '); +} + +function getMid$1(a, b) { + return { + x: Math.round((a.x + b.x) / 2), + y: Math.round((a.y + b.y) / 2) + }; +} + +function ensureImported(element, target) { + + if (element.ownerDocument !== target.ownerDocument) { + try { + + // may fail on webkit + return target.ownerDocument.importNode(element, true); + } catch (e) { + + // ignore + } + } + + return element; +} + +/** + * appendTo utility + */ + +/** + * Append a node to a target element and return the appended node. + * + * @param {SVGElement} element + * @param {SVGElement} target + * + * @return {SVGElement} the appended node + */ +function appendTo(element, target) { + return target.appendChild(ensureImported(element, target)); +} + +/** + * append utility + */ + +/** + * Append a node to an element + * + * @param {SVGElement} element + * @param {SVGElement} node + * + * @return {SVGElement} the element + */ +function append(target, node) { + appendTo(node, target); + return target; +} + +/** + * attribute accessor utility + */ + +var LENGTH_ATTR = 2; + +var CSS_PROPERTIES = { + 'alignment-baseline': 1, + 'baseline-shift': 1, + 'clip': 1, + 'clip-path': 1, + 'clip-rule': 1, + 'color': 1, + 'color-interpolation': 1, + 'color-interpolation-filters': 1, + 'color-profile': 1, + 'color-rendering': 1, + 'cursor': 1, + 'direction': 1, + 'display': 1, + 'dominant-baseline': 1, + 'enable-background': 1, + 'fill': 1, + 'fill-opacity': 1, + 'fill-rule': 1, + 'filter': 1, + 'flood-color': 1, + 'flood-opacity': 1, + 'font': 1, + 'font-family': 1, + 'font-size': LENGTH_ATTR, + 'font-size-adjust': 1, + 'font-stretch': 1, + 'font-style': 1, + 'font-variant': 1, + 'font-weight': 1, + 'glyph-orientation-horizontal': 1, + 'glyph-orientation-vertical': 1, + 'image-rendering': 1, + 'kerning': 1, + 'letter-spacing': 1, + 'lighting-color': 1, + 'marker': 1, + 'marker-end': 1, + 'marker-mid': 1, + 'marker-start': 1, + 'mask': 1, + 'opacity': 1, + 'overflow': 1, + 'pointer-events': 1, + 'shape-rendering': 1, + 'stop-color': 1, + 'stop-opacity': 1, + 'stroke': 1, + 'stroke-dasharray': 1, + 'stroke-dashoffset': 1, + 'stroke-linecap': 1, + 'stroke-linejoin': 1, + 'stroke-miterlimit': 1, + 'stroke-opacity': 1, + 'stroke-width': LENGTH_ATTR, + 'text-anchor': 1, + 'text-decoration': 1, + 'text-rendering': 1, + 'unicode-bidi': 1, + 'visibility': 1, + 'word-spacing': 1, + 'writing-mode': 1 +}; + + +function getAttribute(node, name) { + if (CSS_PROPERTIES[name]) { + return node.style[name]; + } else { + return node.getAttributeNS(null, name); + } +} + +function setAttribute(node, name, value) { + var hyphenated = name.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); + + var type = CSS_PROPERTIES[hyphenated]; + + if (type) { + + // append pixel unit, unless present + if (type === LENGTH_ATTR && typeof value === 'number') { + value = String(value) + 'px'; + } + + node.style[hyphenated] = value; + } else { + node.setAttributeNS(null, name, value); + } +} + +function setAttributes(node, attrs) { + + var names = Object.keys(attrs), i, name; + + for (i = 0, name; (name = names[i]); i++) { + setAttribute(node, name, attrs[name]); + } +} + +/** + * Gets or sets raw attributes on a node. + * + * @param {SVGElement} node + * @param {Object} [attrs] + * @param {String} [name] + * @param {String} [value] + * + * @return {String} + */ +function attr(node, name, value) { + if (typeof name === 'string') { + if (value !== undefined) { + setAttribute(node, name, value); + } else { + return getAttribute(node, name); + } + } else { + setAttributes(node, name); + } + + return node; +} + +function remove(element) { + var parent = element.parentNode; + + if (parent) { + parent.removeChild(element); + } + + return element; +} + +var ns = { + svg: 'http://www.w3.org/2000/svg' +}; + +/** + * DOM parsing utility + */ + +var SVG_START = '' + svg + ''; + unwrap = true; + } + + var parsed = parseDocument(svg); + + if (!unwrap) { + return parsed; + } + + var fragment = document.createDocumentFragment(); + + var parent = parsed.firstChild; + + while (parent.firstChild) { + fragment.appendChild(parent.firstChild); + } + + return fragment; +} + +function parseDocument(svg) { + + var parser; + + // parse + parser = new DOMParser(); + parser.async = false; + + return parser.parseFromString(svg, 'text/xml'); +} + +/** + * Create utility for SVG elements + */ + + +/** + * Create a specific type from name or SVG markup. + * + * @param {String} name the name or markup of the element + * @param {Object} [attrs] attributes to set on the element + * + * @returns {SVGElement} + */ +function create(name, attrs) { + var element; + + if (name.charAt(0) === '<') { + element = parse(name).firstChild; + element = document.importNode(element, true); + } else { + element = document.createElementNS(ns.svg, name); + } + + if (attrs) { + attr(element, attrs); + } + + return element; +} + +var FILL = '#52B415'; +var getConnections = function (activities, elementRegistry) { + var _a, _b; + var validActivity = new Map(); + var startTimesById = new Map(); + var endTimesById = new Map(); + var connectionDenyList = new Set(); + for (var _i = 0, activities_1 = activities; _i < activities_1.length; _i++) { + var activity = activities_1[_i]; + if (activity.endTime && !(activity.canceled && !activity.activityType.endsWith('Gateway'))) { + validActivity.set(activity.activityId, true); + } + if (endTimesById.has(activity.activityId)) { + var endTimes = (_a = endTimesById.get(activity.activityId)) !== null && _a !== void 0 ? _a : []; + endTimes.push(activity.endTime || 'Z'); + } + else { + endTimesById.set(activity.activityId, [activity.endTime || 'Z']); + } + if (startTimesById.has(activity.activityId)) { + var startTimes = (_b = startTimesById.get(activity.activityId)) !== null && _b !== void 0 ? _b : []; + startTimes.push(activity.startTime || 'Z'); + } + else { + startTimesById.set(activity.activityId, [activity.startTime || 'Z']); + } + } + var elementById = new Map(map$1(activities, function (activity) { + var _a; + var element = elementRegistry.get(activity.activityId); + // Side effect! Populate connectionDenyList for gateways by sorting outgoing + // paths in ascending order by their target activity start time and list everything + // but the first ones in deny list to prevent coloring them as active. + if (activity.activityType === 'exclusiveGateway' && element.outgoing.length) { + var activeConnections = []; + var myEndTimes = endTimesById.get(activity.activityId) || []; + var _loop_1 = function (idx) { + var myEndTime = myEndTimes[idx]; + element.outgoing.sort(function (a, b) { + var _a, _b; + var startTimesA = startTimesById.get(a.target.id) || []; + var startTimesB = startTimesById.get(b.target.id) || []; + var startA = (_a = startTimesA === null || startTimesA === void 0 ? void 0 : startTimesA[idx]) !== null && _a !== void 0 ? _a : 'Z'; + var startB = (_b = startTimesB === null || startTimesB === void 0 ? void 0 : startTimesB[idx]) !== null && _b !== void 0 ? _b : 'Z'; + return startTimesA.length <= idx + ? 1 + : startTimesB.length <= idx + ? -1 + : startA < myEndTime + ? 1 + : startB < myEndTime + ? -1 + : startA > startB + ? 1 + : startA < startB + ? -1 + : 0; + }); + activeConnections.push(element.outgoing[0].id); + }; + for (var idx = 0; idx < myEndTimes.length; idx++) { + _loop_1(idx); + } + for (var _i = 0, _b = element.outgoing; _i < _b.length; _i++) { + var connection = _b[_i]; + if (!activeConnections.includes(connection.id) && + ((_a = connection === null || connection === void 0 ? void 0 : connection.target) === null || _a === void 0 ? void 0 : _a.type) !== 'bpmn:ParallelGateway') { + connectionDenyList.add(connection.id); + } + } + } + return [activity.activityId, element]; + })); + var getActivityConnections = function (activityId) { + var _a; + var current = elementById.get(activityId); + var currentEndTimes = (_a = endTimesById.get(activityId)) !== null && _a !== void 0 ? _a : []; + if (current && validActivity.get(activityId)) { + var incoming = filter(current.incoming, function (connection) { + var _a; + if (connectionDenyList.has(connection.id)) { + return false; + } + var incomingEndTimes = validActivity.get(connection.source.id) + ? (_a = endTimesById.get(connection.source.id)) !== null && _a !== void 0 ? _a : [] + : []; + return incomingEndTimes.reduce(function (acc, iET) { + return acc || currentEndTimes.reduce(function (acc_, cET) { return acc_ || iET <= cET; }, false); + }, false); + }); + var outgoing = filter(current.outgoing, function (connection) { + var _a; + if (connectionDenyList.has(connection.id)) { + return false; + } + var outgoingEndTimes = (_a = endTimesById.get(connection.target.id)) !== null && _a !== void 0 ? _a : []; + return outgoingEndTimes.reduce(function (acc, oET) { + return acc || currentEndTimes.reduce(function (acc_, cET) { return acc_ || oET >= cET; }, false); + }, false); + }); + return __spreadArray(__spreadArray([], incoming, true), outgoing, true); + } + else { + return []; + } + }; + var connections = []; + forEach$1(Array.from(elementById.keys()), function (activityId) { + connections = uniqueBy('id', __spreadArray(__spreadArray([], connections, true), getActivityConnections(activityId), true)); + }); + return connections; +}; +var getMid = function (shape) { + return { + x: shape.x + shape.width / 2, + y: shape.y + shape.height / 2, + }; +}; +var notDottedTypes = ['bpmn:SubProcess']; +var getDottedConnections = function (connections) { + var dottedConnections = []; + connections.forEach(function (connection) { + var target = connection.target; + connections.forEach(function (c) { + var source = c.source; + if (source === target && !notDottedTypes.includes(source.type)) { + dottedConnections.push({ + waypoints: [connection.waypoints[connection.waypoints.length - 1], getMid(target), c.waypoints[0]], + }); + } + }); + }); + return dottedConnections; +}; +var renderSequenceFlow = function (viewer, activities) { + var registry = viewer.get('elementRegistry'); + var canvas = viewer.get('canvas'); + var layer = canvas.getLayer('processInstance', 1); + var connections = getConnections(activities !== null && activities !== void 0 ? activities : [], registry); + var paths = []; + var defs = query('defs', canvas._svg); + if (!defs) { + defs = create('defs'); + append(canvas._svg, defs); + } + var marker = create('marker'); + var path = create('path'); + attr(marker, { + id: 'arrow', + viewBox: '0 0 10 10', + refX: 7, + refY: 5, + markerWidth: 4, + markerHeight: 4, + orient: 'auto-start-reverse', + }); + attr(path, { + d: 'M 0 0 L 10 5 L 0 10 z', + fill: FILL, + stroke: 'blue', + strokeWidth: 0, + }); + append(marker, path); + append(defs, marker); + paths.push(marker); + for (var _i = 0, connections_1 = connections; _i < connections_1.length; _i++) { + var connection = connections_1[_i]; + var curve = createCurve(connection.waypoints, { + markerEnd: 'url(#arrow)', + stroke: FILL, + strokeWidth: 4, + }); + append(layer, curve); + paths.push(curve); + } + var connections_ = getDottedConnections(connections); + for (var _a = 0, connections_2 = connections_; _a < connections_2.length; _a++) { + var connection = connections_2[_a]; + var curve = createCurve(connection.waypoints, { + strokeDasharray: '1 8', + strokeLinecap: 'round', + stroke: FILL, + strokeWidth: 4, + }); + append(layer, curve); + paths.push(curve); + } + return paths; +}; +var clearSequenceFlow = function (nodes) { + for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { + var node = nodes_1[_i]; + remove(node); + } +}; + +var instanceHistoricActivities = [ + { + id: 'instanceDiagramHistoricActivities', + pluginPoint: 'cockpit.processInstance.diagram.plugin', + render: function (viewer, _a) { + var api = _a.api, processInstanceId = _a.processInstanceId; + (function () { return __awaiter(void 0, void 0, void 0, function () { + var overlays, activities, counter, _i, activities_1, activity, id, seen, _a, activities_2, activity, id, overlay, toggleSequenceFlowButton, sequenceFlow; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + overlays = viewer.get('overlays'); + return [4 /*yield*/, get(api, '/history/activity-instance', { processInstanceId: processInstanceId })]; + case 1: + activities = _b.sent(); + counter = {}; + for (_i = 0, activities_1 = activities; _i < activities_1.length; _i++) { + activity = activities_1[_i]; + id = activity.activityId; + counter[id] = counter[id] ? counter[id] + 1 : 1; + } + seen = {}; + for (_a = 0, activities_2 = activities; _a < activities_2.length; _a++) { + activity = activities_2[_a]; + id = activity.activityId; + if (seen[id]) { + continue; + } + else { + seen[id] = true; + } + overlay = document.createElement('span'); + overlay.innerText = "".concat(counter[id]); + overlay.className = 'badge'; + overlay.style.cssText = "\n background: lightgray;\n "; + overlays.add(id.split('#')[0], { + position: { + bottom: 17, + right: 10, + }, + html: overlay, + }); + } + toggleSequenceFlowButton = document.createElement('div'); + toggleSequenceFlowButton.style.cssText = "\n position: absolute;\n right: 15px;\n top: 15px;\n "; + viewer._container.appendChild(toggleSequenceFlowButton); + sequenceFlow = []; + createRoot(toggleSequenceFlowButton).render(React.createElement(React.StrictMode, null, + React.createElement(ToggleSequenceFlowButton, { onToggleSequenceFlow: function (value) { + if (value) { + sequenceFlow = renderSequenceFlow(viewer, activities !== null && activities !== void 0 ? activities : []); + } + else { + clearSequenceFlow(sequenceFlow); + } + } }))); + return [2 /*return*/]; + } + }); + }); })(); + }, + }, + { + id: 'instanceTabHistoricActivities', + pluginPoint: 'cockpit.processInstance.runtime.tab', + properties: { + label: 'Audit Log', + }, + render: function (node, _a) { + var api = _a.api, processInstanceId = _a.processInstanceId; + (function () { return __awaiter(void 0, void 0, void 0, function () { + var _a, activities, decisions, decisionByActivity; + return __generator(this, function (_b) { + switch (_b.label) { + case 0: return [4 /*yield*/, Promise.all([ + get(api, '/history/activity-instance', { processInstanceId: processInstanceId }), + get(api, '/history/decision-instance', { processInstanceId: processInstanceId }), + ])]; + case 1: + _a = _b.sent(), activities = _a[0], decisions = _a[1]; + decisionByActivity = new Map(decisions.map(function (decision) { return [decision.activityInstanceId, decision.id]; })); + activities.sort(function (a, b) { + a = a.endTime ? new Date(a.endTime) : new Date(); + b = b.endTime ? new Date(b.endTime) : new Date(); + if (a > b) { + return -1; + } + if (a < b) { + return 1; + } + return 0; + }); + createRoot(node).render(React.createElement(React.StrictMode, null, + React.createElement(AuditLogTable, { activities: activities, decisions: decisionByActivity }))); + return [2 /*return*/]; + } + }); + }); })(); + }, + }, +]; + +export { instanceHistoricActivities as default }; diff --git a/examples/java-c7/src/main/resources/META-INF/resources/webjars/camunda/app/cockpit/scripts/instance-route-history.js b/examples/java-c7/src/main/resources/META-INF/resources/webjars/camunda/app/cockpit/scripts/instance-route-history.js new file mode 100644 index 0000000..086d796 --- /dev/null +++ b/examples/java-c7/src/main/resources/META-INF/resources/webjars/camunda/app/cockpit/scripts/instance-route-history.js @@ -0,0 +1,71760 @@ +function ___$insertStylesToHeader(css) { + if (!css) { + return + } + if (typeof window === 'undefined') { + return + } + + const style = document.createElement('style'); + + style.setAttribute('type', 'text/css'); + style.innerHTML = css; + document.head.appendChild(style); + return css +} + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +var __assign$1 = function() { + __assign$1 = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + return __assign$1.apply(this, arguments); +}; + +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +} + +___$insertStylesToHeader(":root {\n --separator-border: rgba(128, 128, 128, 0.35);\n}\n\n.allotment-module_splitView__L-yRc {\n height: 100%;\n overflow: hidden;\n position: relative;\n width: 100%;\n}\n\n.allotment-module_splitView__L-yRc > .allotment-module_sashContainer__fzwJF {\n height: 100%;\n pointer-events: none;\n position: absolute;\n width: 100%;\n}\n\n.allotment-module_splitView__L-yRc > .allotment-module_sashContainer__fzwJF > .allotment-module_sash__QA-2t {\n pointer-events: auto;\n}\n\n.allotment-module_splitView__L-yRc > .allotment-module_splitViewContainer__rQnVa {\n height: 100%;\n position: relative;\n white-space: nowrap;\n width: 100%;\n}\n\n.allotment-module_splitView__L-yRc > .allotment-module_splitViewContainer__rQnVa > .allotment-module_splitViewView__MGZ6O {\n overflow: hidden;\n position: absolute;\n white-space: initial;\n}\n\n.allotment-module_splitView__L-yRc.allotment-module_vertical__WSwwa > .allotment-module_splitViewContainer__rQnVa > .allotment-module_splitViewView__MGZ6O {\n width: 100%;\n}\n\n.allotment-module_splitView__L-yRc.allotment-module_horizontal__7doS8 > .allotment-module_splitViewContainer__rQnVa > .allotment-module_splitViewView__MGZ6O {\n height: 100%;\n}\n\n.allotment-module_splitView__L-yRc.allotment-module_separatorBorder__x-rDS > .allotment-module_splitViewContainer__rQnVa > .allotment-module_splitViewView__MGZ6O:not(:first-child)::before {\n background-color: var(--separator-border);\n content: \" \";\n left: 0;\n pointer-events: none;\n position: absolute;\n top: 0;\n z-index: 5;\n}\n\n.allotment-module_splitView__L-yRc.allotment-module_separatorBorder__x-rDS.allotment-module_vertical__WSwwa > .allotment-module_splitViewContainer__rQnVa > .allotment-module_splitViewView__MGZ6O:not(:first-child)::before {\n height: 1px;\n width: 100%;\n}\n\n.allotment-module_splitView__L-yRc.allotment-module_separatorBorder__x-rDS.allotment-module_horizontal__7doS8 > .allotment-module_splitViewContainer__rQnVa > .allotment-module_splitViewView__MGZ6O:not(:first-child)::before {\n height: 100%;\n width: 1px;\n}\n\n:root {\n --focus-border: #007fd4;\n --sash-size: 8px;\n --sash-hover-size: 4px;\n}\n\n.sash-module_sash__K-9lB {\n position: absolute;\n z-index: 35;\n touch-action: none;\n pointer-events: auto;\n text-align: initial;\n}\n\n.sash-module_sash__K-9lB.sash-module_disabled__Hm-wx {\n pointer-events: none;\n}\n\n.sash-module_sash__K-9lB.sash-module_mac__Jf6OJ.sash-module_vertical__pB-rs {\n cursor: col-resize;\n}\n\n.sash-module_sash__K-9lB.sash-module_vertical__pB-rs.sash-module_minimum__-UKxp {\n cursor: e-resize;\n}\n\n.sash-module_sash__K-9lB.sash-module_vertical__pB-rs.sash-module_maximum__TCWxD {\n cursor: w-resize;\n}\n\n.sash-module_sash__K-9lB.sash-module_mac__Jf6OJ.sash-module_horizontal__kFbiw {\n cursor: row-resize;\n}\n\n.sash-module_sash__K-9lB.sash-module_horizontal__kFbiw.sash-module_minimum__-UKxp {\n cursor: s-resize;\n}\n\n.sash-module_sash__K-9lB.sash-module_horizontal__kFbiw.sash-module_maximum__TCWxD {\n cursor: n-resize;\n}\n\n.sash-module_sash__K-9lB.sash-module_disabled__Hm-wx {\n cursor: default !important;\n pointer-events: none !important;\n}\n\n.sash-module_sash__K-9lB.sash-module_vertical__pB-rs {\n cursor: ew-resize;\n top: 0;\n width: var(--sash-size);\n height: 100%;\n}\n\n.sash-module_sash__K-9lB.sash-module_horizontal__kFbiw {\n cursor: ns-resize;\n left: 0;\n width: 100%;\n height: var(--sash-size);\n}\n\n.sash-module_sash__K-9lB:not(.sash-module_disabled__Hm-wx) > .sash-module_orthogonal-drag-handle__Yii2- {\n content: \" \";\n height: calc(var(--sash-size) * 2);\n width: calc(var(--sash-size) * 2);\n z-index: 100;\n display: block;\n cursor: all-scroll;\n position: absolute;\n}\n\n.sash-module_sash__K-9lB.sash-module_horizontal__kFbiw.sash-module_orthogonal-edge-north__f7Noe:not(.sash-module_disabled__Hm-wx) > .sash-module_orthogonal-drag-handle__Yii2-.sash-module_start__uZEDk,\n.sash-module_sash__K-9lB.sash-module_horizontal__kFbiw.sash-module_orthogonal-edge-south__6ZrFC:not(.sash-module_disabled__Hm-wx) > .sash-module_orthogonal-drag-handle__Yii2-.sash-module_end__0TP-R {\n cursor: nwse-resize;\n}\n\n.sash-module_sash__K-9lB.sash-module_horizontal__kFbiw.sash-module_orthogonal-edge-north__f7Noe:not(.sash-module_disabled__Hm-wx) > .sash-module_orthogonal-drag-handle__Yii2-.sash-module_end__0TP-R,\n.sash-module_sash__K-9lB.sash-module_horizontal__kFbiw.sash-module_orthogonal-edge-south__6ZrFC:not(.sash-module_disabled__Hm-wx) > .sash-module_orthogonal-drag-handle__Yii2-.sash-module_start__uZEDk {\n cursor: nesw-resize;\n}\n\n.sash-module_sash__K-9lB.sash-module_vertical__pB-rs > .sash-module_orthogonal-drag-handle__Yii2-.sash-module_start__uZEDk {\n left: calc(var(--sash-size) * -0.5);\n top: calc(var(--sash-size) * -1);\n}\n\n.sash-module_sash__K-9lB.sash-module_vertical__pB-rs > .sash-module_orthogonal-drag-handle__Yii2-.sash-module_end__0TP-R {\n left: calc(var(--sash-size) * -0.5);\n bottom: calc(var(--sash-size) * -1);\n}\n\n.sash-module_sash__K-9lB.sash-module_horizontal__kFbiw > .sash-module_orthogonal-drag-handle__Yii2-.sash-module_start__uZEDk {\n top: calc(var(--sash-size) * -0.5);\n left: calc(var(--sash-size) * -1);\n}\n\n.sash-module_sash__K-9lB.sash-module_horizontal__kFbiw > .sash-module_orthogonal-drag-handle__Yii2-.sash-module_end__0TP-R {\n top: calc(var(--sash-size) * -0.5);\n right: calc(var(--sash-size) * -1);\n}\n\n.sash-module_sash__K-9lB:before {\n content: \"\";\n pointer-events: none;\n position: absolute;\n width: 100%;\n height: 100%;\n transition: background-color 0.1s ease-out;\n background: transparent;\n}\n\n.sash-module_sash__K-9lB.sash-module_vertical__pB-rs:before {\n width: var(--sash-hover-size);\n left: calc(50% - var(--sash-hover-size) / 2);\n}\n\n.sash-module_sash__K-9lB.sash-module_horizontal__kFbiw:before {\n height: var(--sash-hover-size);\n top: calc(50% - var(--sash-hover-size) / 2);\n}\n\n.sash-module_sash__K-9lB.sash-module_hover__80W6I:before,\n.sash-module_sash__K-9lB.sash-module_active__bJspD:before {\n background: var(--focus-border);\n}"); + +___$insertStylesToHeader(".react-tabs__tab a {\n cursor: pointer;\n}\n.react-tabs__tab.active a {\n cursor: none;\n}\n\n.react-tabs__tab-panel--selected {\n z-index: 1;\n}\n\n.Pane.vertical.Pane1 {\n border-right: 1px solid #ddd;\n}\n\n.Resizer {\n background: rgba(255, 255, 255, 0);\n opacity: 0.2;\n z-index: 1;\n -moz-box-sizing: border-box;\n -webkit-box-sizing: border-box;\n box-sizing: border-box;\n -moz-background-clip: padding;\n -webkit-background-clip: padding;\n background-clip: padding-box;\n}\n\n.Resizer:hover {\n -webkit-transition: all 2s ease;\n transition: all 2s ease;\n}\n\n.Resizer.horizontal {\n height: 11px;\n margin: -5px 0;\n border-top: 5px solid rgba(255, 255, 255, 0);\n border-bottom: 5px solid rgba(255, 255, 255, 0);\n cursor: row-resize;\n width: 100%;\n}\n\n.Resizer.horizontal:hover {\n border-top: 5px solid rgba(0, 0, 0, 0.5);\n border-bottom: 5px solid rgba(0, 0, 0, 0.5);\n}\n\n.Resizer.vertical {\n width: 11px;\n margin: 0 -5px;\n border-left: 5px solid rgba(255, 255, 255, 0);\n border-right: 5px solid rgba(255, 255, 255, 0);\n cursor: col-resize;\n}\n\n.Resizer.vertical:hover {\n border-left: 5px solid rgba(0, 0, 0, 0.5);\n border-right: 5px solid rgba(0, 0, 0, 0.5);\n}\n\n.Resizer.disabled {\n cursor: not-allowed;\n}\n\n.Resizer.disabled:hover {\n border-color: transparent;\n}"); + +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +function getAugmentedNamespace(n) { + if (n.__esModule) return n; + var f = n.default; + if (typeof f == "function") { + var a = function a () { + if (this instanceof a) { + var args = [null]; + args.push.apply(args, arguments); + var Ctor = Function.bind.apply(f, args); + return new Ctor(); + } + return f.apply(this, arguments); + }; + a.prototype = f.prototype; + } else a = {}; + Object.defineProperty(a, '__esModule', {value: true}); + Object.keys(n).forEach(function (k) { + var d = Object.getOwnPropertyDescriptor(n, k); + Object.defineProperty(a, k, d.get ? d : { + enumerable: true, + get: function () { + return n[k]; + } + }); + }); + return a; +} + +var react$1 = {exports: {}}; + +var react_production_min$1 = {}; + +/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +var l$2=Symbol.for("react.element"),n=Symbol.for("react.portal"),p$2=Symbol.for("react.fragment"),q$1=Symbol.for("react.strict_mode"),r$2=Symbol.for("react.profiler"),t=Symbol.for("react.provider"),u$1=Symbol.for("react.context"),v$3=Symbol.for("react.forward_ref"),w$1=Symbol.for("react.suspense"),x$1=Symbol.for("react.memo"),y$2=Symbol.for("react.lazy"),z$2=Symbol.iterator;function A$3(a){if(null===a||"object"!==typeof a)return null;a=z$2&&a[z$2]||a["@@iterator"];return "function"===typeof a?a:null} +var B$2={isMounted:function(){return !1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C$3=Object.assign,D$2={};function E$3(a,b,e){this.props=a;this.context=b;this.refs=D$2;this.updater=e||B$2;}E$3.prototype.isReactComponent={}; +E$3.prototype.setState=function(a,b){if("object"!==typeof a&&"function"!==typeof a&&null!=a)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,a,b,"setState");};E$3.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,"forceUpdate");};function F$2(){}F$2.prototype=E$3.prototype;function G$2(a,b,e){this.props=a;this.context=b;this.refs=D$2;this.updater=e||B$2;}var H$2=G$2.prototype=new F$2; +H$2.constructor=G$2;C$3(H$2,E$3.prototype);H$2.isPureReactComponent=!0;var I$2=Array.isArray,J$1=Object.prototype.hasOwnProperty,K$3={current:null},L$2={key:!0,ref:!0,__self:!0,__source:!0}; +function M$2(a,b,e){var d,c={},k=null,h=null;if(null!=b)for(d in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(k=""+b.key),b)J$1.call(b,d)&&!L$2.hasOwnProperty(d)&&(c[d]=b[d]);var g=arguments.length-2;if(1===g)c.children=e;else if(1= t ? e : t)), e; + }(b$1(e), t, i); + }, + w = "undefined" != typeof globalThis ? globalThis : "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof self ? self : {}, + S$1 = {}; +!function (e, t) { + var i = "__lodash_hash_undefined__", + n = 9007199254740991, + r = "[object Arguments]", + s = "[object Array]", + o = "[object Boolean]", + a = "[object Date]", + u = "[object Error]", + h = "[object Function]", + c = "[object Map]", + l = "[object Number]", + f = "[object Object]", + m = "[object Promise]", + d = "[object RegExp]", + p = "[object Set]", + v = "[object String]", + y = "[object Symbol]", + g = "[object WeakMap]", + b = "[object ArrayBuffer]", + z = "[object DataView]", + S = /^\[object .+?Constructor\]$/, + _ = /^(?:0|[1-9]\d*)$/, + I = {}; + I["[object Float32Array]"] = I["[object Float64Array]"] = I["[object Int8Array]"] = I["[object Int16Array]"] = I["[object Int32Array]"] = I["[object Uint8Array]"] = I["[object Uint8ClampedArray]"] = I["[object Uint16Array]"] = I["[object Uint32Array]"] = !0, I[r] = I[s] = I[b] = I[o] = I[z] = I[a] = I[u] = I[h] = I[c] = I[l] = I[f] = I[d] = I[p] = I[v] = I[g] = !1; + var x = "object" == typeof w && w && w.Object === Object && w, + E = "object" == typeof self && self && self.Object === Object && self, + V = x || E || Function("return this")(), + j = t && !t.nodeType && t, + N = j && e && !e.nodeType && e, + L = N && N.exports === j, + D = L && x.process, + O = function () { + try { + return D && D.binding && D.binding("util"); + } catch (e) {} + }(), + M = O && O.isTypedArray; + function P(e, t) { + for (var i = -1, n = null == e ? 0 : e.length; ++i < n;) if (t(e[i], i, e)) return !0; + return !1; + } + function A(e) { + var t = -1, + i = Array(e.size); + return e.forEach(function (e, n) { + i[++t] = [n, e]; + }), i; + } + function T(e) { + var t = -1, + i = Array(e.size); + return e.forEach(function (e) { + i[++t] = e; + }), i; + } + var C, + F, + k, + $ = Array.prototype, + H = Function.prototype, + Y = Object.prototype, + B = V["__core-js_shared__"], + R = H.toString, + W = Y.hasOwnProperty, + G = (C = /[^.]+$/.exec(B && B.keys && B.keys.IE_PROTO || "")) ? "Symbol(src)_1." + C : "", + U = Y.toString, + X = RegExp("^" + R.call(W).replace(/[\\^$.*+?()[\]{}|]/g, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"), + J = L ? V.Buffer : void 0, + K = V.Symbol, + Z = V.Uint8Array, + Q = Y.propertyIsEnumerable, + q = $.splice, + ee = K ? K.toStringTag : void 0, + te = Object.getOwnPropertySymbols, + ie = J ? J.isBuffer : void 0, + ne = (F = Object.keys, k = Object, function (e) { + return F(k(e)); + }), + re = Oe(V, "DataView"), + se = Oe(V, "Map"), + oe = Oe(V, "Promise"), + ae = Oe(V, "Set"), + ue = Oe(V, "WeakMap"), + he = Oe(Object, "create"), + ce = Te(re), + le = Te(se), + fe = Te(oe), + me = Te(ae), + de = Te(ue), + pe = K ? K.prototype : void 0, + ve = pe ? pe.valueOf : void 0; + function ye(e) { + var t = -1, + i = null == e ? 0 : e.length; + for (this.clear(); ++t < i;) { + var n = e[t]; + this.set(n[0], n[1]); + } + } + function ge(e) { + var t = -1, + i = null == e ? 0 : e.length; + for (this.clear(); ++t < i;) { + var n = e[t]; + this.set(n[0], n[1]); + } + } + function be(e) { + var t = -1, + i = null == e ? 0 : e.length; + for (this.clear(); ++t < i;) { + var n = e[t]; + this.set(n[0], n[1]); + } + } + function ze(e) { + var t = -1, + i = null == e ? 0 : e.length; + for (this.__data__ = new be(); ++t < i;) this.add(e[t]); + } + function we(e) { + var t = this.__data__ = new ge(e); + this.size = t.size; + } + function Se(e, t) { + var i = ke(e), + n = !i && Fe(e), + r = !i && !n && $e(e), + s = !i && !n && !r && We(e), + o = i || n || r || s, + a = o ? function (e, t) { + for (var i = -1, n = Array(e); ++i < e;) n[i] = t(i); + return n; + }(e.length, String) : [], + u = a.length; + for (var h in e) !t && !W.call(e, h) || o && ("length" == h || r && ("offset" == h || "parent" == h) || s && ("buffer" == h || "byteLength" == h || "byteOffset" == h) || Ae(h, u)) || a.push(h); + return a; + } + function _e(e, t) { + for (var i = e.length; i--;) if (Ce(e[i][0], t)) return i; + return -1; + } + function Ie(e) { + return null == e ? void 0 === e ? "[object Undefined]" : "[object Null]" : ee && ee in Object(e) ? function (e) { + var t = W.call(e, ee), + i = e[ee]; + try { + e[ee] = void 0; + var n = !0; + } catch (e) {} + var r = U.call(e); + n && (t ? e[ee] = i : delete e[ee]); + return r; + }(e) : function (e) { + return U.call(e); + }(e); + } + function xe(e) { + return Re(e) && Ie(e) == r; + } + function Ee(e, t, i, n, h) { + return e === t || (null == e || null == t || !Re(e) && !Re(t) ? e != e && t != t : function (e, t, i, n, h, m) { + var g = ke(e), + w = ke(t), + S = g ? s : Pe(e), + _ = w ? s : Pe(t), + I = (S = S == r ? f : S) == f, + x = (_ = _ == r ? f : _) == f, + E = S == _; + if (E && $e(e)) { + if (!$e(t)) return !1; + g = !0, I = !1; + } + if (E && !I) return m || (m = new we()), g || We(e) ? Ne(e, t, i, n, h, m) : function (e, t, i, n, r, s, h) { + switch (i) { + case z: + if (e.byteLength != t.byteLength || e.byteOffset != t.byteOffset) return !1; + e = e.buffer, t = t.buffer; + case b: + return !(e.byteLength != t.byteLength || !s(new Z(e), new Z(t))); + case o: + case a: + case l: + return Ce(+e, +t); + case u: + return e.name == t.name && e.message == t.message; + case d: + case v: + return e == t + ""; + case c: + var f = A; + case p: + var m = 1 & n; + if (f || (f = T), e.size != t.size && !m) return !1; + var g = h.get(e); + if (g) return g == t; + n |= 2, h.set(e, t); + var w = Ne(f(e), f(t), n, r, s, h); + return h.delete(e), w; + case y: + if (ve) return ve.call(e) == ve.call(t); + } + return !1; + }(e, t, S, i, n, h, m); + if (!(1 & i)) { + var V = I && W.call(e, "__wrapped__"), + j = x && W.call(t, "__wrapped__"); + if (V || j) { + var N = V ? e.value() : e, + L = j ? t.value() : t; + return m || (m = new we()), h(N, L, i, n, m); + } + } + if (!E) return !1; + return m || (m = new we()), function (e, t, i, n, r, s) { + var o = 1 & i, + a = Le(e), + u = a.length, + h = Le(t).length; + if (u != h && !o) return !1; + var c = u; + for (; c--;) { + var l = a[c]; + if (!(o ? l in t : W.call(t, l))) return !1; + } + var f = s.get(e); + if (f && s.get(t)) return f == t; + var m = !0; + s.set(e, t), s.set(t, e); + var d = o; + for (; ++c < u;) { + var p = e[l = a[c]], + v = t[l]; + if (n) var y = o ? n(v, p, l, t, e, s) : n(p, v, l, e, t, s); + if (!(void 0 === y ? p === v || r(p, v, i, n, s) : y)) { + m = !1; + break; + } + d || (d = "constructor" == l); + } + if (m && !d) { + var g = e.constructor, + b = t.constructor; + g == b || !("constructor" in e) || !("constructor" in t) || "function" == typeof g && g instanceof g && "function" == typeof b && b instanceof b || (m = !1); + } + return s.delete(e), s.delete(t), m; + }(e, t, i, n, h, m); + }(e, t, i, n, Ee, h)); + } + function Ve(e) { + return !(!Be(e) || function (e) { + return !!G && G in e; + }(e)) && (He(e) ? X : S).test(Te(e)); + } + function je(e) { + if (i = (t = e) && t.constructor, n = "function" == typeof i && i.prototype || Y, t !== n) return ne(e); + var t, + i, + n, + r = []; + for (var s in Object(e)) W.call(e, s) && "constructor" != s && r.push(s); + return r; + } + function Ne(e, t, i, n, r, s) { + var o = 1 & i, + a = e.length, + u = t.length; + if (a != u && !(o && u > a)) return !1; + var h = s.get(e); + if (h && s.get(t)) return h == t; + var c = -1, + l = !0, + f = 2 & i ? new ze() : void 0; + for (s.set(e, t), s.set(t, e); ++c < a;) { + var m = e[c], + d = t[c]; + if (n) var p = o ? n(d, m, c, t, e, s) : n(m, d, c, e, t, s); + if (void 0 !== p) { + if (p) continue; + l = !1; + break; + } + if (f) { + if (!P(t, function (e, t) { + if (o = t, !f.has(o) && (m === e || r(m, e, i, n, s))) return f.push(t); + var o; + })) { + l = !1; + break; + } + } else if (m !== d && !r(m, d, i, n, s)) { + l = !1; + break; + } + } + return s.delete(e), s.delete(t), l; + } + function Le(e) { + return function (e, t, i) { + var n = t(e); + return ke(e) ? n : function (e, t) { + for (var i = -1, n = t.length, r = e.length; ++i < n;) e[r + i] = t[i]; + return e; + }(n, i(e)); + }(e, Ge, Me); + } + function De(e, t) { + var i, + n, + r = e.__data__; + return ("string" == (n = typeof (i = t)) || "number" == n || "symbol" == n || "boolean" == n ? "__proto__" !== i : null === i) ? r["string" == typeof t ? "string" : "hash"] : r.map; + } + function Oe(e, t) { + var i = function (e, t) { + return null == e ? void 0 : e[t]; + }(e, t); + return Ve(i) ? i : void 0; + } + ye.prototype.clear = function () { + this.__data__ = he ? he(null) : {}, this.size = 0; + }, ye.prototype.delete = function (e) { + var t = this.has(e) && delete this.__data__[e]; + return this.size -= t ? 1 : 0, t; + }, ye.prototype.get = function (e) { + var t = this.__data__; + if (he) { + var n = t[e]; + return n === i ? void 0 : n; + } + return W.call(t, e) ? t[e] : void 0; + }, ye.prototype.has = function (e) { + var t = this.__data__; + return he ? void 0 !== t[e] : W.call(t, e); + }, ye.prototype.set = function (e, t) { + var n = this.__data__; + return this.size += this.has(e) ? 0 : 1, n[e] = he && void 0 === t ? i : t, this; + }, ge.prototype.clear = function () { + this.__data__ = [], this.size = 0; + }, ge.prototype.delete = function (e) { + var t = this.__data__, + i = _e(t, e); + return !(i < 0) && (i == t.length - 1 ? t.pop() : q.call(t, i, 1), --this.size, !0); + }, ge.prototype.get = function (e) { + var t = this.__data__, + i = _e(t, e); + return i < 0 ? void 0 : t[i][1]; + }, ge.prototype.has = function (e) { + return _e(this.__data__, e) > -1; + }, ge.prototype.set = function (e, t) { + var i = this.__data__, + n = _e(i, e); + return n < 0 ? (++this.size, i.push([e, t])) : i[n][1] = t, this; + }, be.prototype.clear = function () { + this.size = 0, this.__data__ = { + hash: new ye(), + map: new (se || ge)(), + string: new ye() + }; + }, be.prototype.delete = function (e) { + var t = De(this, e).delete(e); + return this.size -= t ? 1 : 0, t; + }, be.prototype.get = function (e) { + return De(this, e).get(e); + }, be.prototype.has = function (e) { + return De(this, e).has(e); + }, be.prototype.set = function (e, t) { + var i = De(this, e), + n = i.size; + return i.set(e, t), this.size += i.size == n ? 0 : 1, this; + }, ze.prototype.add = ze.prototype.push = function (e) { + return this.__data__.set(e, i), this; + }, ze.prototype.has = function (e) { + return this.__data__.has(e); + }, we.prototype.clear = function () { + this.__data__ = new ge(), this.size = 0; + }, we.prototype.delete = function (e) { + var t = this.__data__, + i = t.delete(e); + return this.size = t.size, i; + }, we.prototype.get = function (e) { + return this.__data__.get(e); + }, we.prototype.has = function (e) { + return this.__data__.has(e); + }, we.prototype.set = function (e, t) { + var i = this.__data__; + if (i instanceof ge) { + var n = i.__data__; + if (!se || n.length < 199) return n.push([e, t]), this.size = ++i.size, this; + i = this.__data__ = new be(n); + } + return i.set(e, t), this.size = i.size, this; + }; + var Me = te ? function (e) { + return null == e ? [] : (e = Object(e), function (e, t) { + for (var i = -1, n = null == e ? 0 : e.length, r = 0, s = []; ++i < n;) { + var o = e[i]; + t(o, i, e) && (s[r++] = o); + } + return s; + }(te(e), function (t) { + return Q.call(e, t); + })); + } : function () { + return []; + }, + Pe = Ie; + function Ae(e, t) { + return !!(t = null == t ? n : t) && ("number" == typeof e || _.test(e)) && e > -1 && e % 1 == 0 && e < t; + } + function Te(e) { + if (null != e) { + try { + return R.call(e); + } catch (e) {} + try { + return e + ""; + } catch (e) {} + } + return ""; + } + function Ce(e, t) { + return e === t || e != e && t != t; + } + (re && Pe(new re(new ArrayBuffer(1))) != z || se && Pe(new se()) != c || oe && Pe(oe.resolve()) != m || ae && Pe(new ae()) != p || ue && Pe(new ue()) != g) && (Pe = function (e) { + var t = Ie(e), + i = t == f ? e.constructor : void 0, + n = i ? Te(i) : ""; + if (n) switch (n) { + case ce: + return z; + case le: + return c; + case fe: + return m; + case me: + return p; + case de: + return g; + } + return t; + }); + var Fe = xe(function () { + return arguments; + }()) ? xe : function (e) { + return Re(e) && W.call(e, "callee") && !Q.call(e, "callee"); + }, + ke = Array.isArray; + var $e = ie || function () { + return !1; + }; + function He(e) { + if (!Be(e)) return !1; + var t = Ie(e); + return t == h || "[object GeneratorFunction]" == t || "[object AsyncFunction]" == t || "[object Proxy]" == t; + } + function Ye(e) { + return "number" == typeof e && e > -1 && e % 1 == 0 && e <= n; + } + function Be(e) { + var t = typeof e; + return null != e && ("object" == t || "function" == t); + } + function Re(e) { + return null != e && "object" == typeof e; + } + var We = M ? function (e) { + return function (t) { + return e(t); + }; + }(M) : function (e) { + return Re(e) && Ye(e.length) && !!I[Ie(e)]; + }; + function Ge(e) { + return null != (t = e) && Ye(t.length) && !He(t) ? Se(e) : je(e); + var t; + } + e.exports = function (e, t) { + return Ee(e, t); + }; +}({ + get exports() { + return S$1; + }, + set exports(e) { + S$1 = e; + } +}, S$1); +var _ = S$1; +function I$1(e, t, i) { + return e[t] ? e[t][0] ? e[t][0][i] : e[t][i] : "contentBoxSize" === t ? e.contentRect["inlineSize" === i ? "width" : "height"] : void 0; +} +function x(e) { + void 0 === e && (e = {}); + var o = e.onResize, + a = reactExports.useRef(void 0); + a.current = o; + var u = e.round || Math.round, + h = reactExports.useRef(), + c = reactExports.useState({ + width: void 0, + height: void 0 + }), + l = c[0], + f = c[1], + m = reactExports.useRef(!1); + reactExports.useEffect(function () { + return m.current = !1, function () { + m.current = !0; + }; + }, []); + var d = reactExports.useRef({ + width: void 0, + height: void 0 + }), + p = function (e, i) { + var s = reactExports.useRef(null), + o = reactExports.useRef(null); + o.current = i; + var a = reactExports.useRef(null); + reactExports.useEffect(function () { + u(); + }); + var u = reactExports.useCallback(function () { + var t = a.current, + i = o.current, + n = t || (i ? i instanceof Element ? i : i.current : null); + s.current && s.current.element === n && s.current.subscriber === e || (s.current && s.current.cleanup && s.current.cleanup(), s.current = { + element: n, + subscriber: e, + cleanup: n ? e(n) : void 0 + }); + }, [e]); + return reactExports.useEffect(function () { + return function () { + s.current && s.current.cleanup && (s.current.cleanup(), s.current = null); + }; + }, []), reactExports.useCallback(function (e) { + a.current = e, u(); + }, [u]); + }(reactExports.useCallback(function (t) { + return h.current && h.current.box === e.box && h.current.round === u || (h.current = { + box: e.box, + round: u, + instance: new ResizeObserver(function (t) { + var i = t[0], + n = "border-box" === e.box ? "borderBoxSize" : "device-pixel-content-box" === e.box ? "devicePixelContentBoxSize" : "contentBoxSize", + r = I$1(i, n, "inlineSize"), + s = I$1(i, n, "blockSize"), + o = r ? u(r) : void 0, + h = s ? u(s) : void 0; + if (d.current.width !== o || d.current.height !== h) { + var c = { + width: o, + height: h + }; + d.current.width = o, d.current.height = h, a.current ? a.current(c) : m.current || f(c); + } + }) + }), h.current.instance.observe(t, { + box: e.box + }), function () { + h.current && h.current.instance.unobserve(t); + }; + }, [e.box, u]), e.ref); + return reactExports.useMemo(function () { + return { + ref: p, + width: l.width, + height: l.height + }; + }, [p, l.width, l.height]); +} +var E$2 = "allotment-module_splitView__L-yRc", + V$1 = "allotment-module_sashContainer__fzwJF", + j$1 = "allotment-module_splitViewContainer__rQnVa", + N$1 = "allotment-module_splitViewView__MGZ6O", + L$1 = "allotment-module_vertical__WSwwa", + D$1 = "allotment-module_horizontal__7doS8", + O$1 = "allotment-module_separatorBorder__x-rDS"; +let M$1, + P$1 = !1, + A$2 = !1; +"object" == typeof navigator && (M$1 = navigator.userAgent, A$2 = M$1.indexOf("Macintosh") >= 0, P$1 = (M$1.indexOf("Macintosh") >= 0 || M$1.indexOf("iPad") >= 0 || M$1.indexOf("iPhone") >= 0) && !!navigator.maxTouchPoints && navigator.maxTouchPoints > 0); +const T$1 = P$1, + C$2 = A$2, + F$1 = "undefined" != typeof window && void 0 !== window.document && void 0 !== window.document.createElement ? reactExports.useLayoutEffect : reactExports.useEffect; +let k$1 = class k { + constructor() { + this._size = void 0; + } + getSize() { + return this._size; + } + setSize(e) { + this._size = e; + } +}; +function $(e, t) { + const i = e.length, + n = i - t.length; + return n >= 0 && e.slice(n, i) === t; +} +var H$1 = {}; +!function (e) { + var t = Object.prototype.hasOwnProperty, + i = "~"; + function n() {} + function r(e, t, i) { + this.fn = e, this.context = t, this.once = i || !1; + } + function s(e, t, n, s, o) { + if ("function" != typeof n) throw new TypeError("The listener must be a function"); + var a = new r(n, s || e, o), + u = i ? i + t : t; + return e._events[u] ? e._events[u].fn ? e._events[u] = [e._events[u], a] : e._events[u].push(a) : (e._events[u] = a, e._eventsCount++), e; + } + function o(e, t) { + 0 == --e._eventsCount ? e._events = new n() : delete e._events[t]; + } + function a() { + this._events = new n(), this._eventsCount = 0; + } + Object.create && (n.prototype = Object.create(null), new n().__proto__ || (i = !1)), a.prototype.eventNames = function () { + var e, + n, + r = []; + if (0 === this._eventsCount) return r; + for (n in e = this._events) t.call(e, n) && r.push(i ? n.slice(1) : n); + return Object.getOwnPropertySymbols ? r.concat(Object.getOwnPropertySymbols(e)) : r; + }, a.prototype.listeners = function (e) { + var t = i ? i + e : e, + n = this._events[t]; + if (!n) return []; + if (n.fn) return [n.fn]; + for (var r = 0, s = n.length, o = new Array(s); r < s; r++) o[r] = n[r].fn; + return o; + }, a.prototype.listenerCount = function (e) { + var t = i ? i + e : e, + n = this._events[t]; + return n ? n.fn ? 1 : n.length : 0; + }, a.prototype.emit = function (e, t, n, r, s, o) { + var a = i ? i + e : e; + if (!this._events[a]) return !1; + var u, + h, + c = this._events[a], + l = arguments.length; + if (c.fn) { + switch (c.once && this.removeListener(e, c.fn, void 0, !0), l) { + case 1: + return c.fn.call(c.context), !0; + case 2: + return c.fn.call(c.context, t), !0; + case 3: + return c.fn.call(c.context, t, n), !0; + case 4: + return c.fn.call(c.context, t, n, r), !0; + case 5: + return c.fn.call(c.context, t, n, r, s), !0; + case 6: + return c.fn.call(c.context, t, n, r, s, o), !0; + } + for (h = 1, u = new Array(l - 1); h < l; h++) u[h - 1] = arguments[h]; + c.fn.apply(c.context, u); + } else { + var f, + m = c.length; + for (h = 0; h < m; h++) switch (c[h].once && this.removeListener(e, c[h].fn, void 0, !0), l) { + case 1: + c[h].fn.call(c[h].context); + break; + case 2: + c[h].fn.call(c[h].context, t); + break; + case 3: + c[h].fn.call(c[h].context, t, n); + break; + case 4: + c[h].fn.call(c[h].context, t, n, r); + break; + default: + if (!u) for (f = 1, u = new Array(l - 1); f < l; f++) u[f - 1] = arguments[f]; + c[h].fn.apply(c[h].context, u); + } + } + return !0; + }, a.prototype.on = function (e, t, i) { + return s(this, e, t, i, !1); + }, a.prototype.once = function (e, t, i) { + return s(this, e, t, i, !0); + }, a.prototype.removeListener = function (e, t, n, r) { + var s = i ? i + e : e; + if (!this._events[s]) return this; + if (!t) return o(this, s), this; + var a = this._events[s]; + if (a.fn) a.fn !== t || r && !a.once || n && a.context !== n || o(this, s);else { + for (var u = 0, h = [], c = a.length; u < c; u++) (a[u].fn !== t || r && !a[u].once || n && a[u].context !== n) && h.push(a[u]); + h.length ? this._events[s] = 1 === h.length ? h[0] : h : o(this, s); + } + return this; + }, a.prototype.removeAllListeners = function (e) { + var t; + return e ? (t = i ? i + e : e, this._events[t] && o(this, t)) : (this._events = new n(), this._eventsCount = 0), this; + }, a.prototype.off = a.prototype.removeListener, a.prototype.addListener = a.prototype.on, a.prefixed = i, a.EventEmitter = a, e.exports = a; +}({ + get exports() { + return H$1; + }, + set exports(e) { + H$1 = e; + } +}); +function Y$1(e, t) { + const i = e.indexOf(t); + i > -1 && (e.splice(i, 1), e.unshift(t)); +} +function B$1(e, t) { + const i = e.indexOf(t); + i > -1 && (e.splice(i, 1), e.push(t)); +} +function R$1(e, t, i = 1) { + const n = Math.max(0, Math.ceil((t - e) / i)), + r = new Array(n); + let s = -1; + for (; ++s < n;) r[s] = e + s * i; + return r; +} +var W$2 = /^\s+|\s+$/g, + G$1 = /^[-+]0x[0-9a-f]+$/i, + U$1 = /^0b[01]+$/i, + X$1 = /^0o[0-7]+$/i, + J = parseInt, + K$2 = "object" == typeof w && w && w.Object === Object && w, + Z$1 = "object" == typeof self && self && self.Object === Object && self, + Q$1 = K$2 || Z$1 || Function("return this")(), + q = Object.prototype.toString, + ee$1 = Math.max, + te$1 = Math.min, + ie$1 = function ie() { + return Q$1.Date.now(); + }; +function ne$1(e) { + var t = typeof e; + return !!e && ("object" == t || "function" == t); +} +function re$1(e) { + if ("number" == typeof e) return e; + if (function (e) { + return "symbol" == typeof e || function (e) { + return !!e && "object" == typeof e; + }(e) && "[object Symbol]" == q.call(e); + }(e)) return NaN; + if (ne$1(e)) { + var t = "function" == typeof e.valueOf ? e.valueOf() : e; + e = ne$1(t) ? t + "" : t; + } + if ("string" != typeof e) return 0 === e ? e : +e; + e = e.replace(W$2, ""); + var i = U$1.test(e); + return i || X$1.test(e) ? J(e.slice(2), i ? 2 : 8) : G$1.test(e) ? NaN : +e; +} +var se$1 = function se(e, t, i) { + var n, + r, + s, + o, + a, + u, + h = 0, + c = !1, + l = !1, + f = !0; + if ("function" != typeof e) throw new TypeError("Expected a function"); + function m(t) { + var i = n, + s = r; + return n = r = void 0, h = t, o = e.apply(s, i); + } + function d(e) { + return h = e, a = setTimeout(v, t), c ? m(e) : o; + } + function p(e) { + var i = e - u; + return void 0 === u || i >= t || i < 0 || l && e - h >= s; + } + function v() { + var e = ie$1(); + if (p(e)) return y(e); + a = setTimeout(v, function (e) { + var i = t - (e - u); + return l ? te$1(i, s - (e - h)) : i; + }(e)); + } + function y(e) { + return a = void 0, f && n ? m(e) : (n = r = void 0, o); + } + function g() { + var e = ie$1(), + i = p(e); + if (n = arguments, r = this, u = e, i) { + if (void 0 === a) return d(u); + if (l) return a = setTimeout(v, t), m(u); + } + return void 0 === a && (a = setTimeout(v, t)), o; + } + return t = re$1(t) || 0, ne$1(i) && (c = !!i.leading, s = (l = "maxWait" in i) ? ee$1(re$1(i.maxWait) || 0, t) : s, f = "trailing" in i ? !!i.trailing : f), g.cancel = function () { + void 0 !== a && clearTimeout(a), h = 0, n = u = r = a = void 0; + }, g.flush = function () { + return void 0 === a ? o : y(ie$1()); + }, g; + }, + oe$1 = "sash-module_sash__K-9lB", + ae$1 = "sash-module_disabled__Hm-wx", + ue$2 = "sash-module_mac__Jf6OJ", + he$2 = "sash-module_vertical__pB-rs", + ce$1 = "sash-module_minimum__-UKxp", + le$2 = "sash-module_maximum__TCWxD", + fe$2 = "sash-module_horizontal__kFbiw", + me$2 = "sash-module_hover__80W6I", + de$2 = "sash-module_active__bJspD"; +let pe$1 = function (e) { + return e.Vertical = "VERTICAL", e.Horizontal = "HORIZONTAL", e; + }({}), + ve$2 = function (e) { + return e.Disabled = "DISABLED", e.Minimum = "MINIMUM", e.Maximum = "MAXIMUM", e.Enabled = "ENABLED", e; + }({}), + ye$2 = T$1 ? 20 : 8; +const ge$2 = new H$1(); +let be$2 = class be extends H$1 { + get state() { + return this._state; + } + set state(e) { + this._state !== e && (this.el.classList.toggle(ae$1, e === ve$2.Disabled), this.el.classList.toggle("dash-disabled", e === ve$2.Disabled), this.el.classList.toggle(ce$1, e === ve$2.Minimum), this.el.classList.toggle("sash-minimum", e === ve$2.Minimum), this.el.classList.toggle(le$2, e === ve$2.Maximum), this.el.classList.toggle("sash-maximum", e === ve$2.Maximum), this._state = e, this.emit("enablementChange", e)); + } + constructor(e, t, i) { + var _i$orientation; + super(), this.el = void 0, this.layoutProvider = void 0, this.orientation = void 0, this.size = void 0, this.hoverDelay = 300, this.hoverDelayer = se$1(e => e.classList.add("sash-hover", me$2), this.hoverDelay), this._state = ve$2.Enabled, this.onPointerStart = e => { + const t = e.pageX, + i = e.pageY, + n = { + startX: t, + currentX: t, + startY: i, + currentY: i + }; + this.el.classList.add("sash-active", de$2), this.emit("start", n), this.el.setPointerCapture(e.pointerId); + const r = e => { + e.preventDefault(); + const n = { + startX: t, + currentX: e.pageX, + startY: i, + currentY: e.pageY + }; + this.emit("change", n); + }, + s = e => { + e.preventDefault(), this.el.classList.remove("sash-active", de$2), this.hoverDelayer.cancel(), this.emit("end"), this.el.releasePointerCapture(e.pointerId), window.removeEventListener("pointermove", r), window.removeEventListener("pointerup", s); + }; + window.addEventListener("pointermove", r), window.addEventListener("pointerup", s); + }, this.onPointerDoublePress = () => { + this.emit("reset"); + }, this.onMouseEnter = () => { + this.el.classList.contains(de$2) ? (this.hoverDelayer.cancel(), this.el.classList.add("sash-hover", me$2)) : this.hoverDelayer(this.el); + }, this.onMouseLeave = () => { + this.hoverDelayer.cancel(), this.el.classList.remove("sash-hover", me$2); + }, this.el = document.createElement("div"), this.el.classList.add("sash", oe$1), this.el.dataset.testid = "sash", e.append(this.el), C$2 && this.el.classList.add("sash-mac", ue$2), this.el.addEventListener("pointerdown", this.onPointerStart), this.el.addEventListener("dblclick", this.onPointerDoublePress), this.el.addEventListener("mouseenter", this.onMouseEnter), this.el.addEventListener("mouseleave", this.onMouseLeave), "number" == typeof i.size ? (this.size = i.size, i.orientation === pe$1.Vertical ? this.el.style.width = `${this.size}px` : this.el.style.height = `${this.size}px`) : (this.size = ye$2, ge$2.on("onDidChangeGlobalSize", e => { + this.size = e, this.layout(); + })), this.layoutProvider = t, this.orientation = (_i$orientation = i.orientation) != null ? _i$orientation : pe$1.Vertical, this.orientation === pe$1.Horizontal ? (this.el.classList.add("sash-horizontal", fe$2), this.el.classList.remove("sash-vertical", he$2)) : (this.el.classList.remove("sash-horizontal", fe$2), this.el.classList.add("sash-vertical", he$2)), this.layout(); + } + layout() { + if (this.orientation === pe$1.Vertical) { + const e = this.layoutProvider; + this.el.style.left = e.getVerticalSashLeft(this) - this.size / 2 + "px", e.getVerticalSashTop && (this.el.style.top = e.getVerticalSashTop(this) + "px"), e.getVerticalSashHeight && (this.el.style.height = e.getVerticalSashHeight(this) + "px"); + } else { + const e = this.layoutProvider; + this.el.style.top = e.getHorizontalSashTop(this) - this.size / 2 + "px", e.getHorizontalSashLeft && (this.el.style.left = e.getHorizontalSashLeft(this) + "px"), e.getHorizontalSashWidth && (this.el.style.width = e.getHorizontalSashWidth(this) + "px"); + } + } + dispose() { + this.el.removeEventListener("pointerdown", this.onPointerStart), this.el.removeEventListener("dblclick", this.onPointerDoublePress), this.el.removeEventListener("mouseenter", this.onMouseEnter), this.el.removeEventListener("mouseleave", () => this.onMouseLeave), this.el.remove(); + } +}; +let ze$2; +var we$2; +(we$2 = ze$2 || (ze$2 = {})).Distribute = { + type: "distribute" +}, we$2.Split = function (e) { + return { + type: "split", + index: e + }; +}, we$2.Invisible = function (e) { + return { + type: "invisible", + cachedVisibleSize: e + }; +}; +let Se$2 = function (e) { + return e.Normal = "NORMAL", e.Low = "LOW", e.High = "HIGH", e; +}({}); +let _e$1 = class _e { + constructor(e, t, i) { + this.container = void 0, this.view = void 0, this._size = void 0, this._cachedVisibleSize = void 0, this.container = e, this.view = t, this.container.classList.add("split-view-view", N$1), this.container.dataset.testid = "split-view-view", "number" == typeof i ? (this._size = i, this._cachedVisibleSize = void 0, e.classList.add("split-view-view-visible")) : (this._size = 0, this._cachedVisibleSize = i.cachedVisibleSize); + } + set size(e) { + this._size = e; + } + get size() { + return this._size; + } + get priority() { + return this.view.priority; + } + get snap() { + return !!this.view.snap; + } + get cachedVisibleSize() { + return this._cachedVisibleSize; + } + get visible() { + return void 0 === this._cachedVisibleSize; + } + setVisible(e, t) { + e !== this.visible && (e ? (this.size = z$1(this._cachedVisibleSize, this.viewMinimumSize, this.viewMaximumSize), this._cachedVisibleSize = void 0) : (this._cachedVisibleSize = "number" == typeof t ? t : this.size, this.size = 0), this.container.classList.toggle("split-view-view-visible", e), this.view.setVisible && this.view.setVisible(e)); + } + get minimumSize() { + return this.visible ? this.view.minimumSize : 0; + } + get viewMinimumSize() { + return this.view.minimumSize; + } + get maximumSize() { + return this.visible ? this.view.maximumSize : 0; + } + get viewMaximumSize() { + return this.view.maximumSize; + } + set enabled(e) { + this.container.style.pointerEvents = e ? "" : "none"; + } + layout(e) { + this.layoutContainer(e), this.view.layout(this.size, e); + } +}; +let Ie$2 = class Ie extends _e$1 { + layoutContainer(e) { + this.container.style.left = `${e}px`, this.container.style.width = `${this.size}px`; + } +}; +let xe$2 = class xe extends _e$1 { + layoutContainer(e) { + this.container.style.top = `${e}px`, this.container.style.height = `${this.size}px`; + } +}; +let Ee$2 = class Ee extends H$1 { + get startSnappingEnabled() { + return this._startSnappingEnabled; + } + set startSnappingEnabled(e) { + this._startSnappingEnabled !== e && (this._startSnappingEnabled = e, this.updateSashEnablement()); + } + get endSnappingEnabled() { + return this._endSnappingEnabled; + } + set endSnappingEnabled(e) { + this._endSnappingEnabled !== e && (this._endSnappingEnabled = e, this.updateSashEnablement()); + } + constructor(e, t = {}, i, n, r) { + var _t$orientation, _t$proportionalLayout; + if (super(), this.onDidChange = void 0, this.onDidDragStart = void 0, this.onDidDragEnd = void 0, this.orientation = void 0, this.sashContainer = void 0, this.size = 0, this.contentSize = 0, this.proportions = void 0, this.viewItems = [], this.sashItems = [], this.sashDragState = void 0, this.proportionalLayout = void 0, this.getSashOrthogonalSize = void 0, this._startSnappingEnabled = !0, this._endSnappingEnabled = !0, this.onSashEnd = e => { + this.emit("sashchange", e), this.saveProportions(); + for (const _e2 of this.viewItems) _e2.enabled = !0; + }, this.orientation = (_t$orientation = t.orientation) != null ? _t$orientation : pe$1.Vertical, this.proportionalLayout = (_t$proportionalLayout = t.proportionalLayout) != null ? _t$proportionalLayout : !0, this.getSashOrthogonalSize = t.getSashOrthogonalSize, i && (this.onDidChange = i), n && (this.onDidDragStart = n), r && (this.onDidDragEnd = r), this.sashContainer = document.createElement("div"), this.sashContainer.classList.add("sash-container", V$1), e.prepend(this.sashContainer), t.descriptor) { + this.size = t.descriptor.size; + for (const [_e3, _i] of t.descriptor.views.entries()) { + const _t = _i.size, + _n = _i.container, + _r = _i.view; + this.addView(_n, _r, _t, _e3, !0); + } + this.contentSize = this.viewItems.reduce((e, t) => e + t.size, 0), this.saveProportions(); + } + } + addView(e, t, i, n = this.viewItems.length, r) { + let s; + s = "number" == typeof i ? i : "split" === i.type ? this.getViewSize(i.index) / 2 : "invisible" === i.type ? { + cachedVisibleSize: i.cachedVisibleSize + } : t.minimumSize; + const o = this.orientation === pe$1.Vertical ? new xe$2(e, t, s) : new Ie$2(e, t, s); + if (this.viewItems.splice(n, 0, o), this.viewItems.length > 1) { + const _e4 = this.orientation === pe$1.Vertical ? new be$2(this.sashContainer, { + getHorizontalSashTop: e => this.getSashPosition(e), + getHorizontalSashWidth: this.getSashOrthogonalSize + }, { + orientation: pe$1.Horizontal + }) : new be$2(this.sashContainer, { + getVerticalSashLeft: e => this.getSashPosition(e), + getVerticalSashHeight: this.getSashOrthogonalSize + }, { + orientation: pe$1.Vertical + }), + _t2 = this.orientation === pe$1.Vertical ? t => ({ + sash: _e4, + start: t.startY, + current: t.currentY + }) : t => ({ + sash: _e4, + start: t.startX, + current: t.currentX + }); + _e4.on("start", e => { + var _this$onDidDragStart; + this.emit("sashDragStart"), this.onSashStart(_t2(e)); + const i = this.viewItems.map(e => e.size); + (_this$onDidDragStart = this.onDidDragStart) == null ? void 0 : _this$onDidDragStart.call(this, i); + }), _e4.on("change", e => this.onSashChange(_t2(e))), _e4.on("end", () => { + var _this$onDidDragEnd; + this.emit("sashDragEnd"), this.onSashEnd(this.sashItems.findIndex(t => t.sash === _e4)); + const t = this.viewItems.map(e => e.size); + (_this$onDidDragEnd = this.onDidDragEnd) == null ? void 0 : _this$onDidDragEnd.call(this, t); + }), _e4.on("reset", () => { + const t = this.sashItems.findIndex(t => t.sash === _e4), + i = R$1(t, -1, -1), + n = R$1(t + 1, this.viewItems.length), + r = this.findFirstSnapIndex(i), + s = this.findFirstSnapIndex(n); + ("number" != typeof r || this.viewItems[r].visible) && ("number" != typeof s || this.viewItems[s].visible) && this.emit("sashreset", t); + }); + const _i2 = { + sash: _e4 + }; + this.sashItems.splice(n - 1, 0, _i2); + } + r || this.relayout(), r || "number" == typeof i || "distribute" !== i.type || this.distributeViewSizes(); + } + removeView(e, t) { + if (e < 0 || e >= this.viewItems.length) throw new Error("Index out of bounds"); + const i = this.viewItems.splice(e, 1)[0].view; + if (this.viewItems.length >= 1) { + const _t3 = Math.max(e - 1, 0); + this.sashItems.splice(_t3, 1)[0].sash.dispose(); + } + return this.relayout(), t && "distribute" === t.type && this.distributeViewSizes(), i; + } + moveView(e, t, i) { + const n = this.getViewCachedVisibleSize(t), + r = void 0 === n ? this.getViewSize(t) : ze$2.Invisible(n), + s = this.removeView(t); + this.addView(e, s, r, i); + } + getViewCachedVisibleSize(e) { + if (e < 0 || e >= this.viewItems.length) throw new Error("Index out of bounds"); + return this.viewItems[e].cachedVisibleSize; + } + layout(e = this.size) { + const t = Math.max(this.size, this.contentSize); + if (this.size = e, this.proportions) for (let _t4 = 0; _t4 < this.viewItems.length; _t4++) { + const i = this.viewItems[_t4]; + i.size = z$1(Math.round(this.proportions[_t4] * e), i.minimumSize, i.maximumSize); + } else { + const i = R$1(0, this.viewItems.length), + n = i.filter(e => this.viewItems[e].priority === Se$2.Low), + r = i.filter(e => this.viewItems[e].priority === Se$2.High); + this.resize(this.viewItems.length - 1, e - t, void 0, n, r); + } + this.distributeEmptySpace(), this.layoutViews(); + } + resizeView(e, t) { + if (e < 0 || e >= this.viewItems.length) return; + const i = R$1(0, this.viewItems.length).filter(t => t !== e), + n = [...i.filter(e => this.viewItems[e].priority === Se$2.Low), e], + r = i.filter(e => this.viewItems[e].priority === Se$2.High), + s = this.viewItems[e]; + t = Math.round(t), t = z$1(t, s.minimumSize, Math.min(s.maximumSize, this.size)), s.size = t, this.relayout(n, r); + } + resizeViews(e) { + for (let t = 0; t < e.length; t++) { + const i = this.viewItems[t]; + let n = e[t]; + n = Math.round(n), n = z$1(n, i.minimumSize, Math.min(i.maximumSize, this.size)), i.size = n; + } + this.contentSize = this.viewItems.reduce((e, t) => e + t.size, 0), this.saveProportions(), this.layout(this.size); + } + getViewSize(e) { + return e < 0 || e >= this.viewItems.length ? -1 : this.viewItems[e].size; + } + isViewVisible(e) { + if (e < 0 || e >= this.viewItems.length) throw new Error("Index out of bounds"); + return this.viewItems[e].visible; + } + setViewVisible(e, t) { + if (e < 0 || e >= this.viewItems.length) throw new Error("Index out of bounds"); + this.viewItems[e].setVisible(t), this.distributeEmptySpace(e), this.layoutViews(), this.saveProportions(); + } + distributeViewSizes() { + const e = []; + let t = 0; + for (const _i3 of this.viewItems) _i3.maximumSize - _i3.minimumSize > 0 && (e.push(_i3), t += _i3.size); + const i = Math.floor(t / e.length); + for (const _t5 of e) _t5.size = z$1(i, _t5.minimumSize, _t5.maximumSize); + const n = R$1(0, this.viewItems.length), + r = n.filter(e => this.viewItems[e].priority === Se$2.Low), + s = n.filter(e => this.viewItems[e].priority === Se$2.High); + this.relayout(r, s); + } + dispose() { + this.sashItems.forEach(e => e.sash.dispose()), this.sashItems = [], this.sashContainer.remove(); + } + relayout(e, t) { + const i = this.viewItems.reduce((e, t) => e + t.size, 0); + this.resize(this.viewItems.length - 1, this.size - i, void 0, e, t), this.distributeEmptySpace(), this.layoutViews(), this.saveProportions(); + } + onSashStart({ + sash: e, + start: t + }) { + const i = this.sashItems.findIndex(t => t.sash === e); + (e => { + const t = this.viewItems.map(e => e.size); + let n, + r, + s = Number.NEGATIVE_INFINITY, + o = Number.POSITIVE_INFINITY; + const a = R$1(i, -1, -1), + u = R$1(i + 1, this.viewItems.length), + h = a.reduce((e, i) => e + (this.viewItems[i].minimumSize - t[i]), 0), + c = a.reduce((e, i) => e + (this.viewItems[i].viewMaximumSize - t[i]), 0), + l = 0 === u.length ? Number.POSITIVE_INFINITY : u.reduce((e, i) => e + (t[i] - this.viewItems[i].minimumSize), 0), + f = 0 === u.length ? Number.NEGATIVE_INFINITY : u.reduce((e, i) => e + (t[i] - this.viewItems[i].viewMaximumSize), 0); + s = Math.max(h, f), o = Math.min(l, c); + const m = this.findFirstSnapIndex(a), + d = this.findFirstSnapIndex(u); + if ("number" == typeof m) { + const _e5 = this.viewItems[m], + _t6 = Math.floor(_e5.viewMinimumSize / 2); + n = { + index: m, + limitDelta: _e5.visible ? s - _t6 : s + _t6, + size: _e5.size + }; + } + if ("number" == typeof d) { + const _e6 = this.viewItems[d], + _t7 = Math.floor(_e6.viewMinimumSize / 2); + r = { + index: d, + limitDelta: _e6.visible ? o + _t7 : o - _t7, + size: _e6.size + }; + } + this.sashDragState = { + start: e, + current: e, + index: i, + sizes: t, + minDelta: s, + maxDelta: o, + snapBefore: n, + snapAfter: r + }; + })(t); + } + onSashChange({ + current: e + }) { + const { + index: t, + start: i, + sizes: n, + minDelta: r, + maxDelta: s, + snapBefore: o, + snapAfter: a + } = this.sashDragState; + this.sashDragState.current = e; + const u = e - i; + this.resize(t, u, n, void 0, void 0, r, s, o, a), this.distributeEmptySpace(), this.layoutViews(); + } + getSashPosition(e) { + let t = 0; + for (let i = 0; i < this.sashItems.length; i++) if (t += this.viewItems[i].size, this.sashItems[i].sash === e) return t; + return 0; + } + resize(e, t, i = this.viewItems.map(e => e.size), n, r, s = Number.NEGATIVE_INFINITY, o = Number.POSITIVE_INFINITY, a, u) { + if (e < 0 || e >= this.viewItems.length) return 0; + const h = R$1(e, -1, -1), + c = R$1(e + 1, this.viewItems.length); + if (r) for (const _e7 of r) Y$1(h, _e7), Y$1(c, _e7); + if (n) for (const _e8 of n) B$1(h, _e8), B$1(c, _e8); + const l = h.map(e => this.viewItems[e]), + f = h.map(e => i[e]), + m = c.map(e => this.viewItems[e]), + d = c.map(e => i[e]), + p = h.reduce((e, t) => e + (this.viewItems[t].minimumSize - i[t]), 0), + v = h.reduce((e, t) => e + (this.viewItems[t].maximumSize - i[t]), 0), + y = 0 === c.length ? Number.POSITIVE_INFINITY : c.reduce((e, t) => e + (i[t] - this.viewItems[t].minimumSize), 0), + g = 0 === c.length ? Number.NEGATIVE_INFINITY : c.reduce((e, t) => e + (i[t] - this.viewItems[t].maximumSize), 0), + b = Math.max(p, g, s), + w = Math.min(y, v, o); + let S = !1; + if (a) { + const _e9 = this.viewItems[a.index], + _i4 = t >= a.limitDelta; + S = _i4 !== _e9.visible, _e9.setVisible(_i4, a.size); + } + if (!S && u) { + const _e10 = this.viewItems[u.index], + _i5 = t < u.limitDelta; + S = _i5 !== _e10.visible, _e10.setVisible(_i5, u.size); + } + if (S) return this.resize(e, t, i, n, r, s, o); + for (let _e11 = 0, _i6 = t = z$1(t, b, w); _e11 < l.length; _e11++) { + const _t8 = l[_e11], + _n2 = z$1(f[_e11] + _i6, _t8.minimumSize, _t8.maximumSize); + _i6 -= _n2 - f[_e11], _t8.size = _n2; + } + for (let _e12 = 0, _i7 = t; _e12 < m.length; _e12++) { + const _t9 = m[_e12], + _n3 = z$1(d[_e12] - _i7, _t9.minimumSize, _t9.maximumSize); + _i7 += _n3 - d[_e12], _t9.size = _n3; + } + return t; + } + distributeEmptySpace(e) { + const t = this.viewItems.reduce((e, t) => e + t.size, 0); + let i = this.size - t; + const n = R$1(this.viewItems.length - 1, -1, -1); + "number" == typeof e && B$1(n, e); + for (let _e13 = 0; 0 !== i && _e13 < n.length; _e13++) { + const _t10 = this.viewItems[n[_e13]], + r = z$1(_t10.size + i, _t10.minimumSize, _t10.maximumSize); + i -= r - _t10.size, _t10.size = r; + } + } + layoutViews() { + var _this$onDidChange; + this.contentSize = this.viewItems.reduce((e, t) => e + t.size, 0); + let e = 0; + for (const t of this.viewItems) t.layout(e), e += t.size; + (_this$onDidChange = this.onDidChange) != null && _this$onDidChange.call(this, this.viewItems.map(e => e.size)), this.sashItems.forEach(e => e.sash.layout()), this.updateSashEnablement(); + } + saveProportions() { + this.proportionalLayout && this.contentSize > 0 && (this.proportions = this.viewItems.map(e => e.size / this.contentSize)); + } + updateSashEnablement() { + let e = !1; + const t = this.viewItems.map(t => e = t.size - t.minimumSize > 0 || e); + e = !1; + const i = this.viewItems.map(t => e = t.maximumSize - t.size > 0 || e), + n = [...this.viewItems].reverse(); + e = !1; + const r = n.map(t => e = t.size - t.minimumSize > 0 || e).reverse(); + e = !1; + const s = n.map(t => e = t.maximumSize - t.size > 0 || e).reverse(); + let o = 0; + for (let _e14 = 0; _e14 < this.sashItems.length; _e14++) { + const { + sash: _n4 + } = this.sashItems[_e14]; + o += this.viewItems[_e14].size; + const a = !(t[_e14] && s[_e14 + 1]), + u = !(i[_e14] && r[_e14 + 1]); + if (a && u) { + const _i8 = R$1(_e14, -1, -1), + _s = R$1(_e14 + 1, this.viewItems.length), + _a = this.findFirstSnapIndex(_i8), + _u = this.findFirstSnapIndex(_s), + h = "number" == typeof _a && !this.viewItems[_a].visible, + c = "number" == typeof _u && !this.viewItems[_u].visible; + h && r[_e14] && (o > 0 || this.startSnappingEnabled) ? _n4.state = ve$2.Minimum : c && t[_e14] && (o < this.contentSize || this.endSnappingEnabled) ? _n4.state = ve$2.Maximum : _n4.state = ve$2.Disabled; + } else _n4.state = a && !u ? ve$2.Minimum : !a && u ? ve$2.Maximum : ve$2.Enabled; + } + } + findFirstSnapIndex(e) { + for (const t of e) { + const _e15 = this.viewItems[t]; + if (_e15.visible && _e15.snap) return t; + } + for (const t of e) { + const _e16 = this.viewItems[t]; + if (_e16.visible && _e16.maximumSize - _e16.minimumSize > 0) return; + if (!_e16.visible && _e16.snap) return t; + } + } +}; +let Ve$2 = class Ve { + constructor(e) { + this.size = void 0, this.size = e; + } + getPreferredSize() { + return this.size; + } +}; +let je$2 = class je { + constructor(e, t) { + this.proportion = void 0, this.layoutService = void 0, this.proportion = e, this.layoutService = t; + } + getPreferredSize() { + return this.proportion * this.layoutService.getSize(); + } +}; +let Ne$2 = class Ne { + getPreferredSize() {} +}; +let Le$2 = class Le { + get preferredSize() { + return this.layoutStrategy.getPreferredSize(); + } + set preferredSize(e) { + if ("number" == typeof e) this.layoutStrategy = new Ve$2(e);else if ("string" == typeof e) { + const t = e.trim(); + if ($(t, "%")) { + const _e17 = Number(t.slice(0, -1)) / 100; + this.layoutStrategy = new je$2(_e17, this.layoutService); + } else if ($(t, "px")) { + const _e18 = Number(t.slice(0, -2)) / 100; + this.layoutStrategy = new Ve$2(_e18); + } else if ("number" == typeof Number.parseFloat(t)) { + const _e19 = Number.parseFloat(t); + this.layoutStrategy = new Ve$2(_e19); + } else this.layoutStrategy = new Ne$2(); + } else this.layoutStrategy = new Ne$2(); + } + constructor(e, t) { + var _t$priority; + if (this.minimumSize = 0, this.maximumSize = Number.POSITIVE_INFINITY, this.element = void 0, this.priority = void 0, this.snap = void 0, this.layoutService = void 0, this.layoutStrategy = void 0, this.layoutService = e, this.element = t.element, this.minimumSize = "number" == typeof t.minimumSize ? t.minimumSize : 30, this.maximumSize = "number" == typeof t.maximumSize ? t.maximumSize : Number.POSITIVE_INFINITY, "number" == typeof t.preferredSize) this.layoutStrategy = new Ve$2(t.preferredSize);else if ("string" == typeof t.preferredSize) { + const _e20 = t.preferredSize.trim(); + if ($(_e20, "%")) { + const _t11 = Number(_e20.slice(0, -1)) / 100; + this.layoutStrategy = new je$2(_t11, this.layoutService); + } else if ($(_e20, "px")) { + const _t12 = Number(_e20.slice(0, -2)); + this.layoutStrategy = new Ve$2(_t12); + } else if ("number" == typeof Number.parseFloat(_e20)) { + const _t13 = Number.parseFloat(_e20); + this.layoutStrategy = new Ve$2(_t13); + } else this.layoutStrategy = new Ne$2(); + } else this.layoutStrategy = new Ne$2(); + this.priority = (_t$priority = t.priority) != null ? _t$priority : Se$2.Normal, this.snap = "boolean" == typeof t.snap && t.snap; + } + layout(e) {} +}; +function De$2(e) { + return void 0 !== e.minSize || void 0 !== e.maxSize || void 0 !== e.preferredSize || void 0 !== e.priority || void 0 !== e.visible; +} +const Oe$2 = reactExports.forwardRef(({ + className: t, + children: i +}, n) => React.createElement("div", { + ref: n, + className: l$1("split-view-view", N$1, t) +}, i)); +Oe$2.displayName = "Allotment.Pane"; +const Me$2 = reactExports.forwardRef(({ + children: o, + className: a, + maxSize: h = 1 / 0, + minSize: c = 30, + proportionalLayout: f = !0, + separator: m = !0, + sizes: d, + defaultSizes: p = d, + snap: v = !1, + vertical: y = !1, + onChange: g, + onReset: b, + onVisibleChange: z, + onDragStart: w, + onDragEnd: S +}, I) => { + const V = reactExports.useRef(null), + N = reactExports.useRef([]), + M = reactExports.useRef(new Map()), + P = reactExports.useRef(null), + A = reactExports.useRef(new Map()), + C = reactExports.useRef(new k$1()), + $ = reactExports.useRef([]), + [H, Y] = reactExports.useState(!1); + const B = reactExports.useMemo(() => React.Children.toArray(o).filter(React.isValidElement), [o]), + R = reactExports.useCallback(e => { + var _$$current, _P$current; + const t = (_$$current = $.current) == null ? void 0 : _$$current[e]; + return "number" == typeof (t == null ? void 0 : t.preferredSize) && ((_P$current = P.current) != null && _P$current.resizeView(e, Math.round(t.preferredSize)), !0); + }, []); + return reactExports.useImperativeHandle(I, () => ({ + reset: () => { + if (b) b();else { + var _P$current2; + (_P$current2 = P.current) == null ? void 0 : _P$current2.distributeViewSizes(); + for (let e = 0; e < $.current.length; e++) R(e); + } + }, + resize: e => { + var _P$current3; + (_P$current3 = P.current) == null ? void 0 : _P$current3.resizeViews(e); + } + })), F$1(() => { + let e = !0; + p && A.current.size !== p.length && (e = !1, console.warn(`Expected ${p.length} children based on defaultSizes but found ${A.current.size}`)), e && p && (N.current = B.map(e => e.key)); + const t = _extends$2({ + orientation: y ? pe$1.Vertical : pe$1.Horizontal, + proportionalLayout: f + }, e && p && { + descriptor: { + size: p.reduce((e, t) => e + t, 0), + views: p.map((e, t) => { + var _i$minSize, _i$maxSize, _i$priority, _i$snap; + const i = M.current.get(N.current[t]), + n = new Le$2(C.current, _extends$2({ + element: document.createElement("div"), + minimumSize: (_i$minSize = i == null ? void 0 : i.minSize) != null ? _i$minSize : c, + maximumSize: (_i$maxSize = i == null ? void 0 : i.maxSize) != null ? _i$maxSize : h, + priority: (_i$priority = i == null ? void 0 : i.priority) != null ? _i$priority : Se$2.Normal + }, (i == null ? void 0 : i.preferredSize) && { + preferredSize: i == null ? void 0 : i.preferredSize + }, { + snap: (_i$snap = i == null ? void 0 : i.snap) != null ? _i$snap : v + })); + return $.current.push(n), { + container: [...A.current.values()][t], + size: e, + view: n + }; + }) + } + }); + P.current = new Ee$2(V.current, t, g, w, S), P.current.on("sashDragStart", () => { + var _V$current; + (_V$current = V.current) == null ? void 0 : _V$current.classList.add("split-view-sash-dragging"); + }), P.current.on("sashDragEnd", () => { + var _V$current2; + (_V$current2 = V.current) == null ? void 0 : _V$current2.classList.remove("split-view-sash-dragging"); + }), P.current.on("sashchange", e => { + if (z && P.current) { + const _e21 = B.map(e => e.key); + for (let t = 0; t < _e21.length; t++) { + const i = M.current.get(_e21[t]); + void 0 !== (i == null ? void 0 : i.visible) && i.visible !== P.current.isViewVisible(t) && z(t, P.current.isViewVisible(t)); + } + } + }), P.current.on("sashreset", e => { + if (b) b();else { + var _P$current4; + if (R(e)) return; + if (R(e + 1)) return; + (_P$current4 = P.current) == null ? void 0 : _P$current4.distributeViewSizes(); + } + }); + const i = P.current; + return () => { + i.dispose(); + }; + }, []), F$1(() => { + if (H) { + const e = B.map(e => e.key), + t = [...N.current], + i = e.filter(e => !N.current.includes(e)), + n = e.filter(e => N.current.includes(e)), + r = N.current.map(t => !e.includes(t)); + for (let _e22 = r.length - 1; _e22 >= 0; _e22--) { + var _P$current5; + r[_e22] && ((_P$current5 = P.current) != null && _P$current5.removeView(_e22), t.splice(_e22, 1), $.current.splice(_e22, 1)); + } + for (const _n5 of i) { + var _i9$minSize, _i9$maxSize, _i9$priority, _i9$snap, _P$current6; + const _i9 = M.current.get(_n5), + _r2 = new Le$2(C.current, _extends$2({ + element: document.createElement("div"), + minimumSize: (_i9$minSize = _i9 == null ? void 0 : _i9.minSize) != null ? _i9$minSize : c, + maximumSize: (_i9$maxSize = _i9 == null ? void 0 : _i9.maxSize) != null ? _i9$maxSize : h, + priority: (_i9$priority = _i9 == null ? void 0 : _i9.priority) != null ? _i9$priority : Se$2.Normal + }, (_i9 == null ? void 0 : _i9.preferredSize) && { + preferredSize: _i9 == null ? void 0 : _i9.preferredSize + }, { + snap: (_i9$snap = _i9 == null ? void 0 : _i9.snap) != null ? _i9$snap : v + })); + (_P$current6 = P.current) != null && _P$current6.addView(A.current.get(_n5), _r2, ze$2.Distribute, e.findIndex(e => e === _n5)), t.splice(e.findIndex(e => e === _n5), 0, _n5), $.current.splice(e.findIndex(e => e === _n5), 0, _r2); + } + for (; !_(e, t);) for (const [_i10, _n6] of e.entries()) { + const _e23 = t.findIndex(e => e === _n6); + if (_e23 !== _i10) { + var _P$current7; + (_P$current7 = P.current) == null ? void 0 : _P$current7.moveView(A.current.get(_n6), _e23, _i10); + const _r3 = t[_e23]; + t.splice(_e23, 1), t.splice(_i10, 0, _r3); + break; + } + } + for (const _t14 of i) { + var _P$current8; + const _i11 = e.findIndex(e => e === _t14), + _n7 = $.current[_i11].preferredSize; + void 0 !== _n7 && ((_P$current8 = P.current) == null ? void 0 : _P$current8.resizeView(_i11, _n7)); + } + for (const _t15 of [...i, ...n]) { + var _P$current9, _P$current10; + const _i12 = M.current.get(_t15), + _n8 = e.findIndex(e => e === _t15); + _i12 && De$2(_i12) && void 0 !== _i12.visible && ((_P$current9 = P.current) == null ? void 0 : _P$current9.isViewVisible(_n8)) !== _i12.visible && ((_P$current10 = P.current) == null ? void 0 : _P$current10.setViewVisible(_n8, _i12.visible)); + } + for (const _t16 of n) { + const _i13 = M.current.get(_t16), + _n9 = e.findIndex(e => e === _t16); + if (_i13 && De$2(_i13)) { + var _P$current11; + void 0 !== _i13.preferredSize && $.current[_n9].preferredSize !== _i13.preferredSize && ($.current[_n9].preferredSize = _i13.preferredSize); + let _e24 = !1; + void 0 !== _i13.minSize && $.current[_n9].minimumSize !== _i13.minSize && ($.current[_n9].minimumSize = _i13.minSize, _e24 = !0), void 0 !== _i13.maxSize && $.current[_n9].maximumSize !== _i13.maxSize && ($.current[_n9].maximumSize = _i13.maxSize, _e24 = !0), _e24 && ((_P$current11 = P.current) == null ? void 0 : _P$current11.layout()); + } + } + (i.length > 0 || r.length > 0) && (N.current = e); + } + }, [B, H, h, c, v]), reactExports.useEffect(() => { + P.current && (P.current.onDidChange = g); + }, [g]), reactExports.useEffect(() => { + P.current && (P.current.onDidDragStart = w); + }, [w]), reactExports.useEffect(() => { + P.current && (P.current.onDidDragEnd = S); + }, [S]), x({ + ref: V, + onResize: ({ + width: e, + height: t + }) => { + var _P$current12; + e && t && ((_P$current12 = P.current) != null && _P$current12.layout(y ? t : e), C.current.setSize(y ? t : e), Y(!0)); + } + }), F$1(() => { + if (!H) { + var _P$current13; + const { + height: e, + width: t + } = V.current.getBoundingClientRect(); + (_P$current13 = P.current) != null && _P$current13.layout(y ? e : t), C.current.setSize(y ? e : t), Y(!0); + } + }, [H, y]), reactExports.useEffect(() => { + T$1 && Pe$2(20); + }, []), React.createElement("div", { + ref: V, + className: l$1("split-view", y ? "split-view-vertical" : "split-view-horizontal", { + "split-view-separator-border": m + }, E$2, y ? L$1 : D$1, { + [O$1]: m + }, a) + }, React.createElement("div", { + className: l$1("split-view-container", j$1) + }, React.Children.toArray(o).map(t => { + if (!React.isValidElement(t)) return null; + const i = t.key; + return "Allotment.Pane" === t.type.displayName ? (M.current.set(i, t.props), React.cloneElement(t, { + key: i, + ref: e => { + e ? A.current.set(i, e) : A.current.delete(i); + } + })) : React.createElement(Oe$2, { + key: i, + ref: e => { + e ? A.current.set(i, e) : A.current.delete(i); + } + }, t); + }))); +}); +function Pe$2(e) { + const t = z$1(e, 4, 20), + i = z$1(e, 1, 8); + document.documentElement.style.setProperty("--sash-size", t + "px"), document.documentElement.style.setProperty("--sash-hover-size", i + "px"), function (e) { + ye$2 = e, ge$2.emit("onDidChangeGlobalSize", e); + }(t); +} +Me$2.displayName = "Allotment"; +var Ae$2 = Object.assign(Me$2, { + Pane: Oe$2 +}); + +var reactDom$1 = {exports: {}}; + +var reactDom_production_min$1 = {}; + +var scheduler$1 = {exports: {}}; + +var scheduler_production_min$1 = {}; + +/** + * @license React + * scheduler.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +(function (exports) { +function f(a,b){var c=a.length;a.push(b);a:for(;0>>1,e=a[d];if(0>>1;dg(C,c))ng(x,C)?(a[d]=x,a[n]=c,d=n):(a[d]=C,a[m]=c,d=m);else if(ng(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b} + function g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}if("object"===typeof performance&&"function"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now()};}else {var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q};}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D="function"===typeof setTimeout?setTimeout:null,E="function"===typeof clearTimeout?clearTimeout:null,F="undefined"!==typeof setImmediate?setImmediate:null; + "undefined"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t);}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else {var b=h(t);null!==b&&K(H,b.startTime-a);}} + function J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if("function"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();"function"===typeof e?v.callback=e:v===h(r)&&k(r);G(b);}else k(r);v=h(r);}if(null!==v)var w=!0;else {var m=h(t);null!==m&&K(H,m.startTime-b);w=!1;}return w}finally{v=null,y=c,z=!1;}}var N=!1,O=null,L=-1,P=5,Q=-1; + function M(){return exports.unstable_now()-Qa||125d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a}; + exports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c;}}}; +} (scheduler_production_min$1)); + +{ + scheduler$1.exports = scheduler_production_min$1; +} + +var schedulerExports = scheduler$1.exports; + +/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +var aa=reactExports,ca=schedulerExports;function p(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;cb}return !1}function v$1(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g;}var z={}; +"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){z[a]=new v$1(a,0,!1,a,null,!1,!1);});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];z[b]=new v$1(b,1,!1,a[1],null,!1,!1);});["contentEditable","draggable","spellCheck","value"].forEach(function(a){z[a]=new v$1(a,2,!1,a.toLowerCase(),null,!1,!1);}); +["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){z[a]=new v$1(a,2,!1,a,null,!1,!1);});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){z[a]=new v$1(a,3,!1,a.toLowerCase(),null,!1,!1);}); +["checked","multiple","muted","selected"].forEach(function(a){z[a]=new v$1(a,3,!0,a,null,!1,!1);});["capture","download"].forEach(function(a){z[a]=new v$1(a,4,!1,a,null,!1,!1);});["cols","rows","size","span"].forEach(function(a){z[a]=new v$1(a,6,!1,a,null,!1,!1);});["rowSpan","start"].forEach(function(a){z[a]=new v$1(a,5,!1,a.toLowerCase(),null,!1,!1);});var ra=/[\-:]([a-z])/g;function sa(a){return a[1].toUpperCase()} +"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=a.replace(ra, +sa);z[b]=new v$1(b,1,!1,a,null,!1,!1);});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(ra,sa);z[b]=new v$1(b,1,!1,a,"http://www.w3.org/1999/xlink",!1,!1);});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(ra,sa);z[b]=new v$1(b,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1,!1);});["tabIndex","crossOrigin"].forEach(function(a){z[a]=new v$1(a,1,!1,a.toLowerCase(),null,!1,!1);}); +z.xlinkHref=new v$1("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(a){z[a]=new v$1(a,1,!1,a.toLowerCase(),null,!0,!0);}); +function ta(a,b,c,d){var e=z.hasOwnProperty(b)?z[b]:null;if(null!==e?0!==e.type:d||!(2h||e[g]!==f[h]){var k="\n"+e[g].replace(" at new "," at ");a.displayName&&k.includes("")&&(k=k.replace("",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{Na=!1,Error.prepareStackTrace=c;}return (a=a?a.displayName||a.name:"")?Ma(a):""} +function Pa(a){switch(a.tag){case 5:return Ma(a.type);case 16:return Ma("Lazy");case 13:return Ma("Suspense");case 19:return Ma("SuspenseList");case 0:case 2:case 15:return a=Oa(a.type,!1),a;case 11:return a=Oa(a.type.render,!1),a;case 1:return a=Oa(a.type,!0),a;default:return ""}} +function Qa(a){if(null==a)return null;if("function"===typeof a)return a.displayName||a.name||null;if("string"===typeof a)return a;switch(a){case ya:return "Fragment";case wa:return "Portal";case Aa:return "Profiler";case za:return "StrictMode";case Ea:return "Suspense";case Fa:return "SuspenseList"}if("object"===typeof a)switch(a.$$typeof){case Ca:return (a.displayName||"Context")+".Consumer";case Ba:return (a._context.displayName||"Context")+".Provider";case Da:var b=a.render;a=a.displayName;a||(a=b.displayName|| +b.name||"",a=""!==a?"ForwardRef("+a+")":"ForwardRef");return a;case Ga:return b=a.displayName||null,null!==b?b:Qa(a.type)||"Memo";case Ha:b=a._payload;a=a._init;try{return Qa(a(b))}catch(c){}}return null} +function Ra(a){var b=a.type;switch(a.tag){case 24:return "Cache";case 9:return (b.displayName||"Context")+".Consumer";case 10:return (b._context.displayName||"Context")+".Provider";case 18:return "DehydratedFragment";case 11:return a=b.render,a=a.displayName||a.name||"",b.displayName||(""!==a?"ForwardRef("+a+")":"ForwardRef");case 7:return "Fragment";case 5:return b;case 4:return "Portal";case 3:return "Root";case 6:return "Text";case 16:return Qa(b);case 8:return b===za?"StrictMode":"Mode";case 22:return "Offscreen"; +case 12:return "Profiler";case 21:return "Scope";case 13:return "Suspense";case 19:return "SuspenseList";case 25:return "TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if("function"===typeof b)return b.displayName||b.name||null;if("string"===typeof b)return b}return null}function Sa(a){switch(typeof a){case "boolean":case "number":case "string":case "undefined":return a;case "object":return a;default:return ""}} +function Ta(a){var b=a.type;return (a=a.nodeName)&&"input"===a.toLowerCase()&&("checkbox"===b||"radio"===b)} +function Ua(a){var b=Ta(a)?"checked":"value",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=""+a[b];if(!a.hasOwnProperty(b)&&"undefined"!==typeof c&&"function"===typeof c.get&&"function"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=""+a;f.call(this,a);}});Object.defineProperty(a,b,{enumerable:c.enumerable});return {getValue:function(){return d},setValue:function(a){d=""+a;},stopTracking:function(){a._valueTracker= +null;delete a[b];}}}}function Va(a){a._valueTracker||(a._valueTracker=Ua(a));}function Wa(a){if(!a)return !1;var b=a._valueTracker;if(!b)return !0;var c=b.getValue();var d="";a&&(d=Ta(a)?a.checked?"true":"false":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}function Xa(a){a=a||("undefined"!==typeof document?document:void 0);if("undefined"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}} +function Ya(a,b){var c=b.checked;return A$1({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}function Za(a,b){var c=null==b.defaultValue?"":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=Sa(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:"checkbox"===b.type||"radio"===b.type?null!=b.checked:null!=b.value};}function ab(a,b){b=b.checked;null!=b&&ta(a,"checked",b,!1);} +function bb(a,b){ab(a,b);var c=Sa(b.value),d=b.type;if(null!=c)if("number"===d){if(0===c&&""===a.value||a.value!=c)a.value=""+c;}else a.value!==""+c&&(a.value=""+c);else if("submit"===d||"reset"===d){a.removeAttribute("value");return}b.hasOwnProperty("value")?cb(a,b.type,c):b.hasOwnProperty("defaultValue")&&cb(a,b.type,Sa(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked);} +function db(a,b,c){if(b.hasOwnProperty("value")||b.hasOwnProperty("defaultValue")){var d=b.type;if(!("submit"!==d&&"reset"!==d||void 0!==b.value&&null!==b.value))return;b=""+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b;}c=a.name;""!==c&&(a.name="");a.defaultChecked=!!a._wrapperState.initialChecked;""!==c&&(a.name=c);} +function cb(a,b,c){if("number"!==b||Xa(a.ownerDocument)!==a)null==c?a.defaultValue=""+a._wrapperState.initialValue:a.defaultValue!==""+c&&(a.defaultValue=""+c);}var eb=Array.isArray; +function fb(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e"+b.valueOf().toString()+"";for(b=mb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild);}}); +function ob(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b;} +var pb={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0, +zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},qb=["Webkit","ms","Moz","O"];Object.keys(pb).forEach(function(a){qb.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);pb[b]=pb[a];});});function rb(a,b,c){return null==b||"boolean"===typeof b||""===b?"":c||"number"!==typeof b||0===b||pb.hasOwnProperty(a)&&pb[a]?(""+b).trim():b+"px"} +function sb(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf("--"),e=rb(c,b[c],d);"float"===c&&(c="cssFloat");d?a.setProperty(c,e):a[c]=e;}}var tb=A$1({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0}); +function ub(a,b){if(b){if(tb[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(p(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(p(60));if("object"!==typeof b.dangerouslySetInnerHTML||!("__html"in b.dangerouslySetInnerHTML))throw Error(p(61));}if(null!=b.style&&"object"!==typeof b.style)throw Error(p(62));}} +function vb(a,b){if(-1===a.indexOf("-"))return "string"===typeof b.is;switch(a){case "annotation-xml":case "color-profile":case "font-face":case "font-face-src":case "font-face-uri":case "font-face-format":case "font-face-name":case "missing-glyph":return !1;default:return !0}}var wb=null;function xb(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}var yb=null,zb=null,Ab=null; +function Bb(a){if(a=Cb(a)){if("function"!==typeof yb)throw Error(p(280));var b=a.stateNode;b&&(b=Db(b),yb(a.stateNode,a.type,b));}}function Eb(a){zb?Ab?Ab.push(a):Ab=[a]:zb=a;}function Fb(){if(zb){var a=zb,b=Ab;Ab=zb=null;Bb(a);if(b)for(a=0;a>>=0;return 0===a?32:31-(pc(a)/qc|0)|0}var rc=64,sc=4194304; +function tc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824; +default:return a}}function uc(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=tc(h):(f&=g,0!==f&&(d=tc(f)));}else g=c&~e,0!==g?d=tc(g):0!==f&&(d=tc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0c;c++)b.push(a);return b} +function Ac(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-oc(b);a[b]=c;}function Bc(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0=be$1),ee=String.fromCharCode(32),fe$1=!1; +function ge$1(a,b){switch(a){case "keyup":return -1!==$d.indexOf(b.keyCode);case "keydown":return 229!==b.keyCode;case "keypress":case "mousedown":case "focusout":return !0;default:return !1}}function he$1(a){a=a.detail;return "object"===typeof a&&"data"in a?a.data:null}var ie=!1;function je$1(a,b){switch(a){case "compositionend":return he$1(b);case "keypress":if(32!==b.which)return null;fe$1=!0;return ee;case "textInput":return a=b.data,a===ee&&fe$1?null:a;default:return null}} +function ke$1(a,b){if(ie)return "compositionend"===a||!ae&&ge$1(a,b)?(a=nd(),md=ld=kd=null,ie=!1,a):null;switch(a){case "paste":return null;case "keypress":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1=b)return {node:c,offset:b-a};a=d;}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode;}c=void 0;}c=Je(c);}}function Le$1(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Le$1(a,b.parentNode):"contains"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1} +function Me$1(){for(var a=window,b=Xa();b instanceof a.HTMLIFrameElement;){try{var c="string"===typeof b.contentWindow.location.href;}catch(d){c=!1;}if(c)a=b.contentWindow;else break;b=Xa(a.document);}return b}function Ne$1(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&("input"===b&&("text"===a.type||"search"===a.type||"tel"===a.type||"url"===a.type||"password"===a.type)||"textarea"===b||"true"===a.contentEditable)} +function Oe$1(a){var b=Me$1(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&Le$1(c.ownerDocument.documentElement,c)){if(null!==d&&Ne$1(c))if(b=d.start,a=d.end,void 0===a&&(a=b),"selectionStart"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=Ke$1(c,f);var g=Ke$1(c, +d);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset),a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),a.addRange(b)));}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});"function"===typeof c.focus&&c.focus();for(c=0;c=document.documentMode,Qe$1=null,Re$1=null,Se$1=null,Te$1=!1; +function Ue$1(a,b,c){var d=c.window===c?c.document:9===c.nodeType?c:c.ownerDocument;Te$1||null==Qe$1||Qe$1!==Xa(d)||(d=Qe$1,"selectionStart"in d&&Ne$1(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Se$1&&Ie$1(Se$1,d)||(Se$1=d,d=oe(Re$1,"onSelect"),0Tf||(a.current=Sf[Tf],Sf[Tf]=null,Tf--);}function G(a,b){Tf++;Sf[Tf]=a.current;a.current=b;}var Vf={},H=Uf(Vf),Wf=Uf(!1),Xf=Vf;function Yf(a,b){var c=a.type.contextTypes;if(!c)return Vf;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e} +function Zf(a){a=a.childContextTypes;return null!==a&&void 0!==a}function $f(){E$1(Wf);E$1(H);}function ag(a,b,c){if(H.current!==Vf)throw Error(p(168));G(H,b);G(Wf,c);}function bg(a,b,c){var d=a.stateNode;b=b.childContextTypes;if("function"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(p(108,Ra(a)||"Unknown",e));return A$1({},c,d)} +function cg(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Vf;Xf=H.current;G(H,a);G(Wf,Wf.current);return !0}function dg(a,b,c){var d=a.stateNode;if(!d)throw Error(p(169));c?(a=bg(a,b,Xf),d.__reactInternalMemoizedMergedChildContext=a,E$1(Wf),E$1(H),G(H,a)):E$1(Wf);G(Wf,c);}var eg=null,fg=!1,gg=!1;function hg(a){null===eg?eg=[a]:eg.push(a);}function ig(a){fg=!0;hg(a);} +function jg(){if(!gg&&null!==eg){gg=!0;var a=0,b=C$1;try{var c=eg;for(C$1=1;a>=g;e-=g;rg=1<<32-oc(b)+e|c<w?(x=u,u=null):x=u.sibling;var n=r(e,u,h[w],k);if(null===n){null===u&&(u=x);break}a&&u&&null===n.alternate&&b(e,u);g=f(n,g,w);null===m?l=n:m.sibling=n;m=n;u=x;}if(w===h.length)return c(e,u),I&&tg(e,w),l;if(null===u){for(;ww?(x=m,m=null):x=m.sibling;var t=r(e,m,n.value,k);if(null===t){null===m&&(m=x);break}a&&m&&null===t.alternate&&b(e,m);g=f(t,g,w);null===u?l=t:u.sibling=t;u=t;m=x;}if(n.done)return c(e, +m),I&&tg(e,w),l;if(null===m){for(;!n.done;w++,n=h.next())n=q(e,n.value,k),null!==n&&(g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);I&&tg(e,w);return l}for(m=d(e,m);!n.done;w++,n=h.next())n=y(m,e,w,n.value,k),null!==n&&(a&&null!==n.alternate&&m.delete(null===n.key?w:n.key),g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);a&&m.forEach(function(a){return b(e,a)});I&&tg(e,w);return l}function J(a,d,f,h){"object"===typeof f&&null!==f&&f.type===ya&&null===f.key&&(f=f.props.children);if("object"===typeof f&&null!==f){switch(f.$$typeof){case va:a:{for(var k= +f.key,l=d;null!==l;){if(l.key===k){k=f.type;if(k===ya){if(7===l.tag){c(a,l.sibling);d=e(l,f.props.children);d.return=a;a=d;break a}}else if(l.elementType===k||"object"===typeof k&&null!==k&&k.$$typeof===Ha&&uh(k)===l.type){c(a,l.sibling);d=e(l,f.props);d.ref=sh(a,l,f);d.return=a;a=d;break a}c(a,l);break}else b(a,l);l=l.sibling;}f.type===ya?(d=Ah(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=yh(f.type,f.key,f.props,null,a.mode,h),h.ref=sh(a,d,f),h.return=a,a=h);}return g(a);case wa:a:{for(l=f.key;null!== +d;){if(d.key===l)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else {c(a,d);break}else b(a,d);d=d.sibling;}d=zh(f,a.mode,h);d.return=a;a=d;}return g(a);case Ha:return l=f._init,J(a,d,l(f._payload),h)}if(eb(f))return n(a,d,f,h);if(Ka(f))return t(a,d,f,h);th(a,f);}return "string"===typeof f&&""!==f||"number"===typeof f?(f=""+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d): +(c(a,d),d=xh(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d)}return J}var Bh=vh(!0),Ch=vh(!1),Dh={},Eh=Uf(Dh),Fh=Uf(Dh),Gh=Uf(Dh);function Hh(a){if(a===Dh)throw Error(p(174));return a}function Ih(a,b){G(Gh,b);G(Fh,a);G(Eh,Dh);a=b.nodeType;switch(a){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:lb(null,"");break;default:a=8===a?b.parentNode:b,b=a.namespaceURI||null,a=a.tagName,b=lb(b,a);}E$1(Eh);G(Eh,b);}function Jh(){E$1(Eh);E$1(Fh);E$1(Gh);} +function Kh(a){Hh(Gh.current);var b=Hh(Eh.current);var c=lb(b,a.type);b!==c&&(G(Fh,a),G(Eh,c));}function Lh(a){Fh.current===a&&(E$1(Eh),E$1(Fh));}var M=Uf(0); +function Mh(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||"$?"===c.data||"$!"===c.data))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.flags&128))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return;}b.sibling.return=b.return;b=b.sibling;}return null}var Nh=[]; +function Oh(){for(var a=0;ac?c:4;a(!0);var d=Qh.transition;Qh.transition={};try{a(!1),b();}finally{C$1=c,Qh.transition=d;}}function Fi(){return di().memoizedState} +function Gi(a,b,c){var d=lh(a);c={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(b,c);else if(c=Yg(a,b,c,d),null!==c){var e=L();mh(c,a,d,e);Ji(c,b,d);}} +function ri(a,b,c){var d=lh(a),e={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(b,e);else {var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(He$1(h,g)){var k=b.interleaved;null===k?(e.next=e,Xg(b)):(e.next=k.next,k.next=e);b.interleaved=e;return}}catch(l){}finally{}c=Yg(a,b,e,d);null!==c&&(e=L(),mh(c,a,d,e),Ji(c,b,d));}} +function Hi(a){var b=a.alternate;return a===N||null!==b&&b===N}function Ii(a,b){Th=Sh=!0;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b;}function Ji(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c);}} +var ai={readContext:Vg,useCallback:Q,useContext:Q,useEffect:Q,useImperativeHandle:Q,useInsertionEffect:Q,useLayoutEffect:Q,useMemo:Q,useReducer:Q,useRef:Q,useState:Q,useDebugValue:Q,useDeferredValue:Q,useTransition:Q,useMutableSource:Q,useSyncExternalStore:Q,useId:Q,unstable_isNewReconciler:!1},Yh={readContext:Vg,useCallback:function(a,b){ci().memoizedState=[a,void 0===b?null:b];return a},useContext:Vg,useEffect:vi,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ti(4194308, +4,yi.bind(null,b,a),c)},useLayoutEffect:function(a,b){return ti(4194308,4,a,b)},useInsertionEffect:function(a,b){return ti(4,2,a,b)},useMemo:function(a,b){var c=ci();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=ci();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=Gi.bind(null,N,a);return [d.memoizedState,a]},useRef:function(a){var b= +ci();a={current:a};return b.memoizedState=a},useState:qi,useDebugValue:Ai,useDeferredValue:function(a){return ci().memoizedState=a},useTransition:function(){var a=qi(!1),b=a[0];a=Ei.bind(null,a[1]);ci().memoizedState=a;return [b,a]},useMutableSource:function(){},useSyncExternalStore:function(a,b,c){var d=N,e=ci();if(I){if(void 0===c)throw Error(p(407));c=c();}else {c=b();if(null===R)throw Error(p(349));0!==(Rh&30)||ni(d,b,c);}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;vi(ki.bind(null,d, +f,a),[a]);d.flags|=2048;li(9,mi.bind(null,d,f,c,b),void 0,null);return c},useId:function(){var a=ci(),b=R.identifierPrefix;if(I){var c=sg;var d=rg;c=(d&~(1<<32-oc(d)-1)).toString(32)+c;b=":"+b+"R"+c;c=Uh++;0\x3c/script>",a=a.removeChild(a.firstChild)): +"string"===typeof d.is?a=g.createElement(c,{is:d.is}):(a=g.createElement(c),"select"===c&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,c);a[Of]=b;a[Pf]=d;Aj(a,b,!1,!1);b.stateNode=a;a:{g=vb(c,d);switch(c){case "dialog":D("cancel",a);D("close",a);e=d;break;case "iframe":case "object":case "embed":D("load",a);e=d;break;case "video":case "audio":for(e=0;eHj&&(b.flags|=128,d=!0,Ej(f,!1),b.lanes=4194304);}else {if(!d)if(a=Mh(g),null!==a){if(b.flags|=128,d=!0,c=a.updateQueue,null!==c&&(b.updateQueue=c,b.flags|=4),Ej(f,!0),null===f.tail&&"hidden"===f.tailMode&&!g.alternate&&!I)return S(b),null}else 2*B()-f.renderingStartTime>Hj&&1073741824!==c&&(b.flags|=128,d=!0,Ej(f,!1),b.lanes=4194304);f.isBackwards?(g.sibling=b.child,b.child=g):(c=f.last,null!==c?c.sibling=g:b.child=g,f.last=g);}if(null!==f.tail)return b=f.tail,f.rendering= +b,f.tail=b.sibling,f.renderingStartTime=B(),b.sibling=null,c=M.current,G(M,d?c&1|2:c&1),b;S(b);return null;case 22:case 23:return Ij(),d=null!==b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(gj&1073741824)&&(S(b),b.subtreeFlags&6&&(b.flags|=8192)):S(b),null;case 24:return null;case 25:return null}throw Error(p(156,b.tag));} +function Jj(a,b){wg(b);switch(b.tag){case 1:return Zf(b.type)&&$f(),a=b.flags,a&65536?(b.flags=a&-65537|128,b):null;case 3:return Jh(),E$1(Wf),E$1(H),Oh(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return Lh(b),null;case 13:E$1(M);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(p(340));Ig();}a=b.flags;return a&65536?(b.flags=a&-65537|128,b):null;case 19:return E$1(M),null;case 4:return Jh(),null;case 10:return Rg(b.type._context),null;case 22:case 23:return Ij(), +null;case 24:return null;default:return null}}var Kj=!1,U=!1,Lj="function"===typeof WeakSet?WeakSet:Set,V=null;function Mj(a,b){var c=a.ref;if(null!==c)if("function"===typeof c)try{c(null);}catch(d){W$1(a,b,d);}else c.current=null;}function Nj(a,b,c){try{c();}catch(d){W$1(a,b,d);}}var Oj=!1; +function Pj(a,b){Cf=dd;a=Me$1();if(Ne$1(a)){if("selectionStart"in a)var c={start:a.selectionStart,end:a.selectionEnd};else a:{c=(c=a.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&0!==d.rangeCount){c=d.anchorNode;var e=d.anchorOffset,f=d.focusNode;d=d.focusOffset;try{c.nodeType,f.nodeType;}catch(F){c=null;break a}var g=0,h=-1,k=-1,l=0,m=0,q=a,r=null;b:for(;;){for(var y;;){q!==c||0!==e&&3!==q.nodeType||(h=g+e);q!==f||0!==d&&3!==q.nodeType||(k=g+d);3===q.nodeType&&(g+= +q.nodeValue.length);if(null===(y=q.firstChild))break;r=q;q=y;}for(;;){if(q===a)break b;r===c&&++l===e&&(h=g);r===f&&++m===d&&(k=g);if(null!==(y=q.nextSibling))break;q=r;r=q.parentNode;}q=y;}c=-1===h||-1===k?null:{start:h,end:k};}else c=null;}c=c||{start:0,end:0};}else c=null;Df={focusedElem:a,selectionRange:c};dd=!1;for(V=b;null!==V;)if(b=V,a=b.child,0!==(b.subtreeFlags&1028)&&null!==a)a.return=b,V=a;else for(;null!==V;){b=V;try{var n=b.alternate;if(0!==(b.flags&1024))switch(b.tag){case 0:case 11:case 15:break; +case 1:if(null!==n){var t=n.memoizedProps,J=n.memoizedState,x=b.stateNode,w=x.getSnapshotBeforeUpdate(b.elementType===b.type?t:Lg(b.type,t),J);x.__reactInternalSnapshotBeforeUpdate=w;}break;case 3:var u=b.stateNode.containerInfo;1===u.nodeType?u.textContent="":9===u.nodeType&&u.documentElement&&u.removeChild(u.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(p(163));}}catch(F){W$1(b,b.return,F);}a=b.sibling;if(null!==a){a.return=b.return;V=a;break}V=b.return;}n=Oj;Oj=!1;return n} +function Qj(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&Nj(b,c,f);}e=e.next;}while(e!==d)}}function Rj(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d();}c=c.next;}while(c!==b)}}function Sj(a){var b=a.ref;if(null!==b){var c=a.stateNode;switch(a.tag){case 5:a=c;break;default:a=c;}"function"===typeof b?b(a):b.current=a;}} +function Tj(a){var b=a.alternate;null!==b&&(a.alternate=null,Tj(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&(delete b[Of],delete b[Pf],delete b[of],delete b[Qf],delete b[Rf]));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null;}function Uj(a){return 5===a.tag||3===a.tag||4===a.tag} +function Vj(a){a:for(;;){for(;null===a.sibling;){if(null===a.return||Uj(a.return))return null;a=a.return;}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child;}if(!(a.flags&2))return a.stateNode}} +function Wj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?8===c.nodeType?c.parentNode.insertBefore(a,b):c.insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,null!==c&&void 0!==c||null!==b.onclick||(b.onclick=Bf));else if(4!==d&&(a=a.child,null!==a))for(Wj(a,b,c),a=a.sibling;null!==a;)Wj(a,b,c),a=a.sibling;} +function Xj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(Xj(a,b,c),a=a.sibling;null!==a;)Xj(a,b,c),a=a.sibling;}var X=null,Yj=!1;function Zj(a,b,c){for(c=c.child;null!==c;)ak(a,b,c),c=c.sibling;} +function ak(a,b,c){if(lc&&"function"===typeof lc.onCommitFiberUnmount)try{lc.onCommitFiberUnmount(kc,c);}catch(h){}switch(c.tag){case 5:U||Mj(c,b);case 6:var d=X,e=Yj;X=null;Zj(a,b,c);X=d;Yj=e;null!==X&&(Yj?(a=X,c=c.stateNode,8===a.nodeType?a.parentNode.removeChild(c):a.removeChild(c)):X.removeChild(c.stateNode));break;case 18:null!==X&&(Yj?(a=X,c=c.stateNode,8===a.nodeType?Kf(a.parentNode,c):1===a.nodeType&&Kf(a,c),bd(a)):Kf(X,c.stateNode));break;case 4:d=X;e=Yj;X=c.stateNode.containerInfo;Yj=!0; +Zj(a,b,c);X=d;Yj=e;break;case 0:case 11:case 14:case 15:if(!U&&(d=c.updateQueue,null!==d&&(d=d.lastEffect,null!==d))){e=d=d.next;do{var f=e,g=f.destroy;f=f.tag;void 0!==g&&(0!==(f&2)?Nj(c,b,g):0!==(f&4)&&Nj(c,b,g));e=e.next;}while(e!==d)}Zj(a,b,c);break;case 1:if(!U&&(Mj(c,b),d=c.stateNode,"function"===typeof d.componentWillUnmount))try{d.props=c.memoizedProps,d.state=c.memoizedState,d.componentWillUnmount();}catch(h){W$1(c,b,h);}Zj(a,b,c);break;case 21:Zj(a,b,c);break;case 22:c.mode&1?(U=(d=U)||null!== +c.memoizedState,Zj(a,b,c),U=d):Zj(a,b,c);break;default:Zj(a,b,c);}}function bk(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Lj);b.forEach(function(b){var d=ck.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d));});}} +function dk(a,b){var c=b.deletions;if(null!==c)for(var d=0;de&&(e=g);d&=~f;}d=e;d=B()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*mk(d/1960))-d;if(10a?16:a;if(null===xk)var d=!1;else {a=xk;xk=null;yk=0;if(0!==(K$1&6))throw Error(p(331));var e=K$1;K$1|=4;for(V=a.current;null!==V;){var f=V,g=f.child;if(0!==(V.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;kB()-gk?Lk(a,0):sk|=c);Ek(a,b);}function Zk(a,b){0===b&&(0===(a.mode&1)?b=1:(b=sc,sc<<=1,0===(sc&130023424)&&(sc=4194304)));var c=L();a=Zg(a,b);null!==a&&(Ac(a,b,c),Ek(a,c));}function vj(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);Zk(a,c);} +function ck(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);break;case 19:d=a.stateNode;break;default:throw Error(p(314));}null!==d&&d.delete(b);Zk(a,c);}var Wk; +Wk=function(a,b,c){if(null!==a)if(a.memoizedProps!==b.pendingProps||Wf.current)Ug=!0;else {if(0===(a.lanes&c)&&0===(b.flags&128))return Ug=!1,zj(a,b,c);Ug=0!==(a.flags&131072)?!0:!1;}else Ug=!1,I&&0!==(b.flags&1048576)&&ug(b,ng,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;jj(a,b);a=b.pendingProps;var e=Yf(b,H.current);Tg(b,c);e=Xh(null,b,d,a,e,c);var f=bi();b.flags|=1;"object"===typeof e&&null!==e&&"function"===typeof e.render&&void 0===e.$$typeof?(b.tag=1,b.memoizedState=null,b.updateQueue= +null,Zf(d)?(f=!0,cg(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,ah(b),e.updater=nh,b.stateNode=e,e._reactInternals=b,rh(b,d,a,c),b=kj(null,b,d,!0,f,c)):(b.tag=0,I&&f&&vg(b),Yi(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{jj(a,b);a=b.pendingProps;e=d._init;d=e(d._payload);b.type=d;e=b.tag=$k(d);a=Lg(d,a);switch(e){case 0:b=dj(null,b,d,a,c);break a;case 1:b=ij(null,b,d,a,c);break a;case 11:b=Zi(null,b,d,a,c);break a;case 14:b=aj(null,b,d,Lg(d.type,a),c);break a}throw Error(p(306, +d,""));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),dj(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),ij(a,b,d,e,c);case 3:a:{lj(b);if(null===a)throw Error(p(387));d=b.pendingProps;f=b.memoizedState;e=f.element;bh(a,b);gh(b,d,null,c);var g=b.memoizedState;d=g.element;if(f.isDehydrated)if(f={element:d,isDehydrated:!1,cache:g.cache,pendingSuspenseBoundaries:g.pendingSuspenseBoundaries,transitions:g.transitions},b.updateQueue.baseState= +f,b.memoizedState=f,b.flags&256){e=Ki(Error(p(423)),b);b=mj(a,b,d,c,e);break a}else if(d!==e){e=Ki(Error(p(424)),b);b=mj(a,b,d,c,e);break a}else for(yg=Lf(b.stateNode.containerInfo.firstChild),xg=b,I=!0,zg=null,c=Ch(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else {Ig();if(d===e){b=$i(a,b,c);break a}Yi(a,b,d,c);}b=b.child;}return b;case 5:return Kh(b),null===a&&Eg(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,Ef(d,e)?g=null:null!==f&&Ef(d,f)&&(b.flags|=32), +hj(a,b),Yi(a,b,g,c),b.child;case 6:return null===a&&Eg(b),null;case 13:return pj(a,b,c);case 4:return Ih(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=Bh(b,null,d,c):Yi(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),Zi(a,b,d,e,c);case 7:return Yi(a,b,b.pendingProps,c),b.child;case 8:return Yi(a,b,b.pendingProps.children,c),b.child;case 12:return Yi(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;f=b.memoizedProps; +g=e.value;G(Mg,d._currentValue);d._currentValue=g;if(null!==f)if(He$1(f.value,g)){if(f.children===e.children&&!Wf.current){b=$i(a,b,c);break a}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=ch(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var m=l.pending;null===m?k.next=k:(k.next=m.next,m.next=k);l.pending=k;}}f.lanes|=c;k=f.alternate;null!==k&&(k.lanes|=c);Sg(f.return, +c,b);h.lanes|=c;break}k=k.next;}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===f.tag){g=f.return;if(null===g)throw Error(p(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);Sg(g,c,b);g=f.sibling;}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break}f=g.sibling;if(null!==f){f.return=g.return;g=f;break}g=g.return;}f=g;}Yi(a,b,e.children,c);b=b.child;}return b;case 9:return e=b.type,d=b.pendingProps.children,Tg(b,c),e=Vg(e),d=d(e),b.flags|=1,Yi(a,b,d,c), +b.child;case 14:return d=b.type,e=Lg(d,b.pendingProps),e=Lg(d.type,e),aj(a,b,d,e,c);case 15:return cj(a,b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),jj(a,b),b.tag=1,Zf(d)?(a=!0,cg(b)):a=!1,Tg(b,c),ph(b,d,e),rh(b,d,e,c),kj(null,b,d,!0,a,c);case 19:return yj(a,b,c);case 22:return ej(a,b,c)}throw Error(p(156,b.tag));};function Gk(a,b){return ac(a,b)} +function al(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null;}function Bg(a,b,c,d){return new al(a,b,c,d)}function bj(a){a=a.prototype;return !(!a||!a.isReactComponent)} +function $k(a){if("function"===typeof a)return bj(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===Da)return 11;if(a===Ga)return 14}return 2} +function wh(a,b){var c=a.alternate;null===c?(c=Bg(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.subtreeFlags=0,c.deletions=null);c.flags=a.flags&14680064;c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{lanes:b.lanes,firstContext:b.firstContext}; +c.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c} +function yh(a,b,c,d,e,f){var g=2;d=a;if("function"===typeof a)bj(a)&&(g=1);else if("string"===typeof a)g=5;else a:switch(a){case ya:return Ah(c.children,e,f,b);case za:g=8;e|=8;break;case Aa:return a=Bg(12,c,b,e|2),a.elementType=Aa,a.lanes=f,a;case Ea:return a=Bg(13,c,b,e),a.elementType=Ea,a.lanes=f,a;case Fa:return a=Bg(19,c,b,e),a.elementType=Fa,a.lanes=f,a;case Ia:return qj(c,e,f,b);default:if("object"===typeof a&&null!==a)switch(a.$$typeof){case Ba:g=10;break a;case Ca:g=9;break a;case Da:g=11; +break a;case Ga:g=14;break a;case Ha:g=16;d=null;break a}throw Error(p(130,null==a?a:typeof a,""));}b=Bg(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function Ah(a,b,c,d){a=Bg(7,a,d,b);a.lanes=c;return a}function qj(a,b,c,d){a=Bg(22,a,d,b);a.elementType=Ia;a.lanes=c;a.stateNode={isHidden:!1};return a}function xh(a,b,c){a=Bg(6,a,null,b);a.lanes=c;return a} +function zh(a,b,c){b=Bg(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b} +function bl(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=-1;this.callbackNode=this.pendingContext=this.context=null;this.callbackPriority=0;this.eventTimes=zc(0);this.expirationTimes=zc(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=zc(0);this.identifierPrefix=d;this.onRecoverableError=e;this.mutableSourceEagerHydrationData= +null;}function cl(a,b,c,d,e,f,g,h,k){a=new bl(a,b,c,h,k);1===b?(b=1,!0===f&&(b|=8)):b=0;f=Bg(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null,pendingSuspenseBoundaries:null};ah(f);return a}function dl(a,b,c){var d=3Q.length&&Q.push(a);} + function T(a,b,c,e){var d=typeof a;if("undefined"===d||"boolean"===d)a=null;var g=!1;if(null===a)g=!0;else switch(d){case "string":case "number":g=!0;break;case "object":switch(a.$$typeof){case p:case q:g=!0;}}if(g)return c(e,a,""===b?"."+U(a,0):b),1;g=0;b=""===b?".":b+":";if(Array.isArray(a))for(var k=0;k=G};l=function(){};exports.unstable_forceFrameRate=function(a){0>a||125>>1,e=a[d];if(void 0!==e&&0K(n,c))void 0!==r&&0>K(r,n)?(a[d]=r,a[v]=c,d=v):(a[d]=n,a[m]=c,d=m);else if(void 0!==r&&0>K(r,c))a[d]=r,a[v]=c,d=v;else break a}}return b}return null}function K(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}var N=[],O=[],P=1,Q=null,R=3,S=!1,T=!1,U=!1; + function V(a){for(var b=L(O);null!==b;){if(null===b.callback)M(O);else if(b.startTime<=a)M(O),b.sortIndex=b.expirationTime,J(N,b);else break;b=L(O);}}function W(a){U=!1;V(a);if(!T)if(null!==L(N))T=!0,f(X);else {var b=L(O);null!==b&&g(W,b.startTime-a);}} + function X(a,b){T=!1;U&&(U=!1,h());S=!0;var c=R;try{V(b);for(Q=L(N);null!==Q&&(!(Q.expirationTime>b)||a&&!k());){var d=Q.callback;if(null!==d){Q.callback=null;R=Q.priorityLevel;var e=d(Q.expirationTime<=b);b=exports.unstable_now();"function"===typeof e?Q.callback=e:Q===L(N)&&M(N);V(b);}else M(N);Q=L(N);}if(null!==Q)var m=!0;else {var n=L(O);null!==n&&g(W,n.startTime-b);m=!1;}return m}finally{Q=null,R=c,S=!1;}} + function Y(a){switch(a){case 1:return -1;case 2:return 250;case 5:return 1073741823;case 4:return 1E4;default:return 5E3}}var Z=l;exports.unstable_IdlePriority=5;exports.unstable_ImmediatePriority=1;exports.unstable_LowPriority=4;exports.unstable_NormalPriority=3;exports.unstable_Profiling=null;exports.unstable_UserBlockingPriority=2;exports.unstable_cancelCallback=function(a){a.callback=null;};exports.unstable_continueExecution=function(){T||S||(T=!0,f(X));}; + exports.unstable_getCurrentPriorityLevel=function(){return R};exports.unstable_getFirstCallbackNode=function(){return L(N)};exports.unstable_next=function(a){switch(R){case 1:case 2:case 3:var b=3;break;default:b=R;}var c=R;R=b;try{return a()}finally{R=c;}};exports.unstable_pauseExecution=function(){};exports.unstable_requestPaint=Z;exports.unstable_runWithPriority=function(a,b){switch(a){case 1:case 2:case 3:case 4:case 5:break;default:a=3;}var c=R;R=a;try{return b()}finally{R=c;}}; + exports.unstable_scheduleCallback=function(a,b,c){var d=exports.unstable_now();if("object"===typeof c&&null!==c){var e=c.delay;e="number"===typeof e&&0d?(a.sortIndex=e,J(O,a),null===L(N)&&a===L(O)&&(U?h():U=!0,g(W,e-d))):(a.sortIndex=c,J(N,a),T||S||(T=!0,f(X)));return a}; + exports.unstable_shouldYield=function(){var a=exports.unstable_now();V(a);var b=L(N);return b!==Q&&null!==Q&&null!==b&&null!==b.callback&&b.startTime<=a&&b.expirationTimeb}return !1}function v(a,b,c,d,e,f){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;}var C={}; + "children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){C[a]=new v(a,0,!1,a,null,!1);});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];C[b]=new v(b,1,!1,a[1],null,!1);});["contentEditable","draggable","spellCheck","value"].forEach(function(a){C[a]=new v(a,2,!1,a.toLowerCase(),null,!1);}); + ["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){C[a]=new v(a,2,!1,a,null,!1);});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){C[a]=new v(a,3,!1,a.toLowerCase(),null,!1);}); + ["checked","multiple","muted","selected"].forEach(function(a){C[a]=new v(a,3,!0,a,null,!1);});["capture","download"].forEach(function(a){C[a]=new v(a,4,!1,a,null,!1);});["cols","rows","size","span"].forEach(function(a){C[a]=new v(a,6,!1,a,null,!1);});["rowSpan","start"].forEach(function(a){C[a]=new v(a,5,!1,a.toLowerCase(),null,!1);});var Ua=/[\-:]([a-z])/g;function Va(a){return a[1].toUpperCase()} + "accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=a.replace(Ua, + Va);C[b]=new v(b,1,!1,a,null,!1);});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(Ua,Va);C[b]=new v(b,1,!1,a,"http://www.w3.org/1999/xlink",!1);});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(Ua,Va);C[b]=new v(b,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1);});["tabIndex","crossOrigin"].forEach(function(a){C[a]=new v(a,1,!1,a.toLowerCase(),null,!1);}); + C.xlinkHref=new v("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0);["src","href","action","formAction"].forEach(function(a){C[a]=new v(a,1,!1,a.toLowerCase(),null,!0);});var Wa=aa.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;Wa.hasOwnProperty("ReactCurrentDispatcher")||(Wa.ReactCurrentDispatcher={current:null});Wa.hasOwnProperty("ReactCurrentBatchConfig")||(Wa.ReactCurrentBatchConfig={suspense:null}); + function Xa(a,b,c,d){var e=C.hasOwnProperty(b)?C[b]:null;var f=null!==e?0===e.type:d?!1:!(2=c.length))throw Error(u(93));c=c[0];}b=c;}null==b&&(b="");c=b;}a._wrapperState={initialValue:rb(c)};} + function Kb(a,b){var c=rb(b.value),d=rb(b.defaultValue);null!=c&&(c=""+c,c!==a.value&&(a.value=c),null==b.defaultValue&&a.defaultValue!==c&&(a.defaultValue=c));null!=d&&(a.defaultValue=""+d);}function Lb(a){var b=a.textContent;b===a._wrapperState.initialValue&&""!==b&&null!==b&&(a.value=b);}var Mb={html:"http://www.w3.org/1999/xhtml",mathml:"http://www.w3.org/1998/Math/MathML",svg:"http://www.w3.org/2000/svg"}; + function Nb(a){switch(a){case "svg":return "http://www.w3.org/2000/svg";case "math":return "http://www.w3.org/1998/Math/MathML";default:return "http://www.w3.org/1999/xhtml"}}function Ob(a,b){return null==a||"http://www.w3.org/1999/xhtml"===a?Nb(b):"http://www.w3.org/2000/svg"===a&&"foreignObject"===b?"http://www.w3.org/1999/xhtml":a} + var Pb,Qb=function(a){return "undefined"!==typeof MSApp&&MSApp.execUnsafeLocalFunction?function(b,c,d,e){MSApp.execUnsafeLocalFunction(function(){return a(b,c,d,e)});}:a}(function(a,b){if(a.namespaceURI!==Mb.svg||"innerHTML"in a)a.innerHTML=b;else {Pb=Pb||document.createElement("div");Pb.innerHTML=""+b.valueOf().toString()+"";for(b=Pb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild);}}); + function Rb(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b;}function Sb(a,b){var c={};c[a.toLowerCase()]=b.toLowerCase();c["Webkit"+a]="webkit"+b;c["Moz"+a]="moz"+b;return c}var Tb={animationend:Sb("Animation","AnimationEnd"),animationiteration:Sb("Animation","AnimationIteration"),animationstart:Sb("Animation","AnimationStart"),transitionend:Sb("Transition","TransitionEnd")},Ub={},Vb={}; + ya&&(Vb=document.createElement("div").style,"AnimationEvent"in window||(delete Tb.animationend.animation,delete Tb.animationiteration.animation,delete Tb.animationstart.animation),"TransitionEvent"in window||delete Tb.transitionend.transition);function Wb(a){if(Ub[a])return Ub[a];if(!Tb[a])return a;var b=Tb[a],c;for(c in b)if(b.hasOwnProperty(c)&&c in Vb)return Ub[a]=b[c];return a} + var Xb=Wb("animationend"),Yb=Wb("animationiteration"),Zb=Wb("animationstart"),$b=Wb("transitionend"),ac="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),bc=new ("function"===typeof WeakMap?WeakMap:Map);function cc(a){var b=bc.get(a);void 0===b&&(b=new Map,bc.set(a,b));return b} + function dc(a){var b=a,c=a;if(a.alternate)for(;b.return;)b=b.return;else {a=b;do b=a,0!==(b.effectTag&1026)&&(c=b.return),a=b.return;while(a)}return 3===b.tag?c:null}function ec(a){if(13===a.tag){var b=a.memoizedState;null===b&&(a=a.alternate,null!==a&&(b=a.memoizedState));if(null!==b)return b.dehydrated}return null}function fc(a){if(dc(a)!==a)throw Error(u(188));} + function gc(a){var b=a.alternate;if(!b){b=dc(a);if(null===b)throw Error(u(188));return b!==a?null:a}for(var c=a,d=b;;){var e=c.return;if(null===e)break;var f=e.alternate;if(null===f){d=e.return;if(null!==d){c=d;continue}break}if(e.child===f.child){for(f=e.child;f;){if(f===c)return fc(e),a;if(f===d)return fc(e),b;f=f.sibling;}throw Error(u(188));}if(c.return!==d.return)c=e,d=f;else {for(var g=!1,h=e.child;h;){if(h===c){g=!0;c=e;d=f;break}if(h===d){g=!0;d=e;c=f;break}h=h.sibling;}if(!g){for(h=f.child;h;){if(h=== + c){g=!0;c=f;d=e;break}if(h===d){g=!0;d=f;c=e;break}h=h.sibling;}if(!g)throw Error(u(189));}}if(c.alternate!==d)throw Error(u(190));}if(3!==c.tag)throw Error(u(188));return c.stateNode.current===c?a:b}function hc(a){a=gc(a);if(!a)return null;for(var b=a;;){if(5===b.tag||6===b.tag)return b;if(b.child)b.child.return=b,b=b.child;else {if(b===a)break;for(;!b.sibling;){if(!b.return||b.return===a)return null;b=b.return;}b.sibling.return=b.return;b=b.sibling;}}return null} + function ic(a,b){if(null==b)throw Error(u(30));if(null==a)return b;if(Array.isArray(a)){if(Array.isArray(b))return a.push.apply(a,b),a;a.push(b);return a}return Array.isArray(b)?[a].concat(b):[a,b]}function jc(a,b,c){Array.isArray(a)?a.forEach(b,c):a&&b.call(c,a);}var kc=null; + function lc(a){if(a){var b=a._dispatchListeners,c=a._dispatchInstances;if(Array.isArray(b))for(var d=0;dpc.length&&pc.push(a);} + function rc(a,b,c,d){if(pc.length){var e=pc.pop();e.topLevelType=a;e.eventSystemFlags=d;e.nativeEvent=b;e.targetInst=c;return e}return {topLevelType:a,eventSystemFlags:d,nativeEvent:b,targetInst:c,ancestors:[]}} + function sc(a){var b=a.targetInst,c=b;do{if(!c){a.ancestors.push(c);break}var d=c;if(3===d.tag)d=d.stateNode.containerInfo;else {for(;d.return;)d=d.return;d=3!==d.tag?null:d.stateNode.containerInfo;}if(!d)break;b=c.tag;5!==b&&6!==b||a.ancestors.push(c);c=tc(d);}while(c);for(c=0;c=b)return {node:c,offset:b-a};a=d;}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode;}c=void 0;}c=ud(c);}} + function wd(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?wd(a,b.parentNode):"contains"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1}function xd(){for(var a=window,b=td();b instanceof a.HTMLIFrameElement;){try{var c="string"===typeof b.contentWindow.location.href;}catch(d){c=!1;}if(c)a=b.contentWindow;else break;b=td(a.document);}return b} + function yd(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&("input"===b&&("text"===a.type||"search"===a.type||"tel"===a.type||"url"===a.type||"password"===a.type)||"textarea"===b||"true"===a.contentEditable)}var zd="$",Ad="/$",Bd="$?",Cd="$!",Dd=null,Ed=null;function Fd(a,b){switch(a){case "button":case "input":case "select":case "textarea":return !!b.autoFocus}return !1} + function Gd(a,b){return "textarea"===a||"option"===a||"noscript"===a||"string"===typeof b.children||"number"===typeof b.children||"object"===typeof b.dangerouslySetInnerHTML&&null!==b.dangerouslySetInnerHTML&&null!=b.dangerouslySetInnerHTML.__html}var Hd="function"===typeof setTimeout?setTimeout:void 0,Id="function"===typeof clearTimeout?clearTimeout:void 0;function Jd(a){for(;null!=a;a=a.nextSibling){var b=a.nodeType;if(1===b||3===b)break}return a} + function Kd(a){a=a.previousSibling;for(var b=0;a;){if(8===a.nodeType){var c=a.data;if(c===zd||c===Cd||c===Bd){if(0===b)return a;b--;}else c===Ad&&b++;}a=a.previousSibling;}return null}var Ld=Math.random().toString(36).slice(2),Md="__reactInternalInstance$"+Ld,Nd="__reactEventHandlers$"+Ld,Od="__reactContainere$"+Ld; + function tc(a){var b=a[Md];if(b)return b;for(var c=a.parentNode;c;){if(b=c[Od]||c[Md]){c=b.alternate;if(null!==b.child||null!==c&&null!==c.child)for(a=Kd(a);null!==a;){if(c=a[Md])return c;a=Kd(a);}return b}a=c;c=a.parentNode;}return null}function Nc(a){a=a[Md]||a[Od];return !a||5!==a.tag&&6!==a.tag&&13!==a.tag&&3!==a.tag?null:a}function Pd(a){if(5===a.tag||6===a.tag)return a.stateNode;throw Error(u(33));}function Qd(a){return a[Nd]||null} + function Rd(a){do a=a.return;while(a&&5!==a.tag);return a?a:null} + function Sd(a,b){var c=a.stateNode;if(!c)return null;var d=la(c);if(!d)return null;c=d[b];a:switch(b){case "onClick":case "onClickCapture":case "onDoubleClick":case "onDoubleClickCapture":case "onMouseDown":case "onMouseDownCapture":case "onMouseMove":case "onMouseMoveCapture":case "onMouseUp":case "onMouseUpCapture":case "onMouseEnter":(d=!d.disabled)||(a=a.type,d=!("button"===a||"input"===a||"select"===a||"textarea"===a));a=!d;break a;default:a=!1;}if(a)return null;if(c&&"function"!==typeof c)throw Error(u(231, + b,typeof c));return c}function Td(a,b,c){if(b=Sd(a,c.dispatchConfig.phasedRegistrationNames[b]))c._dispatchListeners=ic(c._dispatchListeners,b),c._dispatchInstances=ic(c._dispatchInstances,a);}function Ud(a){if(a&&a.dispatchConfig.phasedRegistrationNames){for(var b=a._targetInst,c=[];b;)c.push(b),b=Rd(b);for(b=c.length;0this.eventPool.length&&this.eventPool.push(a);}function de(a){a.eventPool=[];a.getPooled=ee;a.release=fe;}var ge=G.extend({data:null}),he=G.extend({data:null}),ie=[9,13,27,32],je=ya&&"CompositionEvent"in window,ke=null;ya&&"documentMode"in document&&(ke=document.documentMode); + var le=ya&&"TextEvent"in window&&!ke,me=ya&&(!je||ke&&8=ke),ne=String.fromCharCode(32),oe={beforeInput:{phasedRegistrationNames:{bubbled:"onBeforeInput",captured:"onBeforeInputCapture"},dependencies:["compositionend","keypress","textInput","paste"]},compositionEnd:{phasedRegistrationNames:{bubbled:"onCompositionEnd",captured:"onCompositionEndCapture"},dependencies:"blur compositionend keydown keypress keyup mousedown".split(" ")},compositionStart:{phasedRegistrationNames:{bubbled:"onCompositionStart", + captured:"onCompositionStartCapture"},dependencies:"blur compositionstart keydown keypress keyup mousedown".split(" ")},compositionUpdate:{phasedRegistrationNames:{bubbled:"onCompositionUpdate",captured:"onCompositionUpdateCapture"},dependencies:"blur compositionupdate keydown keypress keyup mousedown".split(" ")}},pe=!1; + function qe(a,b){switch(a){case "keyup":return -1!==ie.indexOf(b.keyCode);case "keydown":return 229!==b.keyCode;case "keypress":case "mousedown":case "blur":return !0;default:return !1}}function re(a){a=a.detail;return "object"===typeof a&&"data"in a?a.data:null}var se=!1;function te(a,b){switch(a){case "compositionend":return re(b);case "keypress":if(32!==b.which)return null;pe=!0;return ne;case "textInput":return a=b.data,a===ne&&pe?null:a;default:return null}} + function ue(a,b){if(se)return "compositionend"===a||!je&&qe(a,b)?(a=ae(),$d=Zd=Yd=null,se=!1,a):null;switch(a){case "paste":return null;case "keypress":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1=document.documentMode,df={select:{phasedRegistrationNames:{bubbled:"onSelect",captured:"onSelectCapture"},dependencies:"blur contextmenu dragend focus keydown keyup mousedown mouseup selectionchange".split(" ")}},ef=null,ff=null,gf=null,hf=!1; + function jf(a,b){var c=b.window===b?b.document:9===b.nodeType?b:b.ownerDocument;if(hf||null==ef||ef!==td(c))return null;c=ef;"selectionStart"in c&&yd(c)?c={start:c.selectionStart,end:c.selectionEnd}:(c=(c.ownerDocument&&c.ownerDocument.defaultView||window).getSelection(),c={anchorNode:c.anchorNode,anchorOffset:c.anchorOffset,focusNode:c.focusNode,focusOffset:c.focusOffset});return gf&&bf(gf,c)?null:(gf=c,a=G.getPooled(df.select,ff,a,b),a.type="select",a.target=ef,Xd(a),a)} + var kf={eventTypes:df,extractEvents:function(a,b,c,d,e,f){e=f||(d.window===d?d.document:9===d.nodeType?d:d.ownerDocument);if(!(f=!e)){a:{e=cc(e);f=wa.onSelect;for(var g=0;gzf||(a.current=yf[zf],yf[zf]=null,zf--);} + function I(a,b){zf++;yf[zf]=a.current;a.current=b;}var Af={},J={current:Af},K={current:!1},Bf=Af;function Cf(a,b){var c=a.type.contextTypes;if(!c)return Af;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}function L(a){a=a.childContextTypes;return null!==a&&void 0!==a} + function Df(){H(K);H(J);}function Ef(a,b,c){if(J.current!==Af)throw Error(u(168));I(J,b);I(K,c);}function Ff(a,b,c){var d=a.stateNode;a=b.childContextTypes;if("function"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in a))throw Error(u(108,pb(b)||"Unknown",e));return n({},c,{},d)}function Gf(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Af;Bf=J.current;I(J,a);I(K,K.current);return !0} + function Hf(a,b,c){var d=a.stateNode;if(!d)throw Error(u(169));c?(a=Ff(a,b,Bf),d.__reactInternalMemoizedMergedChildContext=a,H(K),H(J),I(J,a)):H(K);I(K,c);} + var If=r.unstable_runWithPriority,Jf=r.unstable_scheduleCallback,Kf=r.unstable_cancelCallback,Lf=r.unstable_requestPaint,Mf=r.unstable_now,Nf=r.unstable_getCurrentPriorityLevel,Of=r.unstable_ImmediatePriority,Pf=r.unstable_UserBlockingPriority,Qf=r.unstable_NormalPriority,Rf=r.unstable_LowPriority,Sf=r.unstable_IdlePriority,Tf={},Uf=r.unstable_shouldYield,Vf=void 0!==Lf?Lf:function(){},Wf=null,Xf=null,Yf=!1,Zf=Mf(),$f=1E4>Zf?Mf:function(){return Mf()-Zf}; + function ag(){switch(Nf()){case Of:return 99;case Pf:return 98;case Qf:return 97;case Rf:return 96;case Sf:return 95;default:throw Error(u(332));}}function bg(a){switch(a){case 99:return Of;case 98:return Pf;case 97:return Qf;case 96:return Rf;case 95:return Sf;default:throw Error(u(332));}}function cg(a,b){a=bg(a);return If(a,b)}function dg(a,b,c){a=bg(a);return Jf(a,b,c)}function eg(a){null===Wf?(Wf=[a],Xf=Jf(Of,fg)):Wf.push(a);return Tf}function gg(){if(null!==Xf){var a=Xf;Xf=null;Kf(a);}fg();} + function fg(){if(!Yf&&null!==Wf){Yf=!0;var a=0;try{var b=Wf;cg(99,function(){for(;a=b&&(rg=!0),a.firstContext=null);} + function sg(a,b){if(mg!==a&&!1!==b&&0!==b){if("number"!==typeof b||1073741823===b)mg=a,b=1073741823;b={context:a,observedBits:b,next:null};if(null===lg){if(null===kg)throw Error(u(308));lg=b;kg.dependencies={expirationTime:0,firstContext:b,responders:null};}else lg=lg.next=b;}return a._currentValue}var tg=!1;function ug(a){a.updateQueue={baseState:a.memoizedState,baseQueue:null,shared:{pending:null},effects:null};} + function vg(a,b){a=a.updateQueue;b.updateQueue===a&&(b.updateQueue={baseState:a.baseState,baseQueue:a.baseQueue,shared:a.shared,effects:a.effects});}function wg(a,b){a={expirationTime:a,suspenseConfig:b,tag:0,payload:null,callback:null,next:null};return a.next=a}function xg(a,b){a=a.updateQueue;if(null!==a){a=a.shared;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b;}} + function yg(a,b){var c=a.alternate;null!==c&&vg(c,a);a=a.updateQueue;c=a.baseQueue;null===c?(a.baseQueue=b.next=b,b.next=b):(b.next=c.next,c.next=b);} + function zg(a,b,c,d){var e=a.updateQueue;tg=!1;var f=e.baseQueue,g=e.shared.pending;if(null!==g){if(null!==f){var h=f.next;f.next=g.next;g.next=h;}f=g;e.shared.pending=null;h=a.alternate;null!==h&&(h=h.updateQueue,null!==h&&(h.baseQueue=g));}if(null!==f){h=f.next;var k=e.baseState,l=0,m=null,p=null,x=null;if(null!==h){var z=h;do{g=z.expirationTime;if(gl&&(l=g);}else {null!==x&&(x=x.next={expirationTime:1073741823,suspenseConfig:z.suspenseConfig,tag:z.tag,payload:z.payload,callback:z.callback,next:null});Ag(g,z.suspenseConfig);a:{var D=a,t=z;g=b;ca=c;switch(t.tag){case 1:D=t.payload;if("function"===typeof D){k=D.call(ca,k,g);break a}k=D;break a;case 3:D.effectTag=D.effectTag&-4097|64;case 0:D=t.payload;g="function"===typeof D?D.call(ca,k,g):D;if(null===g||void 0===g)break a;k=n({},k,g);break a;case 2:tg=!0;}}null!==z.callback&& + (a.effectTag|=32,g=e.effects,null===g?e.effects=[z]:g.push(z));}z=z.next;if(null===z||z===h)if(g=e.shared.pending,null===g)break;else z=f.next=g.next,g.next=h,e.baseQueue=f=g,e.shared.pending=null;}while(1)}null===x?m=k:x.next=p;e.baseState=m;e.baseQueue=x;Bg(l);a.expirationTime=l;a.memoizedState=k;}} + function Cg(a,b,c){a=b.effects;b.effects=null;if(null!==a)for(b=0;by?(A=m,m=null):A=m.sibling;var q=x(e,m,h[y],k);if(null===q){null===m&&(m=A);break}a&& + m&&null===q.alternate&&b(e,m);g=f(q,g,y);null===t?l=q:t.sibling=q;t=q;m=A;}if(y===h.length)return c(e,m),l;if(null===m){for(;yy?(A=t,t=null):A=t.sibling;var D=x(e,t,q.value,l);if(null===D){null===t&&(t=A);break}a&&t&&null===D.alternate&&b(e,t);g=f(D,g,y);null===m?k=D:m.sibling=D;m=D;t=A;}if(q.done)return c(e,t),k;if(null===t){for(;!q.done;y++,q=h.next())q=p(e,q.value,l),null!==q&&(g=f(q,g,y),null===m?k=q:m.sibling=q,m=q);return k}for(t=d(e,t);!q.done;y++,q=h.next())q=z(t,e,y,q.value,l),null!==q&&(a&&null!== + q.alternate&&t.delete(null===q.key?y:q.key),g=f(q,g,y),null===m?k=q:m.sibling=q,m=q);a&&t.forEach(function(a){return b(e,a)});return k}return function(a,d,f,h){var k="object"===typeof f&&null!==f&&f.type===ab&&null===f.key;k&&(f=f.props.children);var l="object"===typeof f&&null!==f;if(l)switch(f.$$typeof){case Za:a:{l=f.key;for(k=d;null!==k;){if(k.key===l){switch(k.tag){case 7:if(f.type===ab){c(a,k.sibling);d=e(k,f.props.children);d.return=a;a=d;break a}break;default:if(k.elementType===f.type){c(a, + k.sibling);d=e(k,f.props);d.ref=Pg(a,k,f);d.return=a;a=d;break a}}c(a,k);break}else b(a,k);k=k.sibling;}f.type===ab?(d=Wg(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=Ug(f.type,f.key,f.props,null,a.mode,h),h.ref=Pg(a,d,f),h.return=a,a=h);}return g(a);case $a:a:{for(k=f.key;null!==d;){if(d.key===k)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else {c(a,d);break}else b(a,d);d= + d.sibling;}d=Vg(f,a.mode,h);d.return=a;a=d;}return g(a)}if("string"===typeof f||"number"===typeof f)return f=""+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):(c(a,d),d=Tg(f,a.mode,h),d.return=a,a=d),g(a);if(Og(f))return ca(a,d,f,h);if(nb(f))return D(a,d,f,h);l&&Qg(a,f);if("undefined"===typeof f&&!k)switch(a.tag){case 1:case 0:throw a=a.type,Error(u(152,a.displayName||a.name||"Component"));}return c(a,d)}}var Xg=Rg(!0),Yg=Rg(!1),Zg={},$g={current:Zg},ah={current:Zg},bh={current:Zg}; + function ch(a){if(a===Zg)throw Error(u(174));return a}function dh(a,b){I(bh,b);I(ah,a);I($g,Zg);a=b.nodeType;switch(a){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:Ob(null,"");break;default:a=8===a?b.parentNode:b,b=a.namespaceURI||null,a=a.tagName,b=Ob(b,a);}H($g);I($g,b);}function eh(){H($g);H(ah);H(bh);}function fh(a){ch(bh.current);var b=ch($g.current);var c=Ob(b,a.type);b!==c&&(I(ah,a),I($g,c));}function gh(a){ah.current===a&&(H($g),H(ah));}var M={current:0}; + function hh(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||c.data===Bd||c.data===Cd))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.effectTag&64))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return;}b.sibling.return=b.return;b=b.sibling;}return null}function ih(a,b){return {responder:a,props:b}} + var jh=Wa.ReactCurrentDispatcher,kh=Wa.ReactCurrentBatchConfig,lh=0,N=null,O=null,P=null,mh=!1;function Q(){throw Error(u(321));}function nh(a,b){if(null===b)return !1;for(var c=0;cf))throw Error(u(301));f+=1;P=O=null;b.updateQueue=null;jh.current=rh;a=c(d,e);}while(b.expirationTime===lh)}jh.current=sh;b=null!==O&&null!==O.next;lh=0;P=O=N=null;mh=!1;if(b)throw Error(u(300));return a} + function th(){var a={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};null===P?N.memoizedState=P=a:P=P.next=a;return P}function uh(){if(null===O){var a=N.alternate;a=null!==a?a.memoizedState:null;}else a=O.next;var b=null===P?N.memoizedState:P.next;if(null!==b)P=b,O=a;else {if(null===a)throw Error(u(310));O=a;a={memoizedState:O.memoizedState,baseState:O.baseState,baseQueue:O.baseQueue,queue:O.queue,next:null};null===P?N.memoizedState=P=a:P=P.next=a;}return P} + function vh(a,b){return "function"===typeof b?b(a):b} + function wh(a){var b=uh(),c=b.queue;if(null===c)throw Error(u(311));c.lastRenderedReducer=a;var d=O,e=d.baseQueue,f=c.pending;if(null!==f){if(null!==e){var g=e.next;e.next=f.next;f.next=g;}d.baseQueue=e=f;c.pending=null;}if(null!==e){e=e.next;d=d.baseState;var h=g=f=null,k=e;do{var l=k.expirationTime;if(lN.expirationTime&& + (N.expirationTime=l,Bg(l));}else null!==h&&(h=h.next={expirationTime:1073741823,suspenseConfig:k.suspenseConfig,action:k.action,eagerReducer:k.eagerReducer,eagerState:k.eagerState,next:null}),Ag(l,k.suspenseConfig),d=k.eagerReducer===a?k.eagerState:a(d,k.action);k=k.next;}while(null!==k&&k!==e);null===h?f=d:h.next=g;$e(d,b.memoizedState)||(rg=!0);b.memoizedState=d;b.baseState=f;b.baseQueue=h;c.lastRenderedState=d;}return [b.memoizedState,c.dispatch]} + function xh(a){var b=uh(),c=b.queue;if(null===c)throw Error(u(311));c.lastRenderedReducer=a;var d=c.dispatch,e=c.pending,f=b.memoizedState;if(null!==e){c.pending=null;var g=e=e.next;do f=a(f,g.action),g=g.next;while(g!==e);$e(f,b.memoizedState)||(rg=!0);b.memoizedState=f;null===b.baseQueue&&(b.baseState=f);c.lastRenderedState=f;}return [f,d]} + function yh(a){var b=th();"function"===typeof a&&(a=a());b.memoizedState=b.baseState=a;a=b.queue={pending:null,dispatch:null,lastRenderedReducer:vh,lastRenderedState:a};a=a.dispatch=zh.bind(null,N,a);return [b.memoizedState,a]}function Ah(a,b,c,d){a={tag:a,create:b,destroy:c,deps:d,next:null};b=N.updateQueue;null===b?(b={lastEffect:null},N.updateQueue=b,b.lastEffect=a.next=a):(c=b.lastEffect,null===c?b.lastEffect=a.next=a:(d=c.next,c.next=a,a.next=d,b.lastEffect=a));return a} + function Bh(){return uh().memoizedState}function Ch(a,b,c,d){var e=th();N.effectTag|=a;e.memoizedState=Ah(1|b,c,void 0,void 0===d?null:d);}function Dh(a,b,c,d){var e=uh();d=void 0===d?null:d;var f=void 0;if(null!==O){var g=O.memoizedState;f=g.destroy;if(null!==d&&nh(d,g.deps)){Ah(b,c,f,d);return}}N.effectTag|=a;e.memoizedState=Ah(1|b,c,f,d);}function Eh(a,b){return Ch(516,4,a,b)}function Fh(a,b){return Dh(516,4,a,b)}function Gh(a,b){return Dh(4,2,a,b)} + function Hh(a,b){if("function"===typeof b)return a=a(),b(a),function(){b(null);};if(null!==b&&void 0!==b)return a=a(),b.current=a,function(){b.current=null;}}function Ih(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return Dh(4,2,Hh.bind(null,b,a),c)}function Jh(){}function Kh(a,b){th().memoizedState=[a,void 0===b?null:b];return a}function Lh(a,b){var c=uh();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&nh(b,d[1]))return d[0];c.memoizedState=[a,b];return a} + function Mh(a,b){var c=uh();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&nh(b,d[1]))return d[0];a=a();c.memoizedState=[a,b];return a}function Nh(a,b,c){var d=ag();cg(98>d?98:d,function(){a(!0);});cg(97\x3c/script>",a=a.removeChild(a.firstChild)):"string"===typeof d.is?a=g.createElement(e,{is:d.is}):(a=g.createElement(e),"select"===e&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,e);a[Md]=b;a[Nd]=d;ni(a,b,!1,!1);b.stateNode=a;g=pd(e,d);switch(e){case "iframe":case "object":case "embed":F("load", + a);h=d;break;case "video":case "audio":for(h=0;hd.tailExpiration&&1b)&&tj.set(a,b)));}} + function xj(a,b){a.expirationTimea?c:a;return 2>=a&&b!==a?0:a} + function Z(a){if(0!==a.lastExpiredTime)a.callbackExpirationTime=1073741823,a.callbackPriority=99,a.callbackNode=eg(yj.bind(null,a));else {var b=zj(a),c=a.callbackNode;if(0===b)null!==c&&(a.callbackNode=null,a.callbackExpirationTime=0,a.callbackPriority=90);else {var d=Gg();1073741823===b?d=99:1===b||2===b?d=95:(d=10*(1073741821-b)-10*(1073741821-d),d=0>=d?99:250>=d?98:5250>=d?97:95);if(null!==c){var e=a.callbackPriority;if(a.callbackExpirationTime===b&&e>=d)return;c!==Tf&&Kf(c);}a.callbackExpirationTime= + b;a.callbackPriority=d;b=1073741823===b?eg(yj.bind(null,a)):dg(d,Bj.bind(null,a),{timeout:10*(1073741821-b)-$f()});a.callbackNode=b;}}} + function Bj(a,b){wj=0;if(b)return b=Gg(),Cj(a,b),Z(a),null;var c=zj(a);if(0!==c){b=a.callbackNode;if((W&(fj|gj))!==V)throw Error(u(327));Dj();a===T&&c===U||Ej(a,c);if(null!==X){var d=W;W|=fj;var e=Fj();do try{Gj();break}catch(h){Hj(a,h);}while(1);ng();W=d;cj.current=e;if(S===hj)throw b=kj,Ej(a,c),xi(a,c),Z(a),b;if(null===X)switch(e=a.finishedWork=a.current.alternate,a.finishedExpirationTime=c,d=S,T=null,d){case ti:case hj:throw Error(u(345));case ij:Cj(a,2=c){a.lastPingedTime=c;Ej(a,c);break}}f=zj(a);if(0!==f&&f!==c)break;if(0!==d&&d!==c){a.lastPingedTime=d;break}a.timeoutHandle=Hd(Jj.bind(null,a),e);break}Jj(a);break;case vi:xi(a,c);d=a.lastSuspendedTime;c===d&&(a.nextKnownPendingLevel=Ij(e));if(oj&&(e=a.lastPingedTime,0===e||e>=c)){a.lastPingedTime=c;Ej(a,c);break}e=zj(a);if(0!==e&&e!==c)break;if(0!==d&&d!==c){a.lastPingedTime= + d;break}1073741823!==mj?d=10*(1073741821-mj)-$f():1073741823===lj?d=0:(d=10*(1073741821-lj)-5E3,e=$f(),c=10*(1073741821-c)-e,d=e-d,0>d&&(d=0),d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*bj(d/1960))-d,c=d?d=0:(e=g.busyDelayMs|0,f=$f()-(10*(1073741821-f)-(g.timeoutMs|0||5E3)),d=f<=e?0:e+d-f);if(10 component higher in the tree to provide a loading indicator or placeholder to display."+qb(g));}S!== + jj&&(S=ij);h=Ai(h,g);p=f;do{switch(p.tag){case 3:k=h;p.effectTag|=4096;p.expirationTime=b;var B=Xi(p,k,b);yg(p,B);break a;case 1:k=h;var w=p.type,ub=p.stateNode;if(0===(p.effectTag&64)&&("function"===typeof w.getDerivedStateFromError||null!==ub&&"function"===typeof ub.componentDidCatch&&(null===aj||!aj.has(ub)))){p.effectTag|=4096;p.expirationTime=b;var vb=$i(p,k,b);yg(p,vb);break a}}p=p.return;}while(null!==p)}X=Pj(X);}catch(Xc){b=Xc;continue}break}while(1)} + function Fj(){var a=cj.current;cj.current=sh;return null===a?sh:a}function Ag(a,b){awi&&(wi=a);}function Kj(){for(;null!==X;)X=Qj(X);}function Gj(){for(;null!==X&&!Uf();)X=Qj(X);}function Qj(a){var b=Rj(a.alternate,a,U);a.memoizedProps=a.pendingProps;null===b&&(b=Pj(a));dj.current=null;return b} + function Pj(a){X=a;do{var b=X.alternate;a=X.return;if(0===(X.effectTag&2048)){b=si(b,X,U);if(1===U||1!==X.childExpirationTime){for(var c=0,d=X.child;null!==d;){var e=d.expirationTime,f=d.childExpirationTime;e>c&&(c=e);f>c&&(c=f);d=d.sibling;}X.childExpirationTime=c;}if(null!==b)return b;null!==a&&0===(a.effectTag&2048)&&(null===a.firstEffect&&(a.firstEffect=X.firstEffect),null!==X.lastEffect&&(null!==a.lastEffect&&(a.lastEffect.nextEffect=X.firstEffect),a.lastEffect=X.lastEffect),1a?b:a}function Jj(a){var b=ag();cg(99,Sj.bind(null,a,b));return null} + function Sj(a,b){do Dj();while(null!==rj);if((W&(fj|gj))!==V)throw Error(u(327));var c=a.finishedWork,d=a.finishedExpirationTime;if(null===c)return null;a.finishedWork=null;a.finishedExpirationTime=0;if(c===a.current)throw Error(u(177));a.callbackNode=null;a.callbackExpirationTime=0;a.callbackPriority=90;a.nextKnownPendingLevel=0;var e=Ij(c);a.firstPendingTime=e;d<=a.lastSuspendedTime?a.firstSuspendedTime=a.lastSuspendedTime=a.nextKnownPendingLevel=0:d<=a.firstSuspendedTime&&(a.firstSuspendedTime= + d-1);d<=a.lastPingedTime&&(a.lastPingedTime=0);d<=a.lastExpiredTime&&(a.lastExpiredTime=0);a===T&&(X=T=null,U=0);1h&&(l=h,h=g,g=l),l=vd(q,g),m=vd(q,h),l&&m&&(1!==w.rangeCount||w.anchorNode!==l.node||w.anchorOffset!==l.offset||w.focusNode!==m.node||w.focusOffset!==m.offset)&&(B=B.createRange(),B.setStart(l.node,l.offset),w.removeAllRanges(),g>h?(w.addRange(B),w.extend(m.node,m.offset)):(B.setEnd(m.node,m.offset),w.addRange(B))))));B=[];for(w=q;w=w.parentNode;)1===w.nodeType&&B.push({element:w,left:w.scrollLeft, + top:w.scrollTop});"function"===typeof q.focus&&q.focus();for(q=0;q=c)return ji(a,b,c);I(M,M.current&1);b=$h(a,b,c);return null!==b?b.sibling:null}I(M,M.current&1);break;case 19:d=b.childExpirationTime>=c;if(0!==(a.effectTag&64)){if(d)return mi(a,b,c);b.effectTag|=64;}e=b.memoizedState;null!==e&&(e.rendering=null,e.tail=null);I(M,M.current);if(!d)return null}return $h(a,b,c)}rg=!1;}}else rg=!1;b.expirationTime=0;switch(b.tag){case 2:d=b.type;null!==a&&(a.alternate=null,b.alternate=null,b.effectTag|=2);a=b.pendingProps;e=Cf(b,J.current);qg(b,c);e=oh(null, + b,d,a,e,c);b.effectTag|=1;if("object"===typeof e&&null!==e&&"function"===typeof e.render&&void 0===e.$$typeof){b.tag=1;b.memoizedState=null;b.updateQueue=null;if(L(d)){var f=!0;Gf(b);}else f=!1;b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null;ug(b);var g=d.getDerivedStateFromProps;"function"===typeof g&&Fg(b,d,g,a);e.updater=Jg;b.stateNode=e;e._reactInternalFiber=b;Ng(b,d,a,c);b=gi(null,b,d,!0,f,c);}else b.tag=0,R(null,b,e,c),b=b.child;return b;case 16:a:{e=b.elementType;null!==a&&(a.alternate= + null,b.alternate=null,b.effectTag|=2);a=b.pendingProps;ob(e);if(1!==e._status)throw e._result;e=e._result;b.type=e;f=b.tag=Xj(e);a=ig(e,a);switch(f){case 0:b=di(null,b,e,a,c);break a;case 1:b=fi(null,b,e,a,c);break a;case 11:b=Zh(null,b,e,a,c);break a;case 14:b=ai(null,b,e,ig(e.type,a),d,c);break a}throw Error(u(306,e,""));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ig(d,e),di(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ig(d,e),fi(a,b,d,e,c); + case 3:hi(b);d=b.updateQueue;if(null===a||null===d)throw Error(u(282));d=b.pendingProps;e=b.memoizedState;e=null!==e?e.element:null;vg(a,b);zg(b,d,null,c);d=b.memoizedState.element;if(d===e)Xh(),b=$h(a,b,c);else {if(e=b.stateNode.hydrate)Ph=Jd(b.stateNode.containerInfo.firstChild),Oh=b,e=Qh=!0;if(e)for(c=Yg(b,null,d,c),b.child=c;c;)c.effectTag=c.effectTag&-3|1024,c=c.sibling;else R(a,b,d,c),Xh();b=b.child;}return b;case 5:return fh(b),null===a&&Uh(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps: + null,g=e.children,Gd(d,e)?g=null:null!==f&&Gd(d,f)&&(b.effectTag|=16),ei(a,b),b.mode&4&&1!==c&&e.hidden?(b.expirationTime=b.childExpirationTime=1,b=null):(R(a,b,g,c),b=b.child),b;case 6:return null===a&&Uh(b),null;case 13:return ji(a,b,c);case 4:return dh(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=Xg(b,null,d,c):R(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ig(d,e),Zh(a,b,d,e,c);case 7:return R(a,b,b.pendingProps,c),b.child;case 8:return R(a, + b,b.pendingProps.children,c),b.child;case 12:return R(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;g=b.memoizedProps;f=e.value;var h=b.type._context;I(jg,h._currentValue);h._currentValue=f;if(null!==g)if(h=g.value,f=$e(h,f)?0:("function"===typeof d._calculateChangedBits?d._calculateChangedBits(h,f):1073741823)|0,0===f){if(g.children===e.children&&!K.current){b=$h(a,b,c);break a}}else for(h=b.child,null!==h&&(h.return=b);null!==h;){var k=h.dependencies;if(null!== + k){g=h.child;for(var l=k.firstContext;null!==l;){if(l.context===d&&0!==(l.observedBits&f)){1===h.tag&&(l=wg(c,null),l.tag=2,xg(h,l));h.expirationTime=b&&a<=b}function xi(a,b){var c=a.firstSuspendedTime,d=a.lastSuspendedTime;cb||0===c)a.lastSuspendedTime=b;b<=a.lastPingedTime&&(a.lastPingedTime=0);b<=a.lastExpiredTime&&(a.lastExpiredTime=0);} + function yi(a,b){b>a.firstPendingTime&&(a.firstPendingTime=b);var c=a.firstSuspendedTime;0!==c&&(b>=c?a.firstSuspendedTime=a.lastSuspendedTime=a.nextKnownPendingLevel=0:b>=a.lastSuspendedTime&&(a.lastSuspendedTime=b+1),b>a.nextKnownPendingLevel&&(a.nextKnownPendingLevel=b));}function Cj(a,b){var c=a.lastExpiredTime;if(0===c||c>b)a.lastExpiredTime=b;} + function bk(a,b,c,d){var e=b.current,f=Gg(),g=Dg.suspense;f=Hg(f,e,g);a:if(c){c=c._reactInternalFiber;b:{if(dc(c)!==c||1!==c.tag)throw Error(u(170));var h=c;do{switch(h.tag){case 3:h=h.stateNode.context;break b;case 1:if(L(h.type)){h=h.stateNode.__reactInternalMemoizedMergedChildContext;break b}}h=h.return;}while(null!==h);throw Error(u(171));}if(1===c.tag){var k=c.type;if(L(k)){c=Ff(c,k,h);break a}}c=h;}else c=Af;null===b.context?b.context=c:b.pendingContext=c;b=wg(f,g);b.payload={element:a};d=void 0=== + d?null:d;null!==d&&(b.callback=d);xg(e,b);Ig(e,f);return f}function ck(a){a=a.current;if(!a.child)return null;switch(a.child.tag){case 5:return a.child.stateNode;default:return a.child.stateNode}}function dk(a,b){a=a.memoizedState;null!==a&&null!==a.dehydrated&&a.retryTime + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */(function(){var o="Expected a function",a="__lodash_placeholder__",s=[["ary",128],["bind",1],["bindKey",2],["curry",8],["curryRight",16],["flip",512],["partial",32],["partialRight",64],["rearg",256]],l="[object Arguments]",u="[object Array]",c="[object Boolean]",f="[object Date]",h="[object Error]",d="[object Function]",p="[object GeneratorFunction]",v="[object Map]",g="[object Number]",m="[object Object]",y="[object RegExp]",b="[object Set]",w="[object String]",x="[object Symbol]",C="[object WeakMap]",_="[object ArrayBuffer]",S="[object DataView]",k="[object Float32Array]",L="[object Float64Array]",M="[object Int8Array]",T="[object Int16Array]",O="[object Int32Array]",A="[object Uint8Array]",N="[object Uint16Array]",D="[object Uint32Array]",W=/\b__p \+= '';/g,E=/\b(__p \+=) '' \+/g,P=/(__e\(.*?\)|\b__t\)) \+\n'';/g,R=/&(?:amp|lt|gt|quot|#39);/g,H=/[&<>"']/g,F=RegExp(R.source),I=RegExp(H.source),z=/<%-([\s\S]+?)%>/g,j=/<%([\s\S]+?)%>/g,B=/<%=([\s\S]+?)%>/g,U=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,V=/^\w*$/,G=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,K=/[\\^$.*+?()[\]{}|]/g,q=RegExp(K.source),$=/^\s+/,X=/\s/,Y=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,Z=/\{\n\/\* \[wrapped with (.+)\] \*/,J=/,? & /,Q=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,tt=/[()=,{}\[\]\/\s]/,et=/\\(\\)?/g,rt=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,nt=/\w*$/,it=/^[-+]0x[0-9a-f]+$/i,ot=/^0b[01]+$/i,at=/^\[object .+?Constructor\]$/,st=/^0o[0-7]+$/i,lt=/^(?:0|[1-9]\d*)$/,ut=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,ct=/($^)/,ft=/['\n\r\u2028\u2029\\]/g,ht="\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff",dt="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",pt="[\\ud800-\\udfff]",vt="["+dt+"]",gt="["+ht+"]",mt="\\d+",yt="[\\u2700-\\u27bf]",bt="[a-z\\xdf-\\xf6\\xf8-\\xff]",wt="[^\\ud800-\\udfff"+dt+mt+"\\u2700-\\u27bfa-z\\xdf-\\xf6\\xf8-\\xffA-Z\\xc0-\\xd6\\xd8-\\xde]",xt="\\ud83c[\\udffb-\\udfff]",Ct="[^\\ud800-\\udfff]",_t="(?:\\ud83c[\\udde6-\\uddff]){2}",St="[\\ud800-\\udbff][\\udc00-\\udfff]",kt="[A-Z\\xc0-\\xd6\\xd8-\\xde]",Lt="(?:"+bt+"|"+wt+")",Mt="(?:"+kt+"|"+wt+")",Tt="(?:"+gt+"|"+xt+")"+"?",Ot="[\\ufe0e\\ufe0f]?"+Tt+("(?:\\u200d(?:"+[Ct,_t,St].join("|")+")[\\ufe0e\\ufe0f]?"+Tt+")*"),At="(?:"+[yt,_t,St].join("|")+")"+Ot,Nt="(?:"+[Ct+gt+"?",gt,_t,St,pt].join("|")+")",Dt=RegExp("['’]","g"),Wt=RegExp(gt,"g"),Et=RegExp(xt+"(?="+xt+")|"+Nt+Ot,"g"),Pt=RegExp([kt+"?"+bt+"+(?:['’](?:d|ll|m|re|s|t|ve))?(?="+[vt,kt,"$"].join("|")+")",Mt+"+(?:['’](?:D|LL|M|RE|S|T|VE))?(?="+[vt,kt+Lt,"$"].join("|")+")",kt+"?"+Lt+"+(?:['’](?:d|ll|m|re|s|t|ve))?",kt+"+(?:['’](?:D|LL|M|RE|S|T|VE))?","\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",mt,At].join("|"),"g"),Rt=RegExp("[\\u200d\\ud800-\\udfff"+ht+"\\ufe0e\\ufe0f]"),Ht=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,Ft=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],It=-1,zt={};zt[k]=zt[L]=zt[M]=zt[T]=zt[O]=zt[A]=zt["[object Uint8ClampedArray]"]=zt[N]=zt[D]=!0,zt[l]=zt[u]=zt[_]=zt[c]=zt[S]=zt[f]=zt[h]=zt[d]=zt[v]=zt[g]=zt[m]=zt[y]=zt[b]=zt[w]=zt[C]=!1;var jt={};jt[l]=jt[u]=jt[_]=jt[S]=jt[c]=jt[f]=jt[k]=jt[L]=jt[M]=jt[T]=jt[O]=jt[v]=jt[g]=jt[m]=jt[y]=jt[b]=jt[w]=jt[x]=jt[A]=jt["[object Uint8ClampedArray]"]=jt[N]=jt[D]=!0,jt[h]=jt[d]=jt[C]=!1;var Bt={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},Ut=parseFloat,Vt=parseInt,Gt="object"==typeof t&&t&&t.Object===Object&&t,Kt="object"==typeof self&&self&&self.Object===Object&&self,qt=Gt||Kt||Function("return this")(),$t=e&&!e.nodeType&&e,Xt=$t&&"object"==typeof n&&n&&!n.nodeType&&n,Yt=Xt&&Xt.exports===$t,Zt=Yt&&Gt.process,Jt=function(){try{var t=Xt&&Xt.require&&Xt.require("util").types;return t||Zt&&Zt.binding&&Zt.binding("util")}catch(t){}}(),Qt=Jt&&Jt.isArrayBuffer,te=Jt&&Jt.isDate,ee=Jt&&Jt.isMap,re=Jt&&Jt.isRegExp,ne=Jt&&Jt.isSet,ie=Jt&&Jt.isTypedArray;function oe(t,e,r){switch(r.length){case 0:return t.call(e);case 1:return t.call(e,r[0]);case 2:return t.call(e,r[0],r[1]);case 3:return t.call(e,r[0],r[1],r[2])}return t.apply(e,r)}function ae(t,e,r,n){for(var i=-1,o=null==t?0:t.length;++i-1}function he(t,e,r){for(var n=-1,i=null==t?0:t.length;++n-1;);return r}function Pe(t,e){for(var r=t.length;r--&&xe(e,t[r],0)>-1;);return r}function Re(t,e){for(var r=t.length,n=0;r--;)t[r]===e&&++n;return n}var He=Le({"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"}),Fe=Le({"&":"&","<":"<",">":">",'"':""","'":"'"});function Ie(t){return "\\"+Bt[t]}function ze(t){return Rt.test(t)}function je(t){var e=-1,r=Array(t.size);return t.forEach((function(t,n){r[++e]=[n,t];})),r}function Be(t,e){return function(r){return t(e(r))}}function Ue(t,e){for(var r=-1,n=t.length,i=0,o=[];++r",""":'"',"'":"'"});var Ye=function t(e){var r,n=(e=null==e?qt:Ye.defaults(qt.Object(),e,Ye.pick(qt,Ft))).Array,i=e.Date,X=e.Error,ht=e.Function,dt=e.Math,pt=e.Object,vt=e.RegExp,gt=e.String,mt=e.TypeError,yt=n.prototype,bt=ht.prototype,wt=pt.prototype,xt=e["__core-js_shared__"],Ct=bt.toString,_t=wt.hasOwnProperty,St=0,kt=(r=/[^.]+$/.exec(xt&&xt.keys&&xt.keys.IE_PROTO||""))?"Symbol(src)_1."+r:"",Lt=wt.toString,Mt=Ct.call(pt),Tt=qt._,Ot=vt("^"+Ct.call(_t).replace(K,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),At=Yt?e.Buffer:void 0,Nt=e.Symbol,Et=e.Uint8Array,Rt=At?At.allocUnsafe:void 0,Bt=Be(pt.getPrototypeOf,pt),Gt=pt.create,Kt=wt.propertyIsEnumerable,$t=yt.splice,Xt=Nt?Nt.isConcatSpreadable:void 0,Zt=Nt?Nt.iterator:void 0,Jt=Nt?Nt.toStringTag:void 0,ye=function(){try{var t=to(pt,"defineProperty");return t({},"",{}),t}catch(t){}}(),Le=e.clearTimeout!==qt.clearTimeout&&e.clearTimeout,Ze=i&&i.now!==qt.Date.now&&i.now,Je=e.setTimeout!==qt.setTimeout&&e.setTimeout,Qe=dt.ceil,tr=dt.floor,er=pt.getOwnPropertySymbols,rr=At?At.isBuffer:void 0,nr=e.isFinite,ir=yt.join,or=Be(pt.keys,pt),ar=dt.max,sr=dt.min,lr=i.now,ur=e.parseInt,cr=dt.random,fr=yt.reverse,hr=to(e,"DataView"),dr=to(e,"Map"),pr=to(e,"Promise"),vr=to(e,"Set"),gr=to(e,"WeakMap"),mr=to(pt,"create"),yr=gr&&new gr,br={},wr=To(hr),xr=To(dr),Cr=To(pr),_r=To(vr),Sr=To(gr),kr=Nt?Nt.prototype:void 0,Lr=kr?kr.valueOf:void 0,Mr=kr?kr.toString:void 0;function Tr(t){if(Ga(t)&&!Ea(t)&&!(t instanceof Dr)){if(t instanceof Nr)return t;if(_t.call(t,"__wrapped__"))return Oo(t)}return new Nr(t)}var Or=function(){function t(){}return function(e){if(!Va(e))return {};if(Gt)return Gt(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();function Ar(){}function Nr(t,e){this.__wrapped__=t,this.__actions__=[],this.__chain__=!!e,this.__index__=0,this.__values__=void 0;}function Dr(t){this.__wrapped__=t,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=4294967295,this.__views__=[];}function Wr(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e=e?t:e)),t}function Yr(t,e,r,n,i,o){var a,s=1&e,u=2&e,h=4&e;if(r&&(a=i?r(t,n,i,o):r(t)),void 0!==a)return a;if(!Va(t))return t;var C=Ea(t);if(C){if(a=function(t){var e=t.length,r=new t.constructor(e);e&&"string"==typeof t[0]&&_t.call(t,"index")&&(r.index=t.index,r.input=t.input);return r}(t),!s)return yi(t,a)}else {var W=no(t),E=W==d||W==p;if(Fa(t))return hi(t,s);if(W==m||W==l||E&&!i){if(a=u||E?{}:oo(t),!s)return u?function(t,e){return bi(t,ro(t),e)}(t,function(t,e){return t&&bi(e,Cs(e),t)}(a,t)):function(t,e){return bi(t,eo(t),e)}(t,Kr(a,t))}else {if(!jt[W])return i?t:{};a=function(t,e,r){var n=t.constructor;switch(e){case _:return di(t);case c:case f:return new n(+t);case S:return function(t,e){var r=e?di(t.buffer):t.buffer;return new t.constructor(r,t.byteOffset,t.byteLength)}(t,r);case k:case L:case M:case T:case O:case A:case"[object Uint8ClampedArray]":case N:case D:return pi(t,r);case v:return new n;case g:case w:return new n(t);case y:return function(t){var e=new t.constructor(t.source,nt.exec(t));return e.lastIndex=t.lastIndex,e}(t);case b:return new n;case x:return i=t,Lr?pt(Lr.call(i)):{}}var i;}(t,W,s);}}o||(o=new Hr);var P=o.get(t);if(P)return P;o.set(t,a),Ya(t)?t.forEach((function(n){a.add(Yr(n,e,r,n,t,o));})):Ka(t)&&t.forEach((function(n,i){a.set(i,Yr(n,e,r,i,t,o));}));var R=C?void 0:(h?u?qi:Ki:u?Cs:xs)(t);return se(R||t,(function(n,i){R&&(n=t[i=n]),Ur(a,i,Yr(n,e,r,i,t,o));})),a}function Zr(t,e,r){var n=r.length;if(null==t)return !n;for(t=pt(t);n--;){var i=r[n],o=e[i],a=t[i];if(void 0===a&&!(i in t)||!o(a))return !1}return !0}function Jr(t,e,r){if("function"!=typeof t)throw new mt(o);return xo((function(){t.apply(void 0,r);}),e)}function Qr(t,e,r,n){var i=-1,o=fe,a=!0,s=t.length,l=[],u=e.length;if(!s)return l;r&&(e=de(e,Ne(r))),n?(o=he,a=!1):e.length>=200&&(o=We,a=!1,e=new Rr(e));t:for(;++i-1},Er.prototype.set=function(t,e){var r=this.__data__,n=Vr(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this},Pr.prototype.clear=function(){this.size=0,this.__data__={hash:new Wr,map:new(dr||Er),string:new Wr};},Pr.prototype.delete=function(t){var e=Ji(this,t).delete(t);return this.size-=e?1:0,e},Pr.prototype.get=function(t){return Ji(this,t).get(t)},Pr.prototype.has=function(t){return Ji(this,t).has(t)},Pr.prototype.set=function(t,e){var r=Ji(this,t),n=r.size;return r.set(t,e),this.size+=r.size==n?0:1,this},Rr.prototype.add=Rr.prototype.push=function(t){return this.__data__.set(t,"__lodash_hash_undefined__"),this},Rr.prototype.has=function(t){return this.__data__.has(t)},Hr.prototype.clear=function(){this.__data__=new Er,this.size=0;},Hr.prototype.delete=function(t){var e=this.__data__,r=e.delete(t);return this.size=e.size,r},Hr.prototype.get=function(t){return this.__data__.get(t)},Hr.prototype.has=function(t){return this.__data__.has(t)},Hr.prototype.set=function(t,e){var r=this.__data__;if(r instanceof Er){var n=r.__data__;if(!dr||n.length<199)return n.push([t,e]),this.size=++r.size,this;r=this.__data__=new Pr(n);}return r.set(t,e),this.size=r.size,this};var tn=Ci(un),en=Ci(cn,!0);function rn(t,e){var r=!0;return tn(t,(function(t,n,i){return r=!!e(t,n,i)})),r}function nn(t,e,r){for(var n=-1,i=t.length;++n0&&r(s)?e>1?an(s,e-1,r,n,i):pe(i,s):n||(i[i.length]=s);}return i}var sn=_i(),ln=_i(!0);function un(t,e){return t&&sn(t,e,xs)}function cn(t,e){return t&&ln(t,e,xs)}function fn(t,e){return ce(e,(function(e){return ja(t[e])}))}function hn(t,e){for(var r=0,n=(e=li(e,t)).length;null!=t&&re}function gn(t,e){return null!=t&&_t.call(t,e)}function mn(t,e){return null!=t&&e in pt(t)}function yn(t,e,r){for(var i=r?he:fe,o=t[0].length,a=t.length,s=a,l=n(a),u=1/0,c=[];s--;){var f=t[s];s&&e&&(f=de(f,Ne(e))),u=sr(f.length,u),l[s]=!r&&(e||o>=120&&f.length>=120)?new Rr(s&&f):void 0;}f=t[0];var h=-1,d=l[0];t:for(;++h=s)return l;var u=r[n];return l*("desc"==u?-1:1)}}return t.index-e.index}(t,e,r)}))}function En(t,e,r){for(var n=-1,i=e.length,o={};++n-1;)s!==t&&$t.call(s,l,1),$t.call(t,l,1);return t}function Rn(t,e){for(var r=t?e.length:0,n=r-1;r--;){var i=e[r];if(r==n||i!==o){var o=i;so(i)?$t.call(t,i,1):ti(t,i);}}return t}function Hn(t,e){return t+tr(cr()*(e-t+1))}function Fn(t,e){var r="";if(!t||e<1||e>9007199254740991)return r;do{e%2&&(r+=t),(e=tr(e/2))&&(t+=t);}while(e);return r}function In(t,e){return Co(go(t,e,qs),t+"")}function zn(t){return Ir(As(t))}function jn(t,e){var r=As(t);return ko(r,Xr(e,0,r.length))}function Bn(t,e,r,n){if(!Va(t))return t;for(var i=-1,o=(e=li(e,t)).length,a=o-1,s=t;null!=s&&++io?0:o+e),(r=r>o?o:r)<0&&(r+=o),o=e>r?0:r-e>>>0,e>>>=0;for(var a=n(o);++i>>1,a=t[o];null!==a&&!Ja(a)&&(r?a<=e:a=200){var u=e?null:Fi(t);if(u)return Ve(u);a=!1,i=We,l=new Rr;}else l=e?[]:s;t:for(;++n=n?t:Kn(t,e,r)}var fi=Le||function(t){return qt.clearTimeout(t)};function hi(t,e){if(e)return t.slice();var r=t.length,n=Rt?Rt(r):new t.constructor(r);return t.copy(n),n}function di(t){var e=new t.constructor(t.byteLength);return new Et(e).set(new Et(t)),e}function pi(t,e){var r=e?di(t.buffer):t.buffer;return new t.constructor(r,t.byteOffset,t.length)}function vi(t,e){if(t!==e){var r=void 0!==t,n=null===t,i=t==t,o=Ja(t),a=void 0!==e,s=null===e,l=e==e,u=Ja(e);if(!s&&!u&&!o&&t>e||o&&a&&l&&!s&&!u||n&&a&&l||!r&&l||!i)return 1;if(!n&&!o&&!u&&t1?r[i-1]:void 0,a=i>2?r[2]:void 0;for(o=t.length>3&&"function"==typeof o?(i--,o):void 0,a&&lo(r[0],r[1],a)&&(o=i<3?void 0:o,i=1),e=pt(e);++n-1?i[o?e[a]:a]:void 0}}function Ti(t){return Gi((function(e){var r=e.length,n=r,i=Nr.prototype.thru;for(t&&e.reverse();n--;){var a=e[n];if("function"!=typeof a)throw new mt(o);if(i&&!s&&"wrapper"==Xi(a))var s=new Nr([],!0);}for(n=s?n:r;++n1&&b.reverse(),f&&us))return !1;var u=o.get(t),c=o.get(e);if(u&&c)return u==e&&c==t;var f=-1,h=!0,d=2&r?new Rr:void 0;for(o.set(t,e),o.set(e,t);++f-1&&t%1==0&&t1?"& ":"")+e[n],e=e.join(r>2?", ":" "),t.replace(Y,"{\n/* [wrapped with "+e+"] */\n")}(n,function(t,e){return se(s,(function(r){var n="_."+r[0];e&r[1]&&!fe(t,n)&&t.push(n);})),t.sort()}(function(t){var e=t.match(Z);return e?e[1].split(J):[]}(n),r)))}function So(t){var e=0,r=0;return function(){var n=lr(),i=16-(n-r);if(r=n,i>0){if(++e>=800)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}function ko(t,e){var r=-1,n=t.length,i=n-1;for(e=void 0===e?n:e;++r1?t[e-1]:void 0;return r="function"==typeof r?(t.pop(),r):void 0,Xo(t,r)}));function ra(t){var e=Tr(t);return e.__chain__=!0,e}function na(t,e){return e(t)}var ia=Gi((function(t){var e=t.length,r=e?t[0]:0,n=this.__wrapped__,i=function(e){return $r(e,t)};return !(e>1||this.__actions__.length)&&n instanceof Dr&&so(r)?((n=n.slice(r,+r+(e?1:0))).__actions__.push({func:na,args:[i],thisArg:void 0}),new Nr(n,this.__chain__).thru((function(t){return e&&!t.length&&t.push(void 0),t}))):this.thru(i)}));var oa=wi((function(t,e,r){_t.call(t,r)?++t[r]:qr(t,r,1);}));var aa=Mi(Wo),sa=Mi(Eo);function la(t,e){return (Ea(t)?se:tn)(t,Zi(e,3))}function ua(t,e){return (Ea(t)?le:en)(t,Zi(e,3))}var ca=wi((function(t,e,r){_t.call(t,r)?t[r].push(e):qr(t,r,[e]);}));var fa=In((function(t,e,r){var i=-1,o="function"==typeof e,a=Ra(t)?n(t.length):[];return tn(t,(function(t){a[++i]=o?oe(e,t,r):bn(t,e,r);})),a})),ha=wi((function(t,e,r){qr(t,r,e);}));function da(t,e){return (Ea(t)?de:Tn)(t,Zi(e,3))}var pa=wi((function(t,e,r){t[r?0:1].push(e);}),(function(){return [[],[]]}));var va=In((function(t,e){if(null==t)return [];var r=e.length;return r>1&&lo(t,e[0],e[1])?e=[]:r>2&&lo(e[0],e[1],e[2])&&(e=[e[0]]),Wn(t,an(e,1),[])})),ga=Ze||function(){return qt.Date.now()};function ma(t,e,r){return e=r?void 0:e,zi(t,128,void 0,void 0,void 0,void 0,e=t&&null==e?t.length:e)}function ya(t,e){var r;if("function"!=typeof e)throw new mt(o);return t=is(t),function(){return --t>0&&(r=e.apply(this,arguments)),t<=1&&(e=void 0),r}}var ba=In((function(t,e,r){var n=1;if(r.length){var i=Ue(r,Yi(ba));n|=32;}return zi(t,n,e,r,i)})),wa=In((function(t,e,r){var n=3;if(r.length){var i=Ue(r,Yi(wa));n|=32;}return zi(e,n,t,r,i)}));function xa(t,e,r){var n,i,a,s,l,u,c=0,f=!1,h=!1,d=!0;if("function"!=typeof t)throw new mt(o);function p(e){var r=n,o=i;return n=i=void 0,c=e,s=t.apply(o,r)}function v(t){return c=t,l=xo(m,e),f?p(t):s}function g(t){var r=t-u;return void 0===u||r>=e||r<0||h&&t-c>=a}function m(){var t=ga();if(g(t))return y(t);l=xo(m,function(t){var r=e-(t-u);return h?sr(r,a-(t-c)):r}(t));}function y(t){return l=void 0,d&&n?p(t):(n=i=void 0,s)}function b(){var t=ga(),r=g(t);if(n=arguments,i=this,u=t,r){if(void 0===l)return v(u);if(h)return fi(l),l=xo(m,e),p(u)}return void 0===l&&(l=xo(m,e)),s}return e=as(e)||0,Va(r)&&(f=!!r.leading,a=(h="maxWait"in r)?ar(as(r.maxWait)||0,e):a,d="trailing"in r?!!r.trailing:d),b.cancel=function(){void 0!==l&&fi(l),c=0,n=u=i=l=void 0;},b.flush=function(){return void 0===l?s:y(ga())},b}var Ca=In((function(t,e){return Jr(t,1,e)})),_a=In((function(t,e,r){return Jr(t,as(e)||0,r)}));function Sa(t,e){if("function"!=typeof t||null!=e&&"function"!=typeof e)throw new mt(o);var r=function(){var n=arguments,i=e?e.apply(this,n):n[0],o=r.cache;if(o.has(i))return o.get(i);var a=t.apply(this,n);return r.cache=o.set(i,a)||o,a};return r.cache=new(Sa.Cache||Pr),r}function ka(t){if("function"!=typeof t)throw new mt(o);return function(){var e=arguments;switch(e.length){case 0:return !t.call(this);case 1:return !t.call(this,e[0]);case 2:return !t.call(this,e[0],e[1]);case 3:return !t.call(this,e[0],e[1],e[2])}return !t.apply(this,e)}}Sa.Cache=Pr;var La=ui((function(t,e){var r=(e=1==e.length&&Ea(e[0])?de(e[0],Ne(Zi())):de(an(e,1),Ne(Zi()))).length;return In((function(n){for(var i=-1,o=sr(n.length,r);++i=e})),Wa=wn(function(){return arguments}())?wn:function(t){return Ga(t)&&_t.call(t,"callee")&&!Kt.call(t,"callee")},Ea=n.isArray,Pa=Qt?Ne(Qt):function(t){return Ga(t)&&pn(t)==_};function Ra(t){return null!=t&&Ua(t.length)&&!ja(t)}function Ha(t){return Ga(t)&&Ra(t)}var Fa=rr||al,Ia=te?Ne(te):function(t){return Ga(t)&&pn(t)==f};function za(t){if(!Ga(t))return !1;var e=pn(t);return e==h||"[object DOMException]"==e||"string"==typeof t.message&&"string"==typeof t.name&&!$a(t)}function ja(t){if(!Va(t))return !1;var e=pn(t);return e==d||e==p||"[object AsyncFunction]"==e||"[object Proxy]"==e}function Ba(t){return "number"==typeof t&&t==is(t)}function Ua(t){return "number"==typeof t&&t>-1&&t%1==0&&t<=9007199254740991}function Va(t){var e=typeof t;return null!=t&&("object"==e||"function"==e)}function Ga(t){return null!=t&&"object"==typeof t}var Ka=ee?Ne(ee):function(t){return Ga(t)&&no(t)==v};function qa(t){return "number"==typeof t||Ga(t)&&pn(t)==g}function $a(t){if(!Ga(t)||pn(t)!=m)return !1;var e=Bt(t);if(null===e)return !0;var r=_t.call(e,"constructor")&&e.constructor;return "function"==typeof r&&r instanceof r&&Ct.call(r)==Mt}var Xa=re?Ne(re):function(t){return Ga(t)&&pn(t)==y};var Ya=ne?Ne(ne):function(t){return Ga(t)&&no(t)==b};function Za(t){return "string"==typeof t||!Ea(t)&&Ga(t)&&pn(t)==w}function Ja(t){return "symbol"==typeof t||Ga(t)&&pn(t)==x}var Qa=ie?Ne(ie):function(t){return Ga(t)&&Ua(t.length)&&!!zt[pn(t)]};var ts=Pi(Mn),es=Pi((function(t,e){return t<=e}));function rs(t){if(!t)return [];if(Ra(t))return Za(t)?qe(t):yi(t);if(Zt&&t[Zt])return function(t){for(var e,r=[];!(e=t.next()).done;)r.push(e.value);return r}(t[Zt]());var e=no(t);return (e==v?je:e==b?Ve:As)(t)}function ns(t){return t?(t=as(t))===1/0||t===-1/0?17976931348623157e292*(t<0?-1:1):t==t?t:0:0===t?t:0}function is(t){var e=ns(t),r=e%1;return e==e?r?e-r:e:0}function os(t){return t?Xr(is(t),0,4294967295):0}function as(t){if("number"==typeof t)return t;if(Ja(t))return NaN;if(Va(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=Va(e)?e+"":e;}if("string"!=typeof t)return 0===t?t:+t;t=Ae(t);var r=ot.test(t);return r||st.test(t)?Vt(t.slice(2),r?2:8):it.test(t)?NaN:+t}function ss(t){return bi(t,Cs(t))}function ls(t){return null==t?"":Jn(t)}var us=xi((function(t,e){if(ho(e)||Ra(e))bi(e,xs(e),t);else for(var r in e)_t.call(e,r)&&Ur(t,r,e[r]);})),cs=xi((function(t,e){bi(e,Cs(e),t);})),fs=xi((function(t,e,r,n){bi(e,Cs(e),t,n);})),hs=xi((function(t,e,r,n){bi(e,xs(e),t,n);})),ds=Gi($r);var ps=In((function(t,e){t=pt(t);var r=-1,n=e.length,i=n>2?e[2]:void 0;for(i&&lo(e[0],e[1],i)&&(n=1);++r1),e})),bi(t,qi(t),r),n&&(r=Yr(r,7,Ui));for(var i=e.length;i--;)ti(r,e[i]);return r}));var Ls=Gi((function(t,e){return null==t?{}:function(t,e){return En(t,e,(function(e,r){return ms(t,r)}))}(t,e)}));function Ms(t,e){if(null==t)return {};var r=de(qi(t),(function(t){return [t]}));return e=Zi(e),En(t,r,(function(t,r){return e(t,r[0])}))}var Ts=Ii(xs),Os=Ii(Cs);function As(t){return null==t?[]:De(t,xs(t))}var Ns=ki((function(t,e,r){return e=e.toLowerCase(),t+(r?Ds(e):e)}));function Ds(t){return zs(ls(t).toLowerCase())}function Ws(t){return (t=ls(t))&&t.replace(ut,He).replace(Wt,"")}var Es=ki((function(t,e,r){return t+(r?"-":"")+e.toLowerCase()})),Ps=ki((function(t,e,r){return t+(r?" ":"")+e.toLowerCase()})),Rs=Si("toLowerCase");var Hs=ki((function(t,e,r){return t+(r?"_":"")+e.toLowerCase()}));var Fs=ki((function(t,e,r){return t+(r?" ":"")+zs(e)}));var Is=ki((function(t,e,r){return t+(r?" ":"")+e.toUpperCase()})),zs=Si("toUpperCase");function js(t,e,r){return t=ls(t),void 0===(e=r?void 0:e)?function(t){return Ht.test(t)}(t)?function(t){return t.match(Pt)||[]}(t):function(t){return t.match(Q)||[]}(t):t.match(e)||[]}var Bs=In((function(t,e){try{return oe(t,void 0,e)}catch(t){return za(t)?t:new X(t)}})),Us=Gi((function(t,e){return se(e,(function(e){e=Mo(e),qr(t,e,ba(t[e],t));})),t}));function Vs(t){return function(){return t}}var Gs=Ti(),Ks=Ti(!0);function qs(t){return t}function $s(t){return Sn("function"==typeof t?t:Yr(t,1))}var Xs=In((function(t,e){return function(r){return bn(r,t,e)}})),Ys=In((function(t,e){return function(r){return bn(t,r,e)}}));function Zs(t,e,r){var n=xs(e),i=fn(e,n);null!=r||Va(e)&&(i.length||!n.length)||(r=e,e=t,t=this,i=fn(e,xs(e)));var o=!(Va(r)&&"chain"in r&&!r.chain),a=ja(t);return se(i,(function(r){var n=e[r];t[r]=n,a&&(t.prototype[r]=function(){var e=this.__chain__;if(o||e){var r=t(this.__wrapped__),i=r.__actions__=yi(this.__actions__);return i.push({func:n,args:arguments,thisArg:t}),r.__chain__=e,r}return n.apply(t,pe([this.value()],arguments))});})),t}function Js(){}var Qs=Di(de),tl=Di(ue),el=Di(me);function rl(t){return uo(t)?ke(Mo(t)):function(t){return function(e){return hn(e,t)}}(t)}var nl=Ei(),il=Ei(!0);function ol(){return []}function al(){return !1}var sl=Ni((function(t,e){return t+e}),0),ll=Hi("ceil"),ul=Ni((function(t,e){return t/e}),1),cl=Hi("floor");var fl,hl=Ni((function(t,e){return t*e}),1),dl=Hi("round"),pl=Ni((function(t,e){return t-e}),0);return Tr.after=function(t,e){if("function"!=typeof e)throw new mt(o);return t=is(t),function(){if(--t<1)return e.apply(this,arguments)}},Tr.ary=ma,Tr.assign=us,Tr.assignIn=cs,Tr.assignInWith=fs,Tr.assignWith=hs,Tr.at=ds,Tr.before=ya,Tr.bind=ba,Tr.bindAll=Us,Tr.bindKey=wa,Tr.castArray=function(){if(!arguments.length)return [];var t=arguments[0];return Ea(t)?t:[t]},Tr.chain=ra,Tr.chunk=function(t,e,r){e=(r?lo(t,e,r):void 0===e)?1:ar(is(e),0);var i=null==t?0:t.length;if(!i||e<1)return [];for(var o=0,a=0,s=n(Qe(i/e));oi?0:i+r),(n=void 0===n||n>i?i:is(n))<0&&(n+=i),n=r>n?0:os(n);r>>0)?(t=ls(t))&&("string"==typeof e||null!=e&&!Xa(e))&&!(e=Jn(e))&&ze(t)?ci(qe(t),0,r):t.split(e,r):[]},Tr.spread=function(t,e){if("function"!=typeof t)throw new mt(o);return e=null==e?0:ar(is(e),0),In((function(r){var n=r[e],i=ci(r,0,e);return n&&pe(i,n),oe(t,this,i)}))},Tr.tail=function(t){var e=null==t?0:t.length;return e?Kn(t,1,e):[]},Tr.take=function(t,e,r){return t&&t.length?Kn(t,0,(e=r||void 0===e?1:is(e))<0?0:e):[]},Tr.takeRight=function(t,e,r){var n=null==t?0:t.length;return n?Kn(t,(e=n-(e=r||void 0===e?1:is(e)))<0?0:e,n):[]},Tr.takeRightWhile=function(t,e){return t&&t.length?ri(t,Zi(e,3),!1,!0):[]},Tr.takeWhile=function(t,e){return t&&t.length?ri(t,Zi(e,3)):[]},Tr.tap=function(t,e){return e(t),t},Tr.throttle=function(t,e,r){var n=!0,i=!0;if("function"!=typeof t)throw new mt(o);return Va(r)&&(n="leading"in r?!!r.leading:n,i="trailing"in r?!!r.trailing:i),xa(t,e,{leading:n,maxWait:e,trailing:i})},Tr.thru=na,Tr.toArray=rs,Tr.toPairs=Ts,Tr.toPairsIn=Os,Tr.toPath=function(t){return Ea(t)?de(t,Mo):Ja(t)?[t]:yi(Lo(ls(t)))},Tr.toPlainObject=ss,Tr.transform=function(t,e,r){var n=Ea(t),i=n||Fa(t)||Qa(t);if(e=Zi(e,4),null==r){var o=t&&t.constructor;r=i?n?new o:[]:Va(t)&&ja(o)?Or(Bt(t)):{};}return (i?se:un)(t,(function(t,n,i){return e(r,t,n,i)})),r},Tr.unary=function(t){return ma(t,1)},Tr.union=Go,Tr.unionBy=Ko,Tr.unionWith=qo,Tr.uniq=function(t){return t&&t.length?Qn(t):[]},Tr.uniqBy=function(t,e){return t&&t.length?Qn(t,Zi(e,2)):[]},Tr.uniqWith=function(t,e){return e="function"==typeof e?e:void 0,t&&t.length?Qn(t,void 0,e):[]},Tr.unset=function(t,e){return null==t||ti(t,e)},Tr.unzip=$o,Tr.unzipWith=Xo,Tr.update=function(t,e,r){return null==t?t:ei(t,e,si(r))},Tr.updateWith=function(t,e,r,n){return n="function"==typeof n?n:void 0,null==t?t:ei(t,e,si(r),n)},Tr.values=As,Tr.valuesIn=function(t){return null==t?[]:De(t,Cs(t))},Tr.without=Yo,Tr.words=js,Tr.wrap=function(t,e){return Ma(si(e),t)},Tr.xor=Zo,Tr.xorBy=Jo,Tr.xorWith=Qo,Tr.zip=ta,Tr.zipObject=function(t,e){return oi(t||[],e||[],Ur)},Tr.zipObjectDeep=function(t,e){return oi(t||[],e||[],Bn)},Tr.zipWith=ea,Tr.entries=Ts,Tr.entriesIn=Os,Tr.extend=cs,Tr.extendWith=fs,Zs(Tr,Tr),Tr.add=sl,Tr.attempt=Bs,Tr.camelCase=Ns,Tr.capitalize=Ds,Tr.ceil=ll,Tr.clamp=function(t,e,r){return void 0===r&&(r=e,e=void 0),void 0!==r&&(r=(r=as(r))==r?r:0),void 0!==e&&(e=(e=as(e))==e?e:0),Xr(as(t),e,r)},Tr.clone=function(t){return Yr(t,4)},Tr.cloneDeep=function(t){return Yr(t,5)},Tr.cloneDeepWith=function(t,e){return Yr(t,5,e="function"==typeof e?e:void 0)},Tr.cloneWith=function(t,e){return Yr(t,4,e="function"==typeof e?e:void 0)},Tr.conformsTo=function(t,e){return null==e||Zr(t,e,xs(e))},Tr.deburr=Ws,Tr.defaultTo=function(t,e){return null==t||t!=t?e:t},Tr.divide=ul,Tr.endsWith=function(t,e,r){t=ls(t),e=Jn(e);var n=t.length,i=r=void 0===r?n:Xr(is(r),0,n);return (r-=e.length)>=0&&t.slice(r,i)==e},Tr.eq=Aa,Tr.escape=function(t){return (t=ls(t))&&I.test(t)?t.replace(H,Fe):t},Tr.escapeRegExp=function(t){return (t=ls(t))&&q.test(t)?t.replace(K,"\\$&"):t},Tr.every=function(t,e,r){var n=Ea(t)?ue:rn;return r&&lo(t,e,r)&&(e=void 0),n(t,Zi(e,3))},Tr.find=aa,Tr.findIndex=Wo,Tr.findKey=function(t,e){return be(t,Zi(e,3),un)},Tr.findLast=sa,Tr.findLastIndex=Eo,Tr.findLastKey=function(t,e){return be(t,Zi(e,3),cn)},Tr.floor=cl,Tr.forEach=la,Tr.forEachRight=ua,Tr.forIn=function(t,e){return null==t?t:sn(t,Zi(e,3),Cs)},Tr.forInRight=function(t,e){return null==t?t:ln(t,Zi(e,3),Cs)},Tr.forOwn=function(t,e){return t&&un(t,Zi(e,3))},Tr.forOwnRight=function(t,e){return t&&cn(t,Zi(e,3))},Tr.get=gs,Tr.gt=Na,Tr.gte=Da,Tr.has=function(t,e){return null!=t&&io(t,e,gn)},Tr.hasIn=ms,Tr.head=Ro,Tr.identity=qs,Tr.includes=function(t,e,r,n){t=Ra(t)?t:As(t),r=r&&!n?is(r):0;var i=t.length;return r<0&&(r=ar(i+r,0)),Za(t)?r<=i&&t.indexOf(e,r)>-1:!!i&&xe(t,e,r)>-1},Tr.indexOf=function(t,e,r){var n=null==t?0:t.length;if(!n)return -1;var i=null==r?0:is(r);return i<0&&(i=ar(n+i,0)),xe(t,e,i)},Tr.inRange=function(t,e,r){return e=ns(e),void 0===r?(r=e,e=0):r=ns(r),function(t,e,r){return t>=sr(e,r)&&t=-9007199254740991&&t<=9007199254740991},Tr.isSet=Ya,Tr.isString=Za,Tr.isSymbol=Ja,Tr.isTypedArray=Qa,Tr.isUndefined=function(t){return void 0===t},Tr.isWeakMap=function(t){return Ga(t)&&no(t)==C},Tr.isWeakSet=function(t){return Ga(t)&&"[object WeakSet]"==pn(t)},Tr.join=function(t,e){return null==t?"":ir.call(t,e)},Tr.kebabCase=Es,Tr.last=zo,Tr.lastIndexOf=function(t,e,r){var n=null==t?0:t.length;if(!n)return -1;var i=n;return void 0!==r&&(i=(i=is(r))<0?ar(n+i,0):sr(i,n-1)),e==e?function(t,e,r){for(var n=r+1;n--;)if(t[n]===e)return n;return n}(t,e,i):we(t,_e,i,!0)},Tr.lowerCase=Ps,Tr.lowerFirst=Rs,Tr.lt=ts,Tr.lte=es,Tr.max=function(t){return t&&t.length?nn(t,qs,vn):void 0},Tr.maxBy=function(t,e){return t&&t.length?nn(t,Zi(e,2),vn):void 0},Tr.mean=function(t){return Se(t,qs)},Tr.meanBy=function(t,e){return Se(t,Zi(e,2))},Tr.min=function(t){return t&&t.length?nn(t,qs,Mn):void 0},Tr.minBy=function(t,e){return t&&t.length?nn(t,Zi(e,2),Mn):void 0},Tr.stubArray=ol,Tr.stubFalse=al,Tr.stubObject=function(){return {}},Tr.stubString=function(){return ""},Tr.stubTrue=function(){return !0},Tr.multiply=hl,Tr.nth=function(t,e){return t&&t.length?Dn(t,is(e)):void 0},Tr.noConflict=function(){return qt._===this&&(qt._=Tt),this},Tr.noop=Js,Tr.now=ga,Tr.pad=function(t,e,r){t=ls(t);var n=(e=is(e))?Ke(t):0;if(!e||n>=e)return t;var i=(e-n)/2;return Wi(tr(i),r)+t+Wi(Qe(i),r)},Tr.padEnd=function(t,e,r){t=ls(t);var n=(e=is(e))?Ke(t):0;return e&&ne){var n=t;t=e,e=n;}if(r||t%1||e%1){var i=cr();return sr(t+i*(e-t+Ut("1e-"+((i+"").length-1))),e)}return Hn(t,e)},Tr.reduce=function(t,e,r){var n=Ea(t)?ve:Me,i=arguments.length<3;return n(t,Zi(e,4),r,i,tn)},Tr.reduceRight=function(t,e,r){var n=Ea(t)?ge:Me,i=arguments.length<3;return n(t,Zi(e,4),r,i,en)},Tr.repeat=function(t,e,r){return e=(r?lo(t,e,r):void 0===e)?1:is(e),Fn(ls(t),e)},Tr.replace=function(){var t=arguments,e=ls(t[0]);return t.length<3?e:e.replace(t[1],t[2])},Tr.result=function(t,e,r){var n=-1,i=(e=li(e,t)).length;for(i||(i=1,t=void 0);++n9007199254740991)return [];var r=4294967295,n=sr(t,4294967295);t-=4294967295;for(var i=Oe(n,e=Zi(e));++r=o)return t;var s=r-Ke(n);if(s<1)return n;var l=a?ci(a,0,s).join(""):t.slice(0,s);if(void 0===i)return l+n;if(a&&(s+=l.length-s),Xa(i)){if(t.slice(s).search(i)){var u,c=l;for(i.global||(i=vt(i.source,ls(nt.exec(i))+"g")),i.lastIndex=0;u=i.exec(c);)var f=u.index;l=l.slice(0,void 0===f?s:f);}}else if(t.indexOf(Jn(i),s)!=s){var h=l.lastIndexOf(i);h>-1&&(l=l.slice(0,h));}return l+n},Tr.unescape=function(t){return (t=ls(t))&&F.test(t)?t.replace(R,Xe):t},Tr.uniqueId=function(t){var e=++St;return ls(t)+e},Tr.upperCase=Is,Tr.upperFirst=zs,Tr.each=la,Tr.eachRight=ua,Tr.first=Ro,Zs(Tr,(fl={},un(Tr,(function(t,e){_t.call(Tr.prototype,e)||(fl[e]=t);})),fl),{chain:!1}),Tr.VERSION="4.17.21",se(["bind","bindKey","curry","curryRight","partial","partialRight"],(function(t){Tr[t].placeholder=Tr;})),se(["drop","take"],(function(t,e){Dr.prototype[t]=function(r){r=void 0===r?1:ar(is(r),0);var n=this.__filtered__&&!e?new Dr(this):this.clone();return n.__filtered__?n.__takeCount__=sr(r,n.__takeCount__):n.__views__.push({size:sr(r,4294967295),type:t+(n.__dir__<0?"Right":"")}),n},Dr.prototype[t+"Right"]=function(e){return this.reverse()[t](e).reverse()};})),se(["filter","map","takeWhile"],(function(t,e){var r=e+1,n=1==r||3==r;Dr.prototype[t]=function(t){var e=this.clone();return e.__iteratees__.push({iteratee:Zi(t,3),type:r}),e.__filtered__=e.__filtered__||n,e};})),se(["head","last"],(function(t,e){var r="take"+(e?"Right":"");Dr.prototype[t]=function(){return this[r](1).value()[0]};})),se(["initial","tail"],(function(t,e){var r="drop"+(e?"":"Right");Dr.prototype[t]=function(){return this.__filtered__?new Dr(this):this[r](1)};})),Dr.prototype.compact=function(){return this.filter(qs)},Dr.prototype.find=function(t){return this.filter(t).head()},Dr.prototype.findLast=function(t){return this.reverse().find(t)},Dr.prototype.invokeMap=In((function(t,e){return "function"==typeof t?new Dr(this):this.map((function(r){return bn(r,t,e)}))})),Dr.prototype.reject=function(t){return this.filter(ka(Zi(t)))},Dr.prototype.slice=function(t,e){t=is(t);var r=this;return r.__filtered__&&(t>0||e<0)?new Dr(r):(t<0?r=r.takeRight(-t):t&&(r=r.drop(t)),void 0!==e&&(r=(e=is(e))<0?r.dropRight(-e):r.take(e-t)),r)},Dr.prototype.takeRightWhile=function(t){return this.reverse().takeWhile(t).reverse()},Dr.prototype.toArray=function(){return this.take(4294967295)},un(Dr.prototype,(function(t,e){var r=/^(?:filter|find|map|reject)|While$/.test(e),n=/^(?:head|last)$/.test(e),i=Tr[n?"take"+("last"==e?"Right":""):e],o=n||/^find/.test(e);i&&(Tr.prototype[e]=function(){var e=this.__wrapped__,a=n?[1]:arguments,s=e instanceof Dr,l=a[0],u=s||Ea(e),c=function(t){var e=i.apply(Tr,pe([t],a));return n&&f?e[0]:e};u&&r&&"function"==typeof l&&1!=l.length&&(s=u=!1);var f=this.__chain__,h=!!this.__actions__.length,d=o&&!f,p=s&&!h;if(!o&&u){e=p?e:new Dr(this);var v=t.apply(e,a);return v.__actions__.push({func:na,args:[c],thisArg:void 0}),new Nr(v,f)}return d&&p?t.apply(this,a):(v=this.thru(c),d?n?v.value()[0]:v.value():v)});})),se(["pop","push","shift","sort","splice","unshift"],(function(t){var e=yt[t],r=/^(?:push|sort|unshift)$/.test(t)?"tap":"thru",n=/^(?:pop|shift)$/.test(t);Tr.prototype[t]=function(){var t=arguments;if(n&&!this.__chain__){var i=this.value();return e.apply(Ea(i)?i:[],t)}return this[r]((function(r){return e.apply(Ea(r)?r:[],t)}))};})),un(Dr.prototype,(function(t,e){var r=Tr[e];if(r){var n=r.name+"";_t.call(br,n)||(br[n]=[]),br[n].push({name:e,func:r});}})),br[Oi(void 0,2).name]=[{name:"wrapper",func:void 0}],Dr.prototype.clone=function(){var t=new Dr(this.__wrapped__);return t.__actions__=yi(this.__actions__),t.__dir__=this.__dir__,t.__filtered__=this.__filtered__,t.__iteratees__=yi(this.__iteratees__),t.__takeCount__=this.__takeCount__,t.__views__=yi(this.__views__),t},Dr.prototype.reverse=function(){if(this.__filtered__){var t=new Dr(this);t.__dir__=-1,t.__filtered__=!0;}else (t=this.clone()).__dir__*=-1;return t},Dr.prototype.value=function(){var t=this.__wrapped__.value(),e=this.__dir__,r=Ea(t),n=e<0,i=r?t.length:0,o=function(t,e,r){var n=-1,i=r.length;for(;++n=this.__values__.length;return {done:t,value:t?void 0:this.__values__[this.__index__++]}},Tr.prototype.plant=function(t){for(var e,r=this;r instanceof Ar;){var n=Oo(r);n.__index__=0,n.__values__=void 0,e?i.__wrapped__=n:e=n;var i=n;r=r.__wrapped__;}return i.__wrapped__=t,e},Tr.prototype.reverse=function(){var t=this.__wrapped__;if(t instanceof Dr){var e=t;return this.__actions__.length&&(e=new Dr(this)),(e=e.reverse()).__actions__.push({func:na,args:[Vo],thisArg:void 0}),new Nr(e,this.__chain__)}return this.thru(Vo)},Tr.prototype.toJSON=Tr.prototype.valueOf=Tr.prototype.value=function(){return ni(this.__wrapped__,this.__actions__)},Tr.prototype.first=Tr.prototype.head,Zt&&(Tr.prototype[Zt]=function(){return this}),Tr}();qt._=Ye,void 0===(i=function(){return Ye}.call(e,r,e,n))||(n.exports=i);}).call(this);}).call(this,r(7),r(21)(t));},function(e,r){e.exports=t;},function(t,e,r){t.exports=function(){var t=navigator.userAgent,e=navigator.platform,r=/gecko\/\d/i.test(t),n=/MSIE \d/.test(t),i=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(t),o=/Edge\/(\d+)/.exec(t),a=n||i||o,s=a&&(n?document.documentMode||6:+(o||i)[1]),l=!o&&/WebKit\//.test(t),u=l&&/Qt\/\d+\.\d+/.test(t),c=!o&&/Chrome\//.test(t),f=/Opera\//.test(t),h=/Apple Computer/.test(navigator.vendor),d=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(t),p=/PhantomJS/.test(t),v=!o&&/AppleWebKit/.test(t)&&/Mobile\/\w+/.test(t),g=/Android/.test(t),m=v||g||/webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(t),y=v||/Mac/.test(e),b=/\bCrOS\b/.test(t),w=/win/i.test(e),x=f&&t.match(/Version\/(\d*\.\d*)/);x&&(x=Number(x[1])),x&&x>=15&&(f=!1,l=!0);var C=y&&(u||f&&(null==x||x<12.11)),_=r||a&&s>=9;function S(t){return new RegExp("(^|\\s)"+t+"(?:$|\\s)\\s*")}var k,L=function(t,e){var r=t.className,n=S(e).exec(r);if(n){var i=r.slice(n.index+n[0].length);t.className=r.slice(0,n.index)+(i?n[1]+i:"");}};function M(t){for(var e=t.childNodes.length;e>0;--e)t.removeChild(t.firstChild);return t}function T(t,e){return M(t).appendChild(e)}function O(t,e,r,n){var i=document.createElement(t);if(r&&(i.className=r),n&&(i.style.cssText=n),"string"==typeof e)i.appendChild(document.createTextNode(e));else if(e)for(var o=0;o=e)return a+(e-o);a+=s-o,a+=r-a%r,o=s+1;}}v?P=function(t){t.selectionStart=0,t.selectionEnd=t.value.length;}:a&&(P=function(t){try{t.select();}catch(t){}});var I=function(){this.id=null;};function z(t,e){for(var r=0;r=e)return n+Math.min(a,e-i);if(i+=o-n,n=o+1,(i+=r-i%r)>=e)return n}}var K=[""];function q(t){for(;K.length<=t;)K.push($(K)+" ");return K[t]}function $(t){return t[t.length-1]}function X(t,e){for(var r=[],n=0;n"€"&&(t.toUpperCase()!=t.toLowerCase()||J.test(t))}function tt(t,e){return e?!!(e.source.indexOf("\\w")>-1&&Q(t))||e.test(t):Q(t)}function et(t){for(var e in t)if(t.hasOwnProperty(e)&&t[e])return !1;return !0}var rt=/[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;function nt(t){return t.charCodeAt(0)>=768&&rt.test(t)}function it(t,e,r){for(;(r<0?e>0:er?-1:1;;){if(e==r)return e;var i=(e+r)/2,o=n<0?Math.ceil(i):Math.floor(i);if(o==e)return t(o)?e:r;t(o)?r=o:e=o+n;}}function at(t,e,n){var i=this;this.input=n,i.scrollbarFiller=O("div",null,"CodeMirror-scrollbar-filler"),i.scrollbarFiller.setAttribute("cm-not-content","true"),i.gutterFiller=O("div",null,"CodeMirror-gutter-filler"),i.gutterFiller.setAttribute("cm-not-content","true"),i.lineDiv=A("div",null,"CodeMirror-code"),i.selectionDiv=O("div",null,null,"position: relative; z-index: 1"),i.cursorDiv=O("div",null,"CodeMirror-cursors"),i.measure=O("div",null,"CodeMirror-measure"),i.lineMeasure=O("div",null,"CodeMirror-measure"),i.lineSpace=A("div",[i.measure,i.lineMeasure,i.selectionDiv,i.cursorDiv,i.lineDiv],null,"position: relative; outline: none");var o=A("div",[i.lineSpace],"CodeMirror-lines");i.mover=O("div",[o],null,"position: relative"),i.sizer=O("div",[i.mover],"CodeMirror-sizer"),i.sizerWidth=null,i.heightForcer=O("div",null,null,"position: absolute; height: 30px; width: 1px;"),i.gutters=O("div",null,"CodeMirror-gutters"),i.lineGutter=null,i.scroller=O("div",[i.sizer,i.heightForcer,i.gutters],"CodeMirror-scroll"),i.scroller.setAttribute("tabIndex","-1"),i.wrapper=O("div",[i.scrollbarFiller,i.gutterFiller,i.scroller],"CodeMirror"),a&&s<8&&(i.gutters.style.zIndex=-1,i.scroller.style.paddingRight=0),l||r&&m||(i.scroller.draggable=!0),t&&(t.appendChild?t.appendChild(i.wrapper):t(i.wrapper)),i.viewFrom=i.viewTo=e.first,i.reportedViewFrom=i.reportedViewTo=e.first,i.view=[],i.renderedView=null,i.externalMeasured=null,i.viewOffset=0,i.lastWrapHeight=i.lastWrapWidth=0,i.updateLineNumbers=null,i.nativeBarWidth=i.barHeight=i.barWidth=0,i.scrollbarsClipped=!1,i.lineNumWidth=i.lineNumInnerWidth=i.lineNumChars=null,i.alignWidgets=!1,i.cachedCharWidth=i.cachedTextHeight=i.cachedPaddingH=null,i.maxLine=null,i.maxLineLength=0,i.maxLineChanged=!1,i.wheelDX=i.wheelDY=i.wheelStartX=i.wheelStartY=null,i.shift=!1,i.selForContextMenu=null,i.activeTouch=null,n.init(i);}function st(t,e){if((e-=t.first)<0||e>=t.size)throw new Error("There is no line "+(e+t.first)+" in the document.");for(var r=t;!r.lines;)for(var n=0;;++n){var i=r.children[n],o=i.chunkSize();if(e=t.first&&er?vt(r,st(t,r).text.length):function(t,e){var r=t.ch;return null==r||r>e?vt(t.line,e):r<0?vt(t.line,0):t}(e,st(t,e.line).text.length)}function _t(t,e){for(var r=[],n=0;n=e:o.to>e);(n||(n=[])).push(new Lt(a,o.from,s?null:o.to));}}return n}(r,i,a),l=function(t,e,r){var n;if(t)for(var i=0;i=e:o.to>e)||o.from==e&&"bookmark"==a.type&&(!r||o.marker.insertLeft)){var s=null==o.from||(a.inclusiveLeft?o.from<=e:o.from0&&s)for(var b=0;be)&&(!r||Pt(r,o.marker)<0)&&(r=o.marker);}return r}function zt(t,e,r,n,i){var o=st(t,e),a=kt&&o.markedSpans;if(a)for(var s=0;s=0&&f<=0||c<=0&&f>=0)&&(c<=0&&(l.marker.inclusiveRight&&i.inclusiveLeft?gt(u.to,r)>=0:gt(u.to,r)>0)||c>=0&&(l.marker.inclusiveRight&&i.inclusiveLeft?gt(u.from,n)<=0:gt(u.from,n)<0)))return !0}}}function jt(t){for(var e;e=Ht(t);)t=e.find(-1,!0).line;return t}function Bt(t,e){var r=st(t,e),n=jt(r);return r==n?e:ft(n)}function Ut(t,e){if(e>t.lastLine())return e;var r,n=st(t,e);if(!Vt(t,n))return e;for(;r=Ft(n);)n=r.find(1,!0).line;return ft(n)+1}function Vt(t,e){var r=kt&&e.markedSpans;if(r)for(var n=void 0,i=0;ie.maxLineLength&&(e.maxLineLength=r,e.maxLine=t);}));}var Xt=null;function Yt(t,e,r){var n;Xt=null;for(var i=0;ie)return i;o.to==e&&(o.from!=o.to&&"before"==r?n=i:Xt=i),o.from==e&&(o.from!=o.to&&"before"!=r?n=i:Xt=i);}return null!=n?n:Xt}var Zt=function(){var t=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,e=/[stwN]/,r=/[LRr]/,n=/[Lb1n]/,i=/[1n]/;function o(t,e,r){this.level=t,this.from=e,this.to=r;}return function(a,s){var l="ltr"==s?"L":"R";if(0==a.length||"ltr"==s&&!t.test(a))return !1;for(var u,c=a.length,f=[],h=0;h-1&&(n[e]=i.slice(0,o).concat(i.slice(o+1)));}}}function ne(t,e){var r=ee(t,e);if(r.length)for(var n=Array.prototype.slice.call(arguments,2),i=0;i0}function se(t){t.prototype.on=function(t,e){te(this,t,e);},t.prototype.off=function(t,e){re(this,t,e);};}function le(t){t.preventDefault?t.preventDefault():t.returnValue=!1;}function ue(t){t.stopPropagation?t.stopPropagation():t.cancelBubble=!0;}function ce(t){return null!=t.defaultPrevented?t.defaultPrevented:0==t.returnValue}function fe(t){le(t),ue(t);}function he(t){return t.target||t.srcElement}function de(t){var e=t.which;return null==e&&(1&t.button?e=1:2&t.button?e=3:4&t.button&&(e=2)),y&&t.ctrlKey&&1==e&&(e=3),e}var pe,ve,ge=function(){if(a&&s<9)return !1;var t=O("div");return "draggable"in t||"dragDrop"in t}();function me(t){if(null==pe){var e=O("span","​");T(t,O("span",[e,document.createTextNode("x")])),0!=t.firstChild.offsetHeight&&(pe=e.offsetWidth<=1&&e.offsetHeight>2&&!(a&&s<8));}var r=pe?O("span","​"):O("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px");return r.setAttribute("cm-text",""),r}function ye(t){if(null!=ve)return ve;var e=T(t,document.createTextNode("AخA")),r=k(e,0,1).getBoundingClientRect(),n=k(e,1,2).getBoundingClientRect();return M(t),!(!r||r.left==r.right)&&(ve=n.right-r.right<3)}var be,we=3!="\n\nb".split(/\n/).length?function(t){for(var e=0,r=[],n=t.length;e<=n;){var i=t.indexOf("\n",e);-1==i&&(i=t.length);var o=t.slice(e,"\r"==t.charAt(i-1)?i-1:i),a=o.indexOf("\r");-1!=a?(r.push(o.slice(0,a)),e+=a+1):(r.push(o),e=i+1);}return r}:function(t){return t.split(/\r\n?|\n/)},xe=window.getSelection?function(t){try{return t.selectionStart!=t.selectionEnd}catch(t){return !1}}:function(t){var e;try{e=t.ownerDocument.selection.createRange();}catch(t){}return !(!e||e.parentElement()!=t)&&0!=e.compareEndPoints("StartToEnd",e)},Ce="oncopy"in(be=O("div"))||(be.setAttribute("oncopy","return;"),"function"==typeof be.oncopy),_e=null,Se={},ke={};function Le(t,e){arguments.length>2&&(e.dependencies=Array.prototype.slice.call(arguments,2)),Se[t]=e;}function Me(t){if("string"==typeof t&&ke.hasOwnProperty(t))t=ke[t];else if(t&&"string"==typeof t.name&&ke.hasOwnProperty(t.name)){var e=ke[t.name];"string"==typeof e&&(e={name:e}),(t=Z(e,t)).name=e.name;}else {if("string"==typeof t&&/^[\w\-]+\/[\w\-]+\+xml$/.test(t))return Me("application/xml");if("string"==typeof t&&/^[\w\-]+\/[\w\-]+\+json$/.test(t))return Me("application/json")}return "string"==typeof t?{name:t}:t||{name:"null"}}function Te(t,e){e=Me(e);var r=Se[e.name];if(!r)return Te(t,"text/plain");var n=r(t,e);if(Oe.hasOwnProperty(e.name)){var i=Oe[e.name];for(var o in i)i.hasOwnProperty(o)&&(n.hasOwnProperty(o)&&(n["_"+o]=n[o]),n[o]=i[o]);}if(n.name=e.name,e.helperType&&(n.helperType=e.helperType),e.modeProps)for(var a in e.modeProps)n[a]=e.modeProps[a];return n}var Oe={};function Ae(t,e){H(e,Oe.hasOwnProperty(t)?Oe[t]:Oe[t]={});}function Ne(t,e){if(!0===e)return e;if(t.copyState)return t.copyState(e);var r={};for(var n in e){var i=e[n];i instanceof Array&&(i=i.concat([])),r[n]=i;}return r}function De(t,e){for(var r;t.innerMode&&(r=t.innerMode(e))&&r.mode!=t;)e=r.state,t=r.mode;return r||{mode:t,state:e}}function We(t,e,r){return !t.startState||t.startState(e,r)}var Ee=function(t,e,r){this.pos=this.start=0,this.string=t,this.tabSize=e||8,this.lastColumnPos=this.lastColumnValue=0,this.lineStart=0,this.lineOracle=r;};Ee.prototype.eol=function(){return this.pos>=this.string.length},Ee.prototype.sol=function(){return this.pos==this.lineStart},Ee.prototype.peek=function(){return this.string.charAt(this.pos)||void 0},Ee.prototype.next=function(){if(this.pose},Ee.prototype.eatSpace=function(){for(var t=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>t},Ee.prototype.skipToEnd=function(){this.pos=this.string.length;},Ee.prototype.skipTo=function(t){var e=this.string.indexOf(t,this.pos);if(e>-1)return this.pos=e,!0},Ee.prototype.backUp=function(t){this.pos-=t;},Ee.prototype.column=function(){return this.lastColumnPos0?null:(n&&!1!==e&&(this.pos+=n[0].length),n)}var i=function(t){return r?t.toLowerCase():t};if(i(this.string.substr(this.pos,t.length))==i(t))return !1!==e&&(this.pos+=t.length),!0},Ee.prototype.current=function(){return this.string.slice(this.start,this.pos)},Ee.prototype.hideFirstChars=function(t,e){this.lineStart+=t;try{return e()}finally{this.lineStart-=t;}},Ee.prototype.lookAhead=function(t){var e=this.lineOracle;return e&&e.lookAhead(t)},Ee.prototype.baseToken=function(){var t=this.lineOracle;return t&&t.baseToken(this.pos)};var Pe=function(t,e){this.state=t,this.lookAhead=e;},Re=function(t,e,r,n){this.state=e,this.doc=t,this.line=r,this.maxLookAhead=n||0,this.baseTokens=null,this.baseTokenPos=1;};function He(t,e,r,n){var i=[t.state.modeGen],o={};Ke(t,e.text,t.doc.mode,r,(function(t,e){return i.push(t,e)}),o,n);for(var a=r.state,s=function(n){r.baseTokens=i;var s=t.state.overlays[n],l=1,u=0;r.state=!0,Ke(t,e.text,s.mode,r,(function(t,e){for(var r=l;ut&&i.splice(l,1,t,i[l+1],n),l+=2,u=Math.min(t,n);}if(e)if(s.opaque)i.splice(r,l-r,t,"overlay "+e),l=r+2;else for(;rt.options.maxHighlightLength&&Ne(t.doc.mode,n.state),o=He(t,e,n);i&&(n.state=i),e.stateAfter=n.save(!i),e.styles=o.styles,o.classes?e.styleClasses=o.classes:e.styleClasses&&(e.styleClasses=null),r===t.doc.highlightFrontier&&(t.doc.modeFrontier=Math.max(t.doc.modeFrontier,++t.doc.highlightFrontier));}return e.styles}function Ie(t,e,r){var n=t.doc,i=t.display;if(!n.mode.startState)return new Re(n,!0,e);var o=function(t,e,r){for(var n,i,o=t.doc,a=r?-1:e-(t.doc.mode.innerMode?1e3:100),s=e;s>a;--s){if(s<=o.first)return o.first;var l=st(o,s-1),u=l.stateAfter;if(u&&(!r||s+(u instanceof Pe?u.lookAhead:0)<=o.modeFrontier))return s;var c=F(l.text,null,t.options.tabSize);(null==i||n>c)&&(i=s-1,n=c);}return i}(t,e,r),a=o>n.first&&st(n,o-1).stateAfter,s=a?Re.fromSaved(n,a,o):new Re(n,We(n.mode),o);return n.iter(o,e,(function(r){ze(t,r.text,s);var n=s.line;r.stateAfter=n==e-1||n%5==0||n>=i.viewFrom&&ne.start)return o}throw new Error("Mode "+t.name+" failed to advance stream.")}Re.prototype.lookAhead=function(t){var e=this.doc.getLine(this.line+t);return null!=e&&t>this.maxLookAhead&&(this.maxLookAhead=t),e},Re.prototype.baseToken=function(t){if(!this.baseTokens)return null;for(;this.baseTokens[this.baseTokenPos]<=t;)this.baseTokenPos+=2;var e=this.baseTokens[this.baseTokenPos+1];return {type:e&&e.replace(/( |^)overlay .*/,""),size:this.baseTokens[this.baseTokenPos]-t}},Re.prototype.nextLine=function(){this.line++,this.maxLookAhead>0&&this.maxLookAhead--;},Re.fromSaved=function(t,e,r){return e instanceof Pe?new Re(t,Ne(t.mode,e.state),r,e.lookAhead):new Re(t,Ne(t.mode,e),r)},Re.prototype.save=function(t){var e=!1!==t?Ne(this.doc.mode,this.state):this.state;return this.maxLookAhead>0?new Pe(e,this.maxLookAhead):e};var Ue=function(t,e,r){this.start=t.start,this.end=t.pos,this.string=t.current(),this.type=e||null,this.state=r;};function Ve(t,e,r,n){var i,o,a=t.doc,s=a.mode,l=st(a,(e=Ct(a,e)).line),u=Ie(t,e.line,r),c=new Ee(l.text,t.options.tabSize,u);for(n&&(o=[]);(n||c.post.options.maxHighlightLength?(s=!1,a&&ze(t,e,n,f.pos),f.pos=e.length,l=null):l=Ge(Be(r,f,n.state,h),o),h){var d=h[0].name;d&&(l="m-"+(l?d+" "+l:d));}if(!s||c!=l){for(;u1&&!/ /.test(t))return t;for(var r=e,n="",i=0;iu&&f.from<=u);h++);if(f.to>=c)return t(r,n,i,o,a,s,l);t(r,n.slice(0,f.to-u),i,o,null,s,l),o=null,n=n.slice(f.to-u),u=f.to;}}}function rr(t,e,r,n){var i=!n&&r.widgetNode;i&&t.map.push(t.pos,t.pos+e,i),!n&&t.cm.display.input.needsContentAttribute&&(i||(i=t.content.appendChild(document.createElement("span"))),i.setAttribute("cm-marker",r.id)),i&&(t.cm.display.input.setUneditable(i),t.content.appendChild(i)),t.pos+=e,t.trailingSpace=!1;}function nr(t,e,r){var n=t.markedSpans,i=t.text,o=0;if(n)for(var a,s,l,u,c,f,h,d=i.length,p=0,v=1,g="",m=0;;){if(m==p){l=u=c=s="",h=null,f=null,m=1/0;for(var y=[],b=void 0,w=0;wp||C.collapsed&&x.to==p&&x.from==p)){if(null!=x.to&&x.to!=p&&m>x.to&&(m=x.to,u=""),C.className&&(l+=" "+C.className),C.css&&(s=(s?s+";":"")+C.css),C.startStyle&&x.from==p&&(c+=" "+C.startStyle),C.endStyle&&x.to==m&&(b||(b=[])).push(C.endStyle,x.to),C.title&&((h||(h={})).title=C.title),C.attributes)for(var _ in C.attributes)(h||(h={}))[_]=C.attributes[_];C.collapsed&&(!f||Pt(f.marker,C)<0)&&(f=x);}else x.from>p&&m>x.from&&(m=x.from);}if(b)for(var S=0;S=d)break;for(var L=Math.min(d,m);;){if(g){var M=p+g.length;if(!f){var T=M>L?g.slice(0,L-p):g;e.addToken(e,T,a?a+l:l,c,p+T.length==m?u:"",s,h);}if(M>=L){g=g.slice(L-p),p=L;break}p=M,c="";}g=i.slice(o,o=r[v++]),a=Ze(r[v++],e.cm.options);}}else for(var O=1;Or)return {map:t.measure.maps[i],cache:t.measure.caches[i],before:!0}}function Ar(t,e,r,n){return Wr(t,Dr(t,e),r,n)}function Nr(t,e){if(e>=t.display.viewFrom&&e=r.lineN&&e2&&o.push((l.bottom+u.top)/2-r.top);}}o.push(r.bottom-r.top);}}(t,e.view,e.rect),e.hasHeights=!0),(o=function(t,e,r,n){var i,o=Rr(e.map,r,n),l=o.node,u=o.start,c=o.end,f=o.collapse;if(3==l.nodeType){for(var h=0;h<4;h++){for(;u&&nt(e.line.text.charAt(o.coverStart+u));)--u;for(;o.coverStart+c1}(t))return e;var r=screen.logicalXDPI/screen.deviceXDPI,n=screen.logicalYDPI/screen.deviceYDPI;return {left:e.left*r,right:e.right*r,top:e.top*n,bottom:e.bottom*n}}(t.display.measure,i));}else {var d;u>0&&(f=n="right"),i=t.options.lineWrapping&&(d=l.getClientRects()).length>1?d["right"==n?d.length-1:0]:l.getBoundingClientRect();}if(a&&s<9&&!u&&(!i||!i.left&&!i.right)){var p=l.parentNode.getClientRects()[0];i=p?{left:p.left,right:p.left+on(t.display),top:p.top,bottom:p.bottom}:Pr;}for(var v=i.top-e.rect.top,g=i.bottom-e.rect.top,m=(v+g)/2,y=e.view.measure.heights,b=0;be)&&(i=(o=l-s)-1,e>=l&&(a="right")),null!=i){if(n=t[u+2],s==l&&r==(n.insertLeft?"left":"right")&&(a=r),"left"==r&&0==i)for(;u&&t[u-2]==t[u-3]&&t[u-1].insertLeft;)n=t[2+(u-=3)],a="left";if("right"==r&&i==l-s)for(;u=0&&(r=t[i]).left==r.right;i--);return r}function Fr(t){if(t.measure&&(t.measure.cache={},t.measure.heights=null,t.rest))for(var e=0;e=n.text.length?(l=n.text.length,u="before"):l<=0&&(l=0,u="after"),!s)return a("before"==u?l-1:l,"before"==u);function c(t,e,r){return a(r?t-1:t,1==s[e].level!=r)}var f=Yt(s,l,u),h=Xt,d=c(l,f,"before"==u);return null!=h&&(d.other=c(l,h,"before"!=u)),d}function $r(t,e){var r=0;e=Ct(t.doc,e),t.options.lineWrapping||(r=on(t.display)*e.ch);var n=st(t.doc,e.line),i=Kt(n)+_r(t.display);return {left:r,right:r,top:i,bottom:i+n.height}}function Xr(t,e,r,n,i){var o=vt(t,e,r);return o.xRel=i,n&&(o.outside=!0),o}function Yr(t,e,r){var n=t.doc;if((r+=t.display.viewOffset)<0)return Xr(n.first,0,null,!0,-1);var i=ht(n,r),o=n.first+n.size-1;if(i>o)return Xr(n.first+n.size-1,st(n,o).text.length,null,!0,1);e<0&&(e=0);for(var a=st(n,i);;){var s=tn(t,a,i,e,r),l=It(a,s.ch+(s.xRel>0?1:0));if(!l)return s;var u=l.find(1);if(u.line==i)return u;a=st(n,i=u.line);}}function Zr(t,e,r,n){n-=Ur(e);var i=e.text.length,o=ot((function(e){return Wr(t,r,e-1).bottom<=n}),i,0);return {begin:o,end:i=ot((function(e){return Wr(t,r,e).top>n}),o,i)}}function Jr(t,e,r,n){return r||(r=Dr(t,e)),Zr(t,e,r,Vr(t,e,Wr(t,r,n),"line").top)}function Qr(t,e,r,n){return !(t.bottom<=r)&&(t.top>r||(n?t.left:t.right)>e)}function tn(t,e,r,n,i){i-=Kt(e);var o=Dr(t,e),a=Ur(e),s=0,l=e.text.length,u=!0,c=Jt(e,t.doc.direction);if(c){var f=(t.options.lineWrapping?rn:en)(t,e,r,o,c,n,i);s=(u=1!=f.level)?f.from:f.to-1,l=u?f.to:f.from-1;}var h,d,p=null,v=null,g=ot((function(e){var r=Wr(t,o,e);return r.top+=a,r.bottom+=a,!!Qr(r,n,i,!1)&&(r.top<=i&&r.left<=n&&(p=e,v=r),!0)}),s,l),m=!1;if(v){var y=n-v.left=w.bottom;}return Xr(r,g=it(e.text,g,1),d,m,n-h)}function en(t,e,r,n,i,o,a){var s=ot((function(s){var l=i[s],u=1!=l.level;return Qr(qr(t,vt(r,u?l.to:l.from,u?"before":"after"),"line",e,n),o,a,!0)}),0,i.length-1),l=i[s];if(s>0){var u=1!=l.level,c=qr(t,vt(r,u?l.from:l.to,u?"after":"before"),"line",e,n);Qr(c,o,a,!0)&&c.top>a&&(l=i[s-1]);}return l}function rn(t,e,r,n,i,o,a){var s=Zr(t,e,n,a),l=s.begin,u=s.end;/\s/.test(e.text.charAt(u-1))&&u--;for(var c=null,f=null,h=0;h=u||d.to<=l)){var p=Wr(t,n,1!=d.level?Math.min(u,d.to)-1:Math.max(l,d.from)).right,v=pv)&&(c=d,f=v);}}return c||(c=i[i.length-1]),c.fromu&&(c={from:c.from,to:u,level:c.level}),c}function nn(t){if(null!=t.cachedTextHeight)return t.cachedTextHeight;if(null==Er){Er=O("pre");for(var e=0;e<49;++e)Er.appendChild(document.createTextNode("x")),Er.appendChild(O("br"));Er.appendChild(document.createTextNode("x"));}T(t.measure,Er);var r=Er.offsetHeight/50;return r>3&&(t.cachedTextHeight=r),M(t.measure),r||1}function on(t){if(null!=t.cachedCharWidth)return t.cachedCharWidth;var e=O("span","xxxxxxxxxx"),r=O("pre",[e]);T(t.measure,r);var n=e.getBoundingClientRect(),i=(n.right-n.left)/10;return i>2&&(t.cachedCharWidth=i),i||10}function an(t){for(var e=t.display,r={},n={},i=e.gutters.clientLeft,o=e.gutters.firstChild,a=0;o;o=o.nextSibling,++a)r[t.options.gutters[a]]=o.offsetLeft+o.clientLeft+i,n[t.options.gutters[a]]=o.clientWidth;return {fixedPos:sn(e),gutterTotalWidth:e.gutters.offsetWidth,gutterLeft:r,gutterWidth:n,wrapperWidth:e.wrapper.clientWidth}}function sn(t){return t.scroller.getBoundingClientRect().left-t.sizer.getBoundingClientRect().left}function ln(t){var e=nn(t.display),r=t.options.lineWrapping,n=r&&Math.max(5,t.display.scroller.clientWidth/on(t.display)-3);return function(i){if(Vt(t.doc,i))return 0;var o=0;if(i.widgets)for(var a=0;a=t.display.viewTo)return null;if((e-=t.display.viewFrom)<0)return null;for(var r=t.display.view,n=0;n=t.display.viewTo||s.to().linee||e==r&&a.to==e)&&(n(Math.max(a.from,e),Math.min(a.to,r),1==a.level?"rtl":"ltr",o),i=!0);}i||n(e,r,"ltr");}(v,r||0,null==n?h:n,(function(t,e,i,f){var g="ltr"==i,m=d(t,g?"left":"right"),y=d(e-1,g?"right":"left"),b=null==r&&0==t,w=null==n&&e==h,x=0==f,C=!v||f==v.length-1;if(y.top-m.top<=3){var _=(u?w:b)&&C,S=(u?b:w)&&x?s:(g?m:y).left,k=_?l:(g?y:m).right;c(S,m.top,k-S,m.bottom);}else {var L,M,T,O;g?(L=u&&b&&x?s:m.left,M=u?l:p(t,i,"before"),T=u?s:p(e,i,"after"),O=u&&w&&C?l:y.right):(L=u?p(t,i,"before"):s,M=!u&&b&&x?l:m.right,T=!u&&w&&C?s:y.left,O=u?p(e,i,"after"):l),c(L,m.top,M-L,m.bottom),m.bottom0?e.blinker=setInterval((function(){return e.cursorDiv.style.visibility=(r=!r)?"":"hidden"}),t.options.cursorBlinkRate):t.options.cursorBlinkRate<0&&(e.cursorDiv.style.visibility="hidden");}}function yn(t){t.state.focused||(t.display.input.focus(),wn(t));}function bn(t){t.state.delayingBlurEvent=!0,setTimeout((function(){t.state.delayingBlurEvent&&(t.state.delayingBlurEvent=!1,xn(t));}),100);}function wn(t,e){t.state.delayingBlurEvent&&(t.state.delayingBlurEvent=!1),"nocursor"!=t.options.readOnly&&(t.state.focused||(ne(t,"focus",t,e),t.state.focused=!0,W(t.display.wrapper,"CodeMirror-focused"),t.curOp||t.display.selForContextMenu==t.doc.sel||(t.display.input.reset(),l&&setTimeout((function(){return t.display.input.reset(!0)}),20)),t.display.input.receivedFocus()),mn(t));}function xn(t,e){t.state.delayingBlurEvent||(t.state.focused&&(ne(t,"blur",t,e),t.state.focused=!1,L(t.display.wrapper,"CodeMirror-focused")),clearInterval(t.display.blinker),setTimeout((function(){t.state.focused||(t.display.shift=!1);}),150));}function Cn(t){for(var e=t.display,r=e.lineDiv.offsetTop,n=0;n.005||h<-.005)&&(ct(i.line,l),_n(i.line),i.rest))for(var d=0;dt.display.sizerWidth){var p=Math.ceil(u/on(t.display));p>t.display.maxLineLength&&(t.display.maxLineLength=p,t.display.maxLine=i.line,t.display.maxLineChanged=!0);}}}}function _n(t){if(t.widgets)for(var e=0;e=a&&(o=ht(e,Kt(st(e,l))-t.wrapper.clientHeight),a=l);}return {from:o,to:Math.max(a,o+1)}}function kn(t){var e=t.display,r=e.view;if(e.alignWidgets||e.gutters.firstChild&&t.options.fixedGutter){for(var n=sn(e)-e.scroller.scrollLeft+t.doc.scrollLeft,i=e.gutters.offsetWidth,o=n+"px",a=0;ao&&(e.bottom=e.top+o);var s=t.doc.height+Sr(r),l=e.tops-n;if(e.topi+o){var c=Math.min(e.top,(u?s:e.bottom)-o);c!=i&&(a.scrollTop=c);}var f=t.curOp&&null!=t.curOp.scrollLeft?t.curOp.scrollLeft:r.scroller.scrollLeft,h=Mr(t)-(t.options.fixedGutter?r.gutters.offsetWidth:0),d=e.right-e.left>h;return d&&(e.right=e.left+h),e.left<10?a.scrollLeft=0:e.lefth+f-3&&(a.scrollLeft=e.right+(d?0:10)-h),a}function Tn(t,e){null!=e&&(Nn(t),t.curOp.scrollTop=(null==t.curOp.scrollTop?t.doc.scrollTop:t.curOp.scrollTop)+e);}function On(t){Nn(t);var e=t.getCursor();t.curOp.scrollToPos={from:e,to:e,margin:t.options.cursorScrollMargin};}function An(t,e,r){null==e&&null==r||Nn(t),null!=e&&(t.curOp.scrollLeft=e),null!=r&&(t.curOp.scrollTop=r);}function Nn(t){var e=t.curOp.scrollToPos;e&&(t.curOp.scrollToPos=null,Dn(t,$r(t,e.from),$r(t,e.to),e.margin));}function Dn(t,e,r,n){var i=Mn(t,{left:Math.min(e.left,r.left),top:Math.min(e.top,r.top)-n,right:Math.max(e.right,r.right),bottom:Math.max(e.bottom,r.bottom)+n});An(t,i.scrollLeft,i.scrollTop);}function Wn(t,e){Math.abs(t.doc.scrollTop-e)<2||(r||fi(t,{top:e}),En(t,e,!0),r&&fi(t),ai(t,100));}function En(t,e,r){e=Math.min(t.display.scroller.scrollHeight-t.display.scroller.clientHeight,e),(t.display.scroller.scrollTop!=e||r)&&(t.doc.scrollTop=e,t.display.scrollbars.setScrollTop(e),t.display.scroller.scrollTop!=e&&(t.display.scroller.scrollTop=e));}function Pn(t,e,r,n){e=Math.min(e,t.display.scroller.scrollWidth-t.display.scroller.clientWidth),(r?e==t.doc.scrollLeft:Math.abs(t.doc.scrollLeft-e)<2)&&!n||(t.doc.scrollLeft=e,kn(t),t.display.scroller.scrollLeft!=e&&(t.display.scroller.scrollLeft=e),t.display.scrollbars.setScrollLeft(e));}function Rn(t){var e=t.display,r=e.gutters.offsetWidth,n=Math.round(t.doc.height+Sr(t.display));return {clientHeight:e.scroller.clientHeight,viewHeight:e.wrapper.clientHeight,scrollWidth:e.scroller.scrollWidth,clientWidth:e.scroller.clientWidth,viewWidth:e.wrapper.clientWidth,barLeft:t.options.fixedGutter?r:0,docHeight:n,scrollHeight:n+Lr(t)+e.barHeight,nativeBarWidth:e.nativeBarWidth,gutterWidth:r}}var Hn=function(t,e,r){this.cm=r;var n=this.vert=O("div",[O("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),i=this.horiz=O("div",[O("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar");n.tabIndex=i.tabIndex=-1,t(n),t(i),te(n,"scroll",(function(){n.clientHeight&&e(n.scrollTop,"vertical");})),te(i,"scroll",(function(){i.clientWidth&&e(i.scrollLeft,"horizontal");})),this.checkedZeroWidth=!1,a&&s<8&&(this.horiz.style.minHeight=this.vert.style.minWidth="18px");};Hn.prototype.update=function(t){var e=t.scrollWidth>t.clientWidth+1,r=t.scrollHeight>t.clientHeight+1,n=t.nativeBarWidth;if(r){this.vert.style.display="block",this.vert.style.bottom=e?n+"px":"0";var i=t.viewHeight-(e?n:0);this.vert.firstChild.style.height=Math.max(0,t.scrollHeight-t.clientHeight+i)+"px";}else this.vert.style.display="",this.vert.firstChild.style.height="0";if(e){this.horiz.style.display="block",this.horiz.style.right=r?n+"px":"0",this.horiz.style.left=t.barLeft+"px";var o=t.viewWidth-t.barLeft-(r?n:0);this.horiz.firstChild.style.width=Math.max(0,t.scrollWidth-t.clientWidth+o)+"px";}else this.horiz.style.display="",this.horiz.firstChild.style.width="0";return !this.checkedZeroWidth&&t.clientHeight>0&&(0==n&&this.zeroWidthHack(),this.checkedZeroWidth=!0),{right:r?n:0,bottom:e?n:0}},Hn.prototype.setScrollLeft=function(t){this.horiz.scrollLeft!=t&&(this.horiz.scrollLeft=t),this.disableHoriz&&this.enableZeroWidthBar(this.horiz,this.disableHoriz,"horiz");},Hn.prototype.setScrollTop=function(t){this.vert.scrollTop!=t&&(this.vert.scrollTop=t),this.disableVert&&this.enableZeroWidthBar(this.vert,this.disableVert,"vert");},Hn.prototype.zeroWidthHack=function(){var t=y&&!d?"12px":"18px";this.horiz.style.height=this.vert.style.width=t,this.horiz.style.pointerEvents=this.vert.style.pointerEvents="none",this.disableHoriz=new I,this.disableVert=new I;},Hn.prototype.enableZeroWidthBar=function(t,e,r){t.style.pointerEvents="auto",e.set(1e3,(function n(){var i=t.getBoundingClientRect();("vert"==r?document.elementFromPoint(i.right-1,(i.top+i.bottom)/2):document.elementFromPoint((i.right+i.left)/2,i.bottom-1))!=t?t.style.pointerEvents="none":e.set(1e3,n);}));},Hn.prototype.clear=function(){var t=this.horiz.parentNode;t.removeChild(this.horiz),t.removeChild(this.vert);};var Fn=function(){};function In(t,e){e||(e=Rn(t));var r=t.display.barWidth,n=t.display.barHeight;zn(t,e);for(var i=0;i<4&&r!=t.display.barWidth||n!=t.display.barHeight;i++)r!=t.display.barWidth&&t.options.lineWrapping&&Cn(t),zn(t,Rn(t)),r=t.display.barWidth,n=t.display.barHeight;}function zn(t,e){var r=t.display,n=r.scrollbars.update(e);r.sizer.style.paddingRight=(r.barWidth=n.right)+"px",r.sizer.style.paddingBottom=(r.barHeight=n.bottom)+"px",r.heightForcer.style.borderBottom=n.bottom+"px solid transparent",n.right&&n.bottom?(r.scrollbarFiller.style.display="block",r.scrollbarFiller.style.height=n.bottom+"px",r.scrollbarFiller.style.width=n.right+"px"):r.scrollbarFiller.style.display="",n.bottom&&t.options.coverGutterNextToScrollbar&&t.options.fixedGutter?(r.gutterFiller.style.display="block",r.gutterFiller.style.height=n.bottom+"px",r.gutterFiller.style.width=e.gutterWidth+"px"):r.gutterFiller.style.display="";}Fn.prototype.update=function(){return {bottom:0,right:0}},Fn.prototype.setScrollLeft=function(){},Fn.prototype.setScrollTop=function(){},Fn.prototype.clear=function(){};var jn={native:Hn,null:Fn};function Bn(t){t.display.scrollbars&&(t.display.scrollbars.clear(),t.display.scrollbars.addClass&&L(t.display.wrapper,t.display.scrollbars.addClass)),t.display.scrollbars=new jn[t.options.scrollbarStyle]((function(e){t.display.wrapper.insertBefore(e,t.display.scrollbarFiller),te(e,"mousedown",(function(){t.state.focused&&setTimeout((function(){return t.display.input.focus()}),0);})),e.setAttribute("cm-not-content","true");}),(function(e,r){"horizontal"==r?Pn(t,e):Wn(t,e);}),t),t.display.scrollbars.addClass&&W(t.display.wrapper,t.display.scrollbars.addClass);}var Un=0;function Vn(t){var e;t.curOp={cm:t,viewChanged:!1,startHeight:t.doc.height,forceUpdate:!1,updateInput:null,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,focus:!1,id:++Un},e=t.curOp,ar?ar.ops.push(e):e.ownsGroup=ar={ops:[e],delayedCallbacks:[]};}function Gn(t){var e=t.curOp;e&&function(t,e){var r=t.ownsGroup;if(r)try{!function(t){var e=t.delayedCallbacks,r=0;do{for(;r=r.viewTo)||r.maxLineChanged&&e.options.lineWrapping,t.update=t.mustUpdate&&new li(e,t.mustUpdate&&{top:t.scrollTop,ensure:t.scrollToPos},t.forceUpdate);}function qn(t){t.updatedDisplay=t.mustUpdate&&ui(t.cm,t.update);}function $n(t){var e=t.cm,r=e.display;t.updatedDisplay&&Cn(e),t.barMeasure=Rn(e),r.maxLineChanged&&!e.options.lineWrapping&&(t.adjustWidthTo=Ar(e,r.maxLine,r.maxLine.text.length).left+3,e.display.sizerWidth=t.adjustWidthTo,t.barMeasure.scrollWidth=Math.max(r.scroller.clientWidth,r.sizer.offsetLeft+t.adjustWidthTo+Lr(e)+e.display.barWidth),t.maxScrollLeft=Math.max(0,r.sizer.offsetLeft+t.adjustWidthTo-Mr(e))),(t.updatedDisplay||t.selectionChanged)&&(t.preparedSelection=r.input.prepareSelection());}function Xn(t){var e=t.cm;null!=t.adjustWidthTo&&(e.display.sizer.style.minWidth=t.adjustWidthTo+"px",t.maxScrollLeft(window.innerHeight||document.documentElement.clientHeight)&&(i=!1),null!=i&&!p){var o=O("div","​",null,"position: absolute;\n top: "+(e.top-r.viewOffset-_r(t.display))+"px;\n height: "+(e.bottom-e.top+Lr(t)+r.barHeight)+"px;\n left: "+e.left+"px; width: "+Math.max(2,e.right-e.left)+"px;");t.display.lineSpace.appendChild(o),o.scrollIntoView(i),t.display.lineSpace.removeChild(o);}}}(e,function(t,e,r,n){var i;null==n&&(n=0),t.options.lineWrapping||e!=r||(r="before"==(e=e.ch?vt(e.line,"before"==e.sticky?e.ch-1:e.ch,"after"):e).sticky?vt(e.line,e.ch+1,"before"):e);for(var o=0;o<5;o++){var a=!1,s=qr(t,e),l=r&&r!=e?qr(t,r):s,u=Mn(t,i={left:Math.min(s.left,l.left),top:Math.min(s.top,l.top)-n,right:Math.max(s.left,l.left),bottom:Math.max(s.bottom,l.bottom)+n}),c=t.doc.scrollTop,f=t.doc.scrollLeft;if(null!=u.scrollTop&&(Wn(t,u.scrollTop),Math.abs(t.doc.scrollTop-c)>1&&(a=!0)),null!=u.scrollLeft&&(Pn(t,u.scrollLeft),Math.abs(t.doc.scrollLeft-f)>1&&(a=!0)),!a)break}return i}(e,Ct(n,t.scrollToPos.from),Ct(n,t.scrollToPos.to),t.scrollToPos.margin));var i=t.maybeHiddenMarkers,o=t.maybeUnhiddenMarkers;if(i)for(var a=0;ae)&&(i.updateLineNumbers=e),t.curOp.viewChanged=!0,e>=i.viewTo)kt&&Bt(t.doc,e)i.viewFrom?ni(t):(i.viewFrom+=n,i.viewTo+=n);else if(e<=i.viewFrom&&r>=i.viewTo)ni(t);else if(e<=i.viewFrom){var o=ii(t,r,r+n,1);o?(i.view=i.view.slice(o.index),i.viewFrom=o.lineN,i.viewTo+=n):ni(t);}else if(r>=i.viewTo){var a=ii(t,e,e,-1);a?(i.view=i.view.slice(0,a.index),i.viewTo=a.lineN):ni(t);}else {var s=ii(t,e,e,-1),l=ii(t,r,r+n,1);s&&l?(i.view=i.view.slice(0,s.index).concat(or(t,s.lineN,l.lineN)).concat(i.view.slice(l.index)),i.viewTo+=n):ni(t);}var u=i.externalMeasured;u&&(r=i.lineN&&e=n.viewTo)){var o=n.view[fn(t,e)];if(null!=o.node){var a=o.changes||(o.changes=[]);-1==z(a,r)&&a.push(r);}}}function ni(t){t.display.viewFrom=t.display.viewTo=t.doc.first,t.display.view=[],t.display.viewOffset=0;}function ii(t,e,r,n){var i,o=fn(t,e),a=t.display.view;if(!kt||r==t.doc.first+t.doc.size)return {index:o,lineN:r};for(var s=t.display.viewFrom,l=0;l0){if(o==a.length-1)return null;i=s+a[o].size-e,o++;}else i=s-e;e+=i,r+=i;}for(;Bt(t.doc,r)!=r;){if(o==(n<0?0:a.length-1))return null;r+=n*a[o-(n<0?1:0)].size,o+=n;}return {index:o,lineN:r}}function oi(t){for(var e=t.display.view,r=0,n=0;n=t.display.viewTo)){var r=+new Date+t.options.workTime,n=Ie(t,e.highlightFrontier),i=[];e.iter(n.line,Math.min(e.first+e.size,t.display.viewTo+500),(function(o){if(n.line>=t.display.viewFrom){var a=o.styles,s=o.text.length>t.options.maxHighlightLength?Ne(e.mode,n.state):null,l=He(t,o,n,!0);s&&(n.state=s),o.styles=l.styles;var u=o.styleClasses,c=l.classes;c?o.styleClasses=c:u&&(o.styleClasses=null);for(var f=!a||a.length!=o.styles.length||u!=c&&(!u||!c||u.bgClass!=c.bgClass||u.textClass!=c.textClass),h=0;!f&&hr)return ai(t,t.options.workDelay),!0})),e.highlightFrontier=n.line,e.modeFrontier=Math.max(e.modeFrontier,n.line),i.length&&Zn(t,(function(){for(var e=0;e=r.viewFrom&&e.visible.to<=r.viewTo&&(null==r.updateLineNumbers||r.updateLineNumbers>=r.viewTo)&&r.renderedView==r.view&&0==oi(t))return !1;Ln(t)&&(ni(t),e.dims=an(t));var i=n.first+n.size,o=Math.max(e.visible.from-t.options.viewportMargin,n.first),a=Math.min(i,e.visible.to+t.options.viewportMargin);r.viewFroma&&r.viewTo-a<20&&(a=Math.min(i,r.viewTo)),kt&&(o=Bt(t.doc,o),a=Ut(t.doc,a));var s=o!=r.viewFrom||a!=r.viewTo||r.lastWrapHeight!=e.wrapperHeight||r.lastWrapWidth!=e.wrapperWidth;!function(t,e,r){var n=t.display;0==n.view.length||e>=n.viewTo||r<=n.viewFrom?(n.view=or(t,e,r),n.viewFrom=e):(n.viewFrom>e?n.view=or(t,e,n.viewFrom).concat(n.view):n.viewFromr&&(n.view=n.view.slice(0,fn(t,r)))),n.viewTo=r;}(t,o,a),r.viewOffset=Kt(st(t.doc,r.viewFrom)),t.display.mover.style.top=r.viewOffset+"px";var u=oi(t);if(!s&&0==u&&!e.force&&r.renderedView==r.view&&(null==r.updateLineNumbers||r.updateLineNumbers>=r.viewTo))return !1;var c=function(t){if(t.hasFocus())return null;var e=D();if(!e||!N(t.display.lineDiv,e))return null;var r={activeElt:e};if(window.getSelection){var n=window.getSelection();n.anchorNode&&n.extend&&N(t.display.lineDiv,n.anchorNode)&&(r.anchorNode=n.anchorNode,r.anchorOffset=n.anchorOffset,r.focusNode=n.focusNode,r.focusOffset=n.focusOffset);}return r}(t);return u>4&&(r.lineDiv.style.display="none"),function(t,e,r){var n=t.display,i=t.options.lineNumbers,o=n.lineDiv,a=o.firstChild;function s(e){var r=e.nextSibling;return l&&y&&t.display.currentWheelTarget==e?e.style.display="none":e.parentNode.removeChild(e),r}for(var u=n.view,c=n.viewFrom,f=0;f-1&&(d=!1),cr(t,h,c,r)),d&&(M(h.lineNumber),h.lineNumber.appendChild(document.createTextNode(pt(t.options,c)))),a=h.node.nextSibling;}else {var p=mr(t,h,c,r);o.insertBefore(p,a);}c+=h.size;}for(;a;)a=s(a);}(t,r.updateLineNumbers,e.dims),u>4&&(r.lineDiv.style.display=""),r.renderedView=r.view,function(t){if(t&&t.activeElt&&t.activeElt!=D()&&(t.activeElt.focus(),t.anchorNode&&N(document.body,t.anchorNode)&&N(document.body,t.focusNode))){var e=window.getSelection(),r=document.createRange();r.setEnd(t.anchorNode,t.anchorOffset),r.collapse(!1),e.removeAllRanges(),e.addRange(r),e.extend(t.focusNode,t.focusOffset);}}(c),M(r.cursorDiv),M(r.selectionDiv),r.gutters.style.height=r.sizer.style.minHeight=0,s&&(r.lastWrapHeight=e.wrapperHeight,r.lastWrapWidth=e.wrapperWidth,ai(t,400)),r.updateLineNumbers=null,!0}function ci(t,e){for(var r=e.viewport,n=!0;(n&&t.options.lineWrapping&&e.oldDisplayWidth!=Mr(t)||(r&&null!=r.top&&(r={top:Math.min(t.doc.height+Sr(t.display)-Tr(t),r.top)}),e.visible=Sn(t.display,t.doc,r),!(e.visible.from>=t.display.viewFrom&&e.visible.to<=t.display.viewTo)))&&ui(t,e);n=!1){Cn(t);var i=Rn(t);hn(t),In(t,i),di(t,i),e.force=!1;}e.signal(t,"update",t),t.display.viewFrom==t.display.reportedViewFrom&&t.display.viewTo==t.display.reportedViewTo||(e.signal(t,"viewportChange",t,t.display.viewFrom,t.display.viewTo),t.display.reportedViewFrom=t.display.viewFrom,t.display.reportedViewTo=t.display.viewTo);}function fi(t,e){var r=new li(t,e);if(ui(t,r)){Cn(t),ci(t,r);var n=Rn(t);hn(t),In(t,n),di(t,n),r.finish();}}function hi(t){var e=t.display.gutters.offsetWidth;t.display.sizer.style.marginLeft=e+"px";}function di(t,e){t.display.sizer.style.minHeight=e.docHeight+"px",t.display.heightForcer.style.top=e.docHeight+"px",t.display.gutters.style.height=e.docHeight+t.display.barHeight+Lr(t)+"px";}function pi(t){var e=t.display.gutters,r=t.options.gutters;M(e);for(var n=0;n-1&&!t.lineNumbers&&(t.gutters=t.gutters.slice(0),t.gutters.splice(e,1));}li.prototype.signal=function(t,e){ae(t,e)&&this.events.push(arguments);},li.prototype.finish=function(){for(var t=0;ts.clientWidth,c=s.scrollHeight>s.clientHeight;if(i&&u||o&&c){if(o&&y&&l)t:for(var h=e.target,d=a.view;h!=s;h=h.parentNode)for(var p=0;p=0&>(t,n.to())<=0)return r}return -1};var Ci=function(t,e){this.anchor=t,this.head=e;};function _i(t,e,r){var n=t&&t.options.selectionsMayTouch,i=e[r];e.sort((function(t,e){return gt(t.from(),e.from())})),r=z(e,i);for(var o=1;o0:l>=0){var u=wt(s.from(),a.from()),c=bt(s.to(),a.to()),f=s.empty()?a.from()==a.head:s.from()==s.head;o<=r&&--r,e.splice(--o,2,new Ci(f?c:u,f?u:c));}}return new xi(e,r)}function Si(t,e){return new xi([new Ci(t,e||t)],0)}function ki(t){return t.text?vt(t.from.line+t.text.length-1,$(t.text).length+(1==t.text.length?t.from.ch:0)):t.to}function Li(t,e){if(gt(t,e.from)<0)return t;if(gt(t,e.to)<=0)return ki(e);var r=t.line+e.text.length-(e.to.line-e.from.line)-1,n=t.ch;return t.line==e.to.line&&(n+=ki(e).ch-e.to.ch),vt(r,n)}function Mi(t,e){for(var r=[],n=0;n1&&t.remove(s.line+1,p-1),t.insert(s.line+1,m);}lr(t,"change",t,e);}function Wi(t,e,r){!function t(n,i,o){if(n.linked)for(var a=0;as-(t.cm?t.cm.options.historyEventDelay:500)||"*"==e.origin.charAt(0)))&&(o=function(t,e){return e?(Fi(t.done),$(t.done)):t.done.length&&!$(t.done).ranges?$(t.done):t.done.length>1&&!t.done[t.done.length-2].ranges?(t.done.pop(),$(t.done)):void 0}(i,i.lastOp==n)))a=$(o.changes),0==gt(e.from,e.to)&&0==gt(e.from,a.to)?a.to=ki(e):o.changes.push(Hi(t,e));else {var l=$(i.done);for(l&&l.ranges||ji(t.sel,i.done),o={changes:[Hi(t,e)],generation:i.generation},i.done.push(o);i.done.length>i.undoDepth;)i.done.shift(),i.done[0].ranges||i.done.shift();}i.done.push(r),i.generation=++i.maxGeneration,i.lastModTime=i.lastSelTime=s,i.lastOp=i.lastSelOp=n,i.lastOrigin=i.lastSelOrigin=e.origin,a||ne(t,"historyAdded");}function zi(t,e,r,n){var i=t.history,o=n&&n.origin;r==i.lastSelOp||o&&i.lastSelOrigin==o&&(i.lastModTime==i.lastSelTime&&i.lastOrigin==o||function(t,e,r,n){var i=e.charAt(0);return "*"==i||"+"==i&&r.ranges.length==n.ranges.length&&r.somethingSelected()==n.somethingSelected()&&new Date-t.history.lastSelTime<=(t.cm?t.cm.options.historyEventDelay:500)}(t,o,$(i.done),e))?i.done[i.done.length-1]=e:ji(e,i.done),i.lastSelTime=+new Date,i.lastSelOrigin=o,i.lastSelOp=r,n&&!1!==n.clearRedo&&Fi(i.undone);}function ji(t,e){var r=$(e);r&&r.ranges&&r.equals(t)||e.push(t);}function Bi(t,e,r,n){var i=e["spans_"+t.id],o=0;t.iter(Math.max(t.first,r),Math.min(t.first+t.size,n),(function(r){r.markedSpans&&((i||(i=e["spans_"+t.id]={}))[o]=r.markedSpans),++o;}));}function Ui(t){if(!t)return null;for(var e,r=0;r-1&&($(s)[f]=u[f],delete u[f]);}}}return n}function Ki(t,e,r,n){if(n){var i=t.anchor;if(r){var o=gt(e,i)<0;o!=gt(r,i)<0?(i=e,e=r):o!=gt(e,r)<0&&(e=r);}return new Ci(i,e)}return new Ci(r||e,e)}function qi(t,e,r,n,i){null==i&&(i=t.cm&&(t.cm.display.shift||t.extend)),Ji(t,new xi([Ki(t.sel.primary(),e,r,i)],0),n);}function $i(t,e,r){for(var n=[],i=t.cm&&(t.cm.display.shift||t.extend),o=0;o=e.ch:s.to>e.ch))){if(i&&(ne(l,"beforeCursorEnter"),l.explicitlyCleared)){if(o.markedSpans){--a;continue}break}if(!l.atomic)continue;if(r){var u=l.find(n<0?1:-1),c=void 0;if((n<0?l.inclusiveRight:l.inclusiveLeft)&&(u=oo(t,u,-n,u&&u.line==e.line?o:null)),u&&u.line==e.line&&(c=gt(u,r))&&(n<0?c<0:c>0))return no(t,u,e,n,i)}var f=l.find(n<0?-1:1);return (n<0?l.inclusiveLeft:l.inclusiveRight)&&(f=oo(t,f,n,f.line==e.line?o:null)),f?no(t,f,e,n,i):null}}return e}function io(t,e,r,n,i){var o=n||1,a=no(t,e,r,o,i)||!i&&no(t,e,r,o,!0)||no(t,e,r,-o,i)||!i&&no(t,e,r,-o,!0);return a||(t.cantEdit=!0,vt(t.first,0))}function oo(t,e,r,n){return r<0&&0==e.ch?e.line>t.first?Ct(t,vt(e.line-1)):null:r>0&&e.ch==(n||st(t,e.line)).text.length?e.line0)){var c=[l,1],f=gt(u.from,s.from),h=gt(u.to,s.to);(f<0||!a.inclusiveLeft&&!f)&&c.push({from:u.from,to:s.from}),(h>0||!a.inclusiveRight&&!h)&&c.push({from:s.to,to:u.to}),i.splice.apply(i,c),l+=c.length-3;}}return i}(t,e.from,e.to);if(n)for(var i=n.length-1;i>=0;--i)uo(t,{from:n[i].from,to:n[i].to,text:i?[""]:e.text,origin:e.origin});else uo(t,e);}}function uo(t,e){if(1!=e.text.length||""!=e.text[0]||0!=gt(e.from,e.to)){var r=Mi(t,e);Ii(t,e,r,t.cm?t.cm.curOp.id:NaN),ho(t,e,r,Ot(t,e));var n=[];Wi(t,(function(t,r){r||-1!=z(n,t.history)||(mo(t.history,e),n.push(t.history)),ho(t,e,null,Ot(t,e));}));}}function co(t,e,r){var n=t.cm&&t.cm.state.suppressEdits;if(!n||r){for(var i,o=t.history,a=t.sel,s="undo"==e?o.done:o.undone,l="undo"==e?o.undone:o.done,u=0;u=0;--d){var p=h(d);if(p)return p.v}}}}function fo(t,e){if(0!=e&&(t.first+=e,t.sel=new xi(X(t.sel.ranges,(function(t){return new Ci(vt(t.anchor.line+e,t.anchor.ch),vt(t.head.line+e,t.head.ch))})),t.sel.primIndex),t.cm)){ei(t.cm,t.first,t.first-e,e);for(var r=t.cm.display,n=r.viewFrom;nt.lastLine())){if(e.from.lineo&&(e={from:e.from,to:vt(o,st(t,o).text.length),text:[e.text[0]],origin:e.origin}),e.removed=lt(t,e.from,e.to),r||(r=Mi(t,e)),t.cm?function(t,e,r){var n=t.doc,i=t.display,o=e.from,a=e.to,s=!1,l=o.line;t.options.lineWrapping||(l=ft(jt(st(n,o.line))),n.iter(l,a.line+1,(function(t){if(t==i.maxLine)return s=!0,!0}))),n.sel.contains(e.from,e.to)>-1&&oe(t),Di(n,e,r,ln(t)),t.options.lineWrapping||(n.iter(l,o.line+e.text.length,(function(t){var e=qt(t);e>i.maxLineLength&&(i.maxLine=t,i.maxLineLength=e,i.maxLineChanged=!0,s=!1);})),s&&(t.curOp.updateMaxLine=!0)),function(t,e){if(t.modeFrontier=Math.min(t.modeFrontier,e),!(t.highlightFrontierr;n--){var i=st(t,n).stateAfter;if(i&&(!(i instanceof Pe)||n+i.lookAhead1||!(this.children[0]instanceof bo))){var s=[];this.collapse(s),this.children=[new bo(s)],this.children[0].parent=this;}},collapse:function(t){for(var e=0;e50){for(var a=i.lines.length%25+25,s=a;s10);t.parent.maybeSpill();}},iterN:function(t,e,r){for(var n=0;n0||0==a&&!1!==o.clearWhenEmpty)return o;if(o.replacedWith&&(o.collapsed=!0,o.widgetNode=A("span",[o.replacedWith],"CodeMirror-widget"),n.handleMouseEvents||o.widgetNode.setAttribute("cm-ignore-events","true"),n.insertLeft&&(o.widgetNode.insertLeft=!0)),o.collapsed){if(zt(t,e.line,e,r,o)||e.line!=r.line&&zt(t,r.line,e,r,o))throw new Error("Inserting collapsed marker partially overlapping an existing one");kt=!0;}o.addToHistory&&Ii(t,{from:e,to:r,origin:"markText"},t.sel,NaN);var s,l=e.line,u=t.cm;if(t.iter(l,r.line+1,(function(t){u&&o.collapsed&&!u.options.lineWrapping&&jt(t)==u.display.maxLine&&(s=!0),o.collapsed&&l!=e.line&&ct(t,0),function(t,e){t.markedSpans=t.markedSpans?t.markedSpans.concat([e]):[e],e.marker.attachLine(t);}(t,new Lt(o,l==e.line?e.ch:null,l==r.line?r.ch:null)),++l;})),o.collapsed&&t.iter(e.line,r.line+1,(function(e){Vt(t,e)&&ct(e,0);})),o.clearOnEnter&&te(o,"beforeCursorEnter",(function(){return o.clear()})),o.readOnly&&(St=!0,(t.history.done.length||t.history.undone.length)&&t.clearHistory()),o.collapsed&&(o.id=++_o,o.atomic=!0),u){if(s&&(u.curOp.updateMaxLine=!0),o.collapsed)ei(u,e.line,r.line+1);else if(o.className||o.startStyle||o.endStyle||o.css||o.attributes||o.title)for(var c=e.line;c<=r.line;c++)ri(u,c,"text");o.atomic&&eo(u.doc),lr(u,"markerAdded",u,o);}return o}So.prototype.clear=function(){if(!this.explicitlyCleared){var t=this.doc.cm,e=t&&!t.curOp;if(e&&Vn(t),ae(this,"clear")){var r=this.find();r&&lr(this,"clear",r.from,r.to);}for(var n=null,i=null,o=0;ot.display.maxLineLength&&(t.display.maxLine=u,t.display.maxLineLength=c,t.display.maxLineChanged=!0);}null!=n&&t&&this.collapsed&&ei(t,n,i+1),this.lines.length=0,this.explicitlyCleared=!0,this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,t&&eo(t.doc)),t&&lr(t,"markerCleared",t,this,n,i),e&&Gn(t),this.parent&&this.parent.clear();}},So.prototype.find=function(t,e){var r,n;null==t&&"bookmark"==this.type&&(t=1);for(var i=0;i=0;l--)lo(this,n[l]);s?Zi(this,s):this.cm&&On(this.cm);})),undo:ti((function(){co(this,"undo");})),redo:ti((function(){co(this,"redo");})),undoSelection:ti((function(){co(this,"undo",!0);})),redoSelection:ti((function(){co(this,"redo",!0);})),setExtending:function(t){this.extend=t;},getExtending:function(){return this.extend},historySize:function(){for(var t=this.history,e=0,r=0,n=0;n=t.ch)&&e.push(i.marker.parent||i.marker);}return e},findMarks:function(t,e,r){t=Ct(this,t),e=Ct(this,e);var n=[],i=t.line;return this.iter(t.line,e.line+1,(function(o){var a=o.markedSpans;if(a)for(var s=0;s=l.to||null==l.from&&i!=t.line||null!=l.from&&i==e.line&&l.from>=e.ch||r&&!r(l.marker)||n.push(l.marker.parent||l.marker);}++i;})),n},getAllMarks:function(){var t=[];return this.iter((function(e){var r=e.markedSpans;if(r)for(var n=0;nt)return e=t,!0;t-=o,++r;})),Ct(this,vt(r,e))},indexFromPos:function(t){var e=(t=Ct(this,t)).ch;if(t.linee&&(e=t.from),null!=t.to&&t.to-1)return e.state.draggingText(t),void setTimeout((function(){return e.display.input.focus()}),20);try{var c=t.dataTransfer.getData("Text");if(c){var f;if(e.state.draggingText&&!e.state.draggingText.copy&&(f=e.listSelections()),Qi(e.doc,Si(r,r)),f)for(var h=0;h=0;e--)po(t.doc,"",n[e].from,n[e].to,"+delete");On(t);}));}function Zo(t,e,r){var n=it(t.text,e+r,r);return n<0||n>t.text.length?null:n}function Jo(t,e,r){var n=Zo(t,e.ch,r);return null==n?null:new vt(e.line,n,r<0?"after":"before")}function Qo(t,e,r,n,i){if(t){var o=Jt(r,e.doc.direction);if(o){var a,s=i<0?$(o):o[0],l=i<0==(1==s.level)?"after":"before";if(s.level>0||"rtl"==e.doc.direction){var u=Dr(e,r);a=i<0?r.text.length-1:0;var c=Wr(e,u,a).top;a=ot((function(t){return Wr(e,u,t).top==c}),i<0==(1==s.level)?s.from:s.to-1,a),"before"==l&&(a=Zo(r,a,1));}else a=i<0?s.to:s.from;return new vt(n,a,l)}}return new vt(n,i<0?r.text.length:0,i<0?"before":"after")}Bo.basic={Left:"goCharLeft",Right:"goCharRight",Up:"goLineUp",Down:"goLineDown",End:"goLineEnd",Home:"goLineStartSmart",PageUp:"goPageUp",PageDown:"goPageDown",Delete:"delCharAfter",Backspace:"delCharBefore","Shift-Backspace":"delCharBefore",Tab:"defaultTab","Shift-Tab":"indentAuto",Enter:"newlineAndIndent",Insert:"toggleOverwrite",Esc:"singleSelection"},Bo.pcDefault={"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Up":"goLineUp","Ctrl-Down":"goLineDown","Ctrl-Left":"goGroupLeft","Ctrl-Right":"goGroupRight","Alt-Left":"goLineStart","Alt-Right":"goLineEnd","Ctrl-Backspace":"delGroupBefore","Ctrl-Delete":"delGroupAfter","Ctrl-S":"save","Ctrl-F":"find","Ctrl-G":"findNext","Shift-Ctrl-G":"findPrev","Shift-Ctrl-F":"replace","Shift-Ctrl-R":"replaceAll","Ctrl-[":"indentLess","Ctrl-]":"indentMore","Ctrl-U":"undoSelection","Shift-Ctrl-U":"redoSelection","Alt-U":"redoSelection",fallthrough:"basic"},Bo.emacsy={"Ctrl-F":"goCharRight","Ctrl-B":"goCharLeft","Ctrl-P":"goLineUp","Ctrl-N":"goLineDown","Alt-F":"goWordRight","Alt-B":"goWordLeft","Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd","Ctrl-V":"goPageDown","Shift-Ctrl-V":"goPageUp","Ctrl-D":"delCharAfter","Ctrl-H":"delCharBefore","Alt-D":"delWordAfter","Alt-Backspace":"delWordBefore","Ctrl-K":"killLine","Ctrl-T":"transposeChars","Ctrl-O":"openLine"},Bo.macDefault={"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Home":"goDocStart","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineLeft","Cmd-Right":"goLineRight","Alt-Backspace":"delGroupBefore","Ctrl-Alt-Backspace":"delGroupAfter","Alt-Delete":"delGroupAfter","Cmd-S":"save","Cmd-F":"find","Cmd-G":"findNext","Shift-Cmd-G":"findPrev","Cmd-Alt-F":"replace","Shift-Cmd-Alt-F":"replaceAll","Cmd-[":"indentLess","Cmd-]":"indentMore","Cmd-Backspace":"delWrappedLineLeft","Cmd-Delete":"delWrappedLineRight","Cmd-U":"undoSelection","Shift-Cmd-U":"redoSelection","Ctrl-Up":"goDocStart","Ctrl-Down":"goDocEnd",fallthrough:["basic","emacsy"]},Bo.default=y?Bo.macDefault:Bo.pcDefault;var ta={selectAll:ao,singleSelection:function(t){return t.setSelection(t.getCursor("anchor"),t.getCursor("head"),B)},killLine:function(t){return Yo(t,(function(e){if(e.empty()){var r=st(t.doc,e.head.line).text.length;return e.head.ch==r&&e.head.line0)i=new vt(i.line,i.ch+1),t.replaceRange(o.charAt(i.ch-1)+o.charAt(i.ch-2),vt(i.line,i.ch-2),i,"+transpose");else if(i.line>t.doc.first){var a=st(t.doc,i.line-1).text;a&&(i=new vt(i.line,1),t.replaceRange(o.charAt(0)+t.doc.lineSeparator()+a.charAt(a.length-1),vt(i.line-1,a.length-1),i,"+transpose"));}r.push(new Ci(i,i));}t.setSelections(r);}))},newlineAndIndent:function(t){return Zn(t,(function(){for(var e=t.listSelections(),r=e.length-1;r>=0;r--)t.replaceRange(t.doc.lineSeparator(),e[r].anchor,e[r].head,"+input");e=t.listSelections();for(var n=0;n-1&&(gt((i=u.ranges[i]).from(),e)<0||e.xRel>0)&&(gt(i.to(),e)>0||e.xRel<0)?function(t,e,r,n){var i=t.display,o=!1,u=Jn(t,(function(e){l&&(i.scroller.draggable=!1),t.state.draggingText=!1,re(i.wrapper.ownerDocument,"mouseup",u),re(i.wrapper.ownerDocument,"mousemove",c),re(i.scroller,"dragstart",f),re(i.scroller,"drop",u),o||(le(e),n.addNew||qi(t.doc,r,null,null,n.extend),l||a&&9==s?setTimeout((function(){i.wrapper.ownerDocument.body.focus(),i.input.focus();}),20):i.input.focus());})),c=function(t){o=o||Math.abs(e.clientX-t.clientX)+Math.abs(e.clientY-t.clientY)>=10;},f=function(){return o=!0};l&&(i.scroller.draggable=!0),t.state.draggingText=u,u.copy=!n.moveOnDrag,i.scroller.dragDrop&&i.scroller.dragDrop(),te(i.wrapper.ownerDocument,"mouseup",u),te(i.wrapper.ownerDocument,"mousemove",c),te(i.scroller,"dragstart",f),te(i.scroller,"drop",u),bn(t),setTimeout((function(){return i.input.focus()}),20);}(t,n,e,o):function(t,e,r,n){var i=t.display,o=t.doc;le(e);var a,s,l=o.sel,u=l.ranges;if(n.addNew&&!n.extend?(s=o.sel.contains(r),a=s>-1?u[s]:new Ci(r,r)):(a=o.sel.primary(),s=o.sel.primIndex),"rectangle"==n.unit)n.addNew||(a=new Ci(r,r)),r=cn(t,e,!0,!0),s=-1;else {var c=ga(t,r,n.unit);a=n.extend?Ki(a,c.anchor,c.head,n.extend):c;}n.addNew?-1==s?(s=u.length,Ji(o,_i(t,u.concat([a]),s),{scroll:!1,origin:"*mouse"})):u.length>1&&u[s].empty()&&"char"==n.unit&&!n.extend?(Ji(o,_i(t,u.slice(0,s).concat(u.slice(s+1)),0),{scroll:!1,origin:"*mouse"}),l=o.sel):Xi(o,s,a,U):(s=0,Ji(o,new xi([a],0),U),l=o.sel);var f=r;function h(e){if(0!=gt(f,e))if(f=e,"rectangle"==n.unit){for(var i=[],u=t.options.tabSize,c=F(st(o,r.line).text,r.ch,u),h=F(st(o,e.line).text,e.ch,u),d=Math.min(c,h),p=Math.max(c,h),v=Math.min(r.line,e.line),g=Math.min(t.lastLine(),Math.max(r.line,e.line));v<=g;v++){var m=st(o,v).text,y=G(m,d,u);d==p?i.push(new Ci(vt(v,y),vt(v,y))):m.length>y&&i.push(new Ci(vt(v,y),vt(v,G(m,p,u))));}i.length||i.push(new Ci(r,r)),Ji(o,_i(t,l.ranges.slice(0,s).concat(i),s),{origin:"*mouse",scroll:!1}),t.scrollIntoView(e);}else {var b,w=a,x=ga(t,e,n.unit),C=w.anchor;gt(x.anchor,C)>0?(b=x.head,C=wt(w.from(),x.anchor)):(b=x.anchor,C=bt(w.to(),x.head));var _=l.ranges.slice(0);_[s]=function(t,e){var r=e.anchor,n=e.head,i=st(t.doc,r.line);if(0==gt(r,n)&&r.sticky==n.sticky)return e;var o=Jt(i);if(!o)return e;var a=Yt(o,r.ch,r.sticky),s=o[a];if(s.from!=r.ch&&s.to!=r.ch)return e;var l,u=a+(s.from==r.ch==(1!=s.level)?0:1);if(0==u||u==o.length)return e;if(n.line!=r.line)l=(n.line-r.line)*("ltr"==t.doc.direction?1:-1)>0;else {var c=Yt(o,n.ch,n.sticky),f=c-a||(n.ch-r.ch)*(1==s.level?-1:1);l=c==u-1||c==u?f<0:f>0;}var h=o[u+(l?-1:0)],d=l==(1==h.level),p=d?h.from:h.to,v=d?"after":"before";return r.ch==p&&r.sticky==v?e:new Ci(new vt(r.line,p,v),n)}(t,new Ci(Ct(o,C),b)),Ji(o,_i(t,_,s),U);}}var d=i.wrapper.getBoundingClientRect(),p=0;function v(e){t.state.selectingText=!1,p=1/0,le(e),i.input.focus(),re(i.wrapper.ownerDocument,"mousemove",g),re(i.wrapper.ownerDocument,"mouseup",m),o.history.lastSelOrigin=null;}var g=Jn(t,(function(e){0!==e.buttons&&de(e)?function e(r){var a=++p,s=cn(t,r,!0,"rectangle"==n.unit);if(s)if(0!=gt(s,f)){t.curOp.focus=D(),h(s);var l=Sn(i,o);(s.line>=l.to||s.lined.bottom?20:0;u&&setTimeout(Jn(t,(function(){p==a&&(i.scroller.scrollTop+=u,e(r));})),50);}}(e):v(e);})),m=Jn(t,v);t.state.selectingText=m,te(i.wrapper.ownerDocument,"mousemove",g),te(i.wrapper.ownerDocument,"mouseup",m);}(t,n,e,o);}(e,n,o,t):he(t)==r.scroller&&le(t):2==i?(n&&qi(e.doc,n),setTimeout((function(){return r.input.focus()}),20)):3==i&&(_?e.display.input.onContextMenu(t):bn(e)));}}function ga(t,e,r){if("char"==r)return new Ci(e,e);if("word"==r)return t.findWordAt(e);if("line"==r)return new Ci(vt(e.line,0),Ct(t.doc,vt(e.line+1,0)));var n=r(t,e);return new Ci(n.from,n.to)}function ma(t,e,r,n){var i,o;if(e.touches)i=e.touches[0].clientX,o=e.touches[0].clientY;else try{i=e.clientX,o=e.clientY;}catch(e){return !1}if(i>=Math.floor(t.display.gutters.getBoundingClientRect().right))return !1;n&&le(e);var a=t.display,s=a.lineDiv.getBoundingClientRect();if(o>s.bottom||!ae(t,r))return ce(e);o-=s.top-a.viewOffset;for(var l=0;l=i)return ne(t,r,t,ht(t.doc,o),t.options.gutters[l],e),ce(e)}}function ya(t,e){return ma(t,e,"gutterClick",!0)}function ba(t,e){Cr(t.display,e)||function(t,e){return !!ae(t,"gutterContextMenu")&&ma(t,e,"gutterContextMenu",!1)}(t,e)||ie(t,e,"contextmenu")||_||t.display.input.onContextMenu(e);}function wa(t){t.display.wrapper.className=t.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+t.options.theme.replace(/(^|\s)\s*/g," cm-s-"),zr(t);}pa.prototype.compare=function(t,e,r){return this.time+400>t&&0==gt(e,this.pos)&&r==this.button};var xa={toString:function(){return "CodeMirror.Init"}},Ca={},_a={};function Sa(t){pi(t),ei(t),kn(t);}function ka(t,e,r){if(!e!=!(r&&r!=xa)){var n=t.display.dragFunctions,i=e?te:re;i(t.display.scroller,"dragstart",n.start),i(t.display.scroller,"dragenter",n.enter),i(t.display.scroller,"dragover",n.over),i(t.display.scroller,"dragleave",n.leave),i(t.display.scroller,"drop",n.drop);}}function La(t){t.options.lineWrapping?(W(t.display.wrapper,"CodeMirror-wrap"),t.display.sizer.style.minWidth="",t.display.sizerWidth=null):(L(t.display.wrapper,"CodeMirror-wrap"),$t(t)),un(t),ei(t),zr(t),setTimeout((function(){return In(t)}),100);}function Ma(t,e){var r=this;if(!(this instanceof Ma))return new Ma(t,e);this.options=e=e?H(e):{},H(Ca,e,!1),vi(e);var n=e.value;"string"==typeof n?n=new Ao(n,e.mode,null,e.lineSeparator,e.direction):e.mode&&(n.modeOption=e.mode),this.doc=n;var i=new Ma.inputStyles[e.inputStyle](this),o=this.display=new at(t,n,i);for(var u in o.wrapper.CodeMirror=this,pi(this),wa(this),e.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap"),Bn(this),this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,delayingBlurEvent:!1,focused:!1,suppressEdits:!1,pasteIncoming:!1,cutIncoming:!1,selectingText:!1,draggingText:!1,highlight:new I,keySeq:null,specialChars:null},e.autofocus&&!m&&o.input.focus(),a&&s<11&&setTimeout((function(){return r.display.input.reset(!0)}),20),function(t){var e=t.display;te(e.scroller,"mousedown",Jn(t,va)),te(e.scroller,"dblclick",a&&s<11?Jn(t,(function(e){if(!ie(t,e)){var r=cn(t,e);if(r&&!ya(t,e)&&!Cr(t.display,e)){le(e);var n=t.findWordAt(r);qi(t.doc,n.anchor,n.head);}}})):function(e){return ie(t,e)||le(e)}),te(e.scroller,"contextmenu",(function(e){return ba(t,e)}));var r,n={end:0};function i(){e.activeTouch&&(r=setTimeout((function(){return e.activeTouch=null}),1e3),(n=e.activeTouch).end=+new Date);}function o(t,e){if(null==e.left)return !0;var r=e.left-t.left,n=e.top-t.top;return r*r+n*n>400}te(e.scroller,"touchstart",(function(i){if(!ie(t,i)&&!function(t){if(1!=t.touches.length)return !1;var e=t.touches[0];return e.radiusX<=1&&e.radiusY<=1}(i)&&!ya(t,i)){e.input.ensurePolled(),clearTimeout(r);var o=+new Date;e.activeTouch={start:o,moved:!1,prev:o-n.end<=300?n:null},1==i.touches.length&&(e.activeTouch.left=i.touches[0].pageX,e.activeTouch.top=i.touches[0].pageY);}})),te(e.scroller,"touchmove",(function(){e.activeTouch&&(e.activeTouch.moved=!0);})),te(e.scroller,"touchend",(function(r){var n=e.activeTouch;if(n&&!Cr(e,r)&&null!=n.left&&!n.moved&&new Date-n.start<300){var a,s=t.coordsChar(e.activeTouch,"page");a=!n.prev||o(n,n.prev)?new Ci(s,s):!n.prev.prev||o(n,n.prev.prev)?t.findWordAt(s):new Ci(vt(s.line,0),Ct(t.doc,vt(s.line+1,0))),t.setSelection(a.anchor,a.head),t.focus(),le(r);}i();})),te(e.scroller,"touchcancel",i),te(e.scroller,"scroll",(function(){e.scroller.clientHeight&&(Wn(t,e.scroller.scrollTop),Pn(t,e.scroller.scrollLeft,!0),ne(t,"scroll",t));})),te(e.scroller,"mousewheel",(function(e){return wi(t,e)})),te(e.scroller,"DOMMouseScroll",(function(e){return wi(t,e)})),te(e.wrapper,"scroll",(function(){return e.wrapper.scrollTop=e.wrapper.scrollLeft=0})),e.dragFunctions={enter:function(e){ie(t,e)||fe(e);},over:function(e){ie(t,e)||(function(t,e){var r=cn(t,e);if(r){var n=document.createDocumentFragment();pn(t,r,n),t.display.dragCursor||(t.display.dragCursor=O("div",null,"CodeMirror-cursors CodeMirror-dragcursors"),t.display.lineSpace.insertBefore(t.display.dragCursor,t.display.cursorDiv)),T(t.display.dragCursor,n);}}(t,e),fe(e));},start:function(e){return function(t,e){if(a&&(!t.state.draggingText||+new Date-No<100))fe(e);else if(!ie(t,e)&&!Cr(t.display,e)&&(e.dataTransfer.setData("Text",t.getSelection()),e.dataTransfer.effectAllowed="copyMove",e.dataTransfer.setDragImage&&!h)){var r=O("img",null,null,"position: fixed; left: 0; top: 0;");r.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",f&&(r.width=r.height=1,t.display.wrapper.appendChild(r),r._top=r.offsetTop),e.dataTransfer.setDragImage(r,0,0),f&&r.parentNode.removeChild(r);}}(t,e)},drop:Jn(t,Do),leave:function(e){ie(t,e)||Wo(t);}};var l=e.input.getField();te(l,"keyup",(function(e){return ca.call(t,e)})),te(l,"keydown",Jn(t,ua)),te(l,"keypress",Jn(t,fa)),te(l,"focus",(function(e){return wn(t,e)})),te(l,"blur",(function(e){return xn(t,e)}));}(this),Ro(),Vn(this),this.curOp.forceUpdate=!0,Ei(this,n),e.autofocus&&!m||this.hasFocus()?setTimeout(R(wn,this),20):xn(this),_a)_a.hasOwnProperty(u)&&_a[u](r,e[u],xa);Ln(this),e.finishInit&&e.finishInit(this);for(var c=0;c150)){if(!n)return;r="prev";}}else u=0,r="not";"prev"==r?u=e>o.first?F(st(o,e-1).text,null,a):0:"add"==r?u=l+t.options.indentUnit:"subtract"==r?u=l-t.options.indentUnit:"number"==typeof r&&(u=l+r),u=Math.max(0,u);var f="",h=0;if(t.options.indentWithTabs)for(var d=Math.floor(u/a);d;--d)h+=a,f+="\t";if(h1)if(Aa&&Aa.text.join("\n")==e){if(n.ranges.length%Aa.text.length==0){u=[];for(var c=0;c=0;f--){var h=n.ranges[f],d=h.from(),p=h.to();h.empty()&&(r&&r>0?d=vt(d.line,d.ch-r):t.state.overwrite&&!s?p=vt(p.line,Math.min(st(o,p.line).text.length,p.ch+$(l).length)):s&&Aa&&Aa.lineWise&&Aa.text.join("\n")==e&&(d=p=vt(d.line,0))),a=t.curOp.updateInput;var v={from:d,to:p,text:u?u[f%u.length]:l,origin:i||(s?"paste":t.state.cutIncoming?"cut":"+input")};lo(t.doc,v),lr(t,"inputRead",t,v);}e&&!s&&Ea(t,e),On(t),t.curOp.updateInput=a,t.curOp.typing=!0,t.state.pasteIncoming=t.state.cutIncoming=!1;}function Wa(t,e){var r=t.clipboardData&&t.clipboardData.getData("Text");if(r)return t.preventDefault(),e.isReadOnly()||e.options.disableInput||Zn(e,(function(){return Da(e,r,0,null,"paste")})),!0}function Ea(t,e){if(t.options.electricChars&&t.options.smartIndent)for(var r=t.doc.sel,n=r.ranges.length-1;n>=0;n--){var i=r.ranges[n];if(!(i.head.ch>100||n&&r.ranges[n-1].head.line==i.head.line)){var o=t.getModeAt(i.head),a=!1;if(o.electricChars){for(var s=0;s-1){a=Oa(t,i.head.line,"smart");break}}else o.electricInput&&o.electricInput.test(st(t.doc,i.head.line).text.slice(0,i.head.ch))&&(a=Oa(t,i.head.line,"smart"));a&&lr(t,"electricInput",t,i.head.line);}}}function Pa(t){for(var e=[],r=[],n=0;n=e.text.length?(r.ch=e.text.length,r.sticky="before"):r.ch<=0&&(r.ch=0,r.sticky="after");var o=Yt(i,r.ch,r.sticky),a=i[o];if("ltr"==t.doc.direction&&a.level%2==0&&(n>0?a.to>r.ch:a.from=a.from&&h>=c.begin)){var d=f?"before":"after";return new vt(r.line,h,d)}}var p=function(t,e,n){for(var o=function(t,e){return e?new vt(r.line,l(t,1),"before"):new vt(r.line,t,"after")};t>=0&&t0==(1!=a.level),u=s?n.begin:l(n.end,-1);if(a.from<=u&&u0?c.end:l(c.begin,-1);return null==g||n>0&&g==e.text.length||!(v=p(n>0?0:i.length-1,n,u(g)))?null:v}(t.cm,s,e,r):Jo(s,e,r))){if(n||(a=e.line+r)=t.first+t.size||(e=new vt(a,e.ch,e.sticky),!(s=st(t,a))))return !1;e=Qo(i,t.cm,s,e.line,r);}else e=o;return !0}if("char"==n)l();else if("column"==n)l(!0);else if("word"==n||"group"==n)for(var u=null,c="group"==n,f=t.cm&&t.cm.getHelper(e,"wordChars"),h=!0;!(r<0)||l(!h);h=!1){var d=s.text.charAt(e.ch)||"\n",p=tt(d,f)?"w":c&&"\n"==d?"n":!c||/\s/.test(d)?null:"p";if(!c||h||p||(p="s"),u&&u!=p){r<0&&(r=1,l(),e.sticky="after");break}if(p&&(u=p),r>0&&!l(!h))break}var v=io(t,e,o,a,!0);return mt(o,v)&&(v.hitSide=!0),v}function Ia(t,e,r,n){var i,o,a=t.doc,s=e.left;if("page"==n){var l=Math.min(t.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight),u=Math.max(l-.5*nn(t.display),3);i=(r>0?e.bottom:e.top)+r*u;}else "line"==n&&(i=r>0?e.bottom+3:e.top-3);for(;(o=Yr(t,s,i)).outside;){if(r<0?i<=0:i>=a.height){o.hitSide=!0;break}i+=5*r;}return o}var za=function(t){this.cm=t,this.lastAnchorNode=this.lastAnchorOffset=this.lastFocusNode=this.lastFocusOffset=null,this.polling=new I,this.composing=null,this.gracePeriod=!1,this.readDOMTimeout=null;};function ja(t,e){var r=Nr(t,e.line);if(!r||r.hidden)return null;var n=st(t.doc,e.line),i=Or(r,n,e.line),o=Jt(n,t.doc.direction),a="left";o&&(a=Yt(o,e.ch)%2?"right":"left");var s=Rr(i.map,e.ch,a);return s.offset="right"==s.collapse?s.end:s.start,s}function Ba(t,e){return e&&(t.bad=!0),t}function Ua(t,e,r){var n;if(e==t.display.lineDiv){if(!(n=t.display.lineDiv.childNodes[r]))return Ba(t.clipPos(vt(t.display.viewTo-1)),!0);e=null,r=0;}else for(n=e;;n=n.parentNode){if(!n||n==t.display.lineDiv)return null;if(n.parentNode&&n.parentNode==t.display.lineDiv)break}for(var i=0;i=e.display.viewTo||o.line=e.display.viewFrom&&ja(e,i)||{node:l[0].measure.map[2],offset:0},c=o.linen.firstLine()&&(a=vt(a.line-1,st(n.doc,a.line-1).length)),s.ch==st(n.doc,s.line).text.length&&s.linei.viewTo-1)return !1;a.line==i.viewFrom||0==(t=fn(n,a.line))?(e=ft(i.view[0].line),r=i.view[0].node):(e=ft(i.view[t].line),r=i.view[t-1].node.nextSibling);var l,u,c=fn(n,s.line);if(c==i.view.length-1?(l=i.viewTo-1,u=i.lineDiv.lastChild):(l=ft(i.view[c+1].line)-1,u=i.view[c+1].node.previousSibling),!r)return !1;for(var f=n.doc.splitLines(function(t,e,r,n,i){var o="",a=!1,s=t.doc.lineSeparator(),l=!1;function u(){a&&(o+=s,l&&(o+=s),a=l=!1);}function c(t){t&&(u(),o+=t);}function f(e){if(1==e.nodeType){var r=e.getAttribute("cm-text");if(r)return void c(r);var o,h=e.getAttribute("cm-marker");if(h){var d=t.findMarks(vt(n,0),vt(i+1,0),(g=+h,function(t){return t.id==g}));return void(d.length&&(o=d[0].find(0))&&c(lt(t.doc,o.from,o.to).join(s)))}if("false"==e.getAttribute("contenteditable"))return;var p=/^(pre|div|p|li|table|br)$/i.test(e.nodeName);if(!/^br$/i.test(e.nodeName)&&0==e.textContent.length)return;p&&u();for(var v=0;v1&&h.length>1;)if($(f)==$(h))f.pop(),h.pop(),l--;else {if(f[0]!=h[0])break;f.shift(),h.shift(),e++;}for(var d=0,p=0,v=f[0],g=h[0],m=Math.min(v.length,g.length);da.ch&&y.charCodeAt(y.length-p-1)==b.charCodeAt(b.length-p-1);)d--,p++;f[f.length-1]=y.slice(0,y.length-p).replace(/^\u200b+/,""),f[0]=f[0].slice(d).replace(/\u200b+$/,"");var x=vt(e,d),C=vt(l,h.length?$(h).length-p:0);return f.length>1||f[0]||gt(x,C)?(po(n.doc,f,x,C,"+input"),!0):void 0},za.prototype.ensurePolled=function(){this.forceCompositionEnd();},za.prototype.reset=function(){this.forceCompositionEnd();},za.prototype.forceCompositionEnd=function(){this.composing&&(clearTimeout(this.readDOMTimeout),this.composing=null,this.updateFromDOM(),this.div.blur(),this.div.focus());},za.prototype.readFromDOMSoon=function(){var t=this;null==this.readDOMTimeout&&(this.readDOMTimeout=setTimeout((function(){if(t.readDOMTimeout=null,t.composing){if(!t.composing.done)return;t.composing=null;}t.updateFromDOM();}),80));},za.prototype.updateFromDOM=function(){var t=this;!this.cm.isReadOnly()&&this.pollContent()||Zn(this.cm,(function(){return ei(t.cm)}));},za.prototype.setUneditable=function(t){t.contentEditable="false";},za.prototype.onKeyPress=function(t){0==t.charCode||this.composing||(t.preventDefault(),this.cm.isReadOnly()||Jn(this.cm,Da)(this.cm,String.fromCharCode(null==t.charCode?t.keyCode:t.charCode),0));},za.prototype.readOnlyChanged=function(t){this.div.contentEditable=String("nocursor"!=t);},za.prototype.onContextMenu=function(){},za.prototype.resetPosition=function(){},za.prototype.needsContentAttribute=!0;var Ga=function(t){this.cm=t,this.prevInput="",this.pollingFast=!1,this.polling=new I,this.hasSelection=!1,this.composing=null;};Ga.prototype.init=function(t){var e=this,r=this,n=this.cm;this.createField(t);var i=this.textarea;function o(t){if(!ie(n,t)){if(n.somethingSelected())Na({lineWise:!1,text:n.getSelections()});else {if(!n.options.lineWiseCopyCut)return;var e=Pa(n);Na({lineWise:!0,text:e.text}),"cut"==t.type?n.setSelections(e.ranges,null,B):(r.prevInput="",i.value=e.text.join("\n"),P(i));}"cut"==t.type&&(n.state.cutIncoming=!0);}}t.wrapper.insertBefore(this.wrapper,t.wrapper.firstChild),v&&(i.style.width="0px"),te(i,"input",(function(){a&&s>=9&&e.hasSelection&&(e.hasSelection=null),r.poll();})),te(i,"paste",(function(t){ie(n,t)||Wa(t,n)||(n.state.pasteIncoming=!0,r.fastPoll());})),te(i,"cut",o),te(i,"copy",o),te(t.scroller,"paste",(function(e){Cr(t,e)||ie(n,e)||(n.state.pasteIncoming=!0,r.focus());})),te(t.lineSpace,"selectstart",(function(e){Cr(t,e)||le(e);})),te(i,"compositionstart",(function(){var t=n.getCursor("from");r.composing&&r.composing.range.clear(),r.composing={start:t,range:n.markText(t,n.getCursor("to"),{className:"CodeMirror-composing"})};})),te(i,"compositionend",(function(){r.composing&&(r.poll(),r.composing.range.clear(),r.composing=null);}));},Ga.prototype.createField=function(t){this.wrapper=Ha(),this.textarea=this.wrapper.firstChild;},Ga.prototype.prepareSelection=function(){var t=this.cm,e=t.display,r=t.doc,n=dn(t);if(t.options.moveInputWithCursor){var i=qr(t,r.sel.primary().head,"div"),o=e.wrapper.getBoundingClientRect(),a=e.lineDiv.getBoundingClientRect();n.teTop=Math.max(0,Math.min(e.wrapper.clientHeight-10,i.top+a.top-o.top)),n.teLeft=Math.max(0,Math.min(e.wrapper.clientWidth-10,i.left+a.left-o.left));}return n},Ga.prototype.showSelection=function(t){var e=this.cm.display;T(e.cursorDiv,t.cursors),T(e.selectionDiv,t.selection),null!=t.teTop&&(this.wrapper.style.top=t.teTop+"px",this.wrapper.style.left=t.teLeft+"px");},Ga.prototype.reset=function(t){if(!this.contextMenuPending&&!this.composing){var e=this.cm;if(e.somethingSelected()){this.prevInput="";var r=e.getSelection();this.textarea.value=r,e.state.focused&&P(this.textarea),a&&s>=9&&(this.hasSelection=r);}else t||(this.prevInput=this.textarea.value="",a&&s>=9&&(this.hasSelection=null));}},Ga.prototype.getField=function(){return this.textarea},Ga.prototype.supportsTouch=function(){return !1},Ga.prototype.focus=function(){if("nocursor"!=this.cm.options.readOnly&&(!m||D()!=this.textarea))try{this.textarea.focus();}catch(t){}},Ga.prototype.blur=function(){this.textarea.blur();},Ga.prototype.resetPosition=function(){this.wrapper.style.top=this.wrapper.style.left=0;},Ga.prototype.receivedFocus=function(){this.slowPoll();},Ga.prototype.slowPoll=function(){var t=this;this.pollingFast||this.polling.set(this.cm.options.pollInterval,(function(){t.poll(),t.cm.state.focused&&t.slowPoll();}));},Ga.prototype.fastPoll=function(){var t=!1,e=this;e.pollingFast=!0,e.polling.set(20,(function r(){e.poll()||t?(e.pollingFast=!1,e.slowPoll()):(t=!0,e.polling.set(60,r));}));},Ga.prototype.poll=function(){var t=this,e=this.cm,r=this.textarea,n=this.prevInput;if(this.contextMenuPending||!e.state.focused||xe(r)&&!n&&!this.composing||e.isReadOnly()||e.options.disableInput||e.state.keySeq)return !1;var i=r.value;if(i==n&&!e.somethingSelected())return !1;if(a&&s>=9&&this.hasSelection===i||y&&/[\uf700-\uf7ff]/.test(i))return e.display.input.reset(),!1;if(e.doc.sel==e.display.selForContextMenu){var o=i.charCodeAt(0);if(8203!=o||n||(n="​"),8666==o)return this.reset(),this.cm.execCommand("undo")}for(var l=0,u=Math.min(n.length,i.length);l1e3||i.indexOf("\n")>-1?r.value=t.prevInput="":t.prevInput=i,t.composing&&(t.composing.range.clear(),t.composing.range=e.markText(t.composing.start,e.getCursor("to"),{className:"CodeMirror-composing"}));})),!0},Ga.prototype.ensurePolled=function(){this.pollingFast&&this.poll()&&(this.pollingFast=!1);},Ga.prototype.onKeyPress=function(){a&&s>=9&&(this.hasSelection=null),this.fastPoll();},Ga.prototype.onContextMenu=function(t){var e=this,r=e.cm,n=r.display,i=e.textarea,o=cn(r,t),u=n.scroller.scrollTop;if(o&&!f){r.options.resetSelectionOnContextMenu&&-1==r.doc.sel.contains(o)&&Jn(r,Ji)(r.doc,Si(o),B);var c=i.style.cssText,h=e.wrapper.style.cssText;e.wrapper.style.cssText="position: absolute";var d,p=e.wrapper.getBoundingClientRect();if(i.style.cssText="position: absolute; width: 30px; height: 30px;\n top: "+(t.clientY-p.top-5)+"px; left: "+(t.clientX-p.left-5)+"px;\n z-index: 1000; background: "+(a?"rgba(255, 255, 255, .05)":"transparent")+";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);",l&&(d=window.scrollY),n.input.focus(),l&&window.scrollTo(null,d),n.input.reset(),r.somethingSelected()||(i.value=e.prevInput=" "),e.contextMenuPending=!0,n.selForContextMenu=r.doc.sel,clearTimeout(n.detectingSelectAll),a&&s>=9&&g(),_){fe(t);var v=function(){re(window,"mouseup",v),setTimeout(m,20);};te(window,"mouseup",v);}else setTimeout(m,50);}function g(){if(null!=i.selectionStart){var t=r.somethingSelected(),o="​"+(t?i.value:"");i.value="⇚",i.value=o,e.prevInput=t?"":"​",i.selectionStart=1,i.selectionEnd=o.length,n.selForContextMenu=r.doc.sel;}}function m(){if(e.contextMenuPending=!1,e.wrapper.style.cssText=h,i.style.cssText=c,a&&s<9&&n.scrollbars.setScrollTop(n.scroller.scrollTop=u),null!=i.selectionStart){(!a||a&&s<9)&&g();var t=0,o=function(){n.selForContextMenu==r.doc.sel&&0==i.selectionStart&&i.selectionEnd>0&&"​"==e.prevInput?Jn(r,ao)(r):t++<10?n.detectingSelectAll=setTimeout(o,500):(n.selForContextMenu=null,n.input.reset());};n.detectingSelectAll=setTimeout(o,200);}}},Ga.prototype.readOnlyChanged=function(t){t||this.reset(),this.textarea.disabled="nocursor"==t;},Ga.prototype.setUneditable=function(){},Ga.prototype.needsContentAttribute=!1,function(t){var e=t.optionHandlers;function r(r,n,i,o){t.defaults[r]=n,i&&(e[r]=o?function(t,e,r){r!=xa&&i(t,e,r);}:i);}t.defineOption=r,t.Init=xa,r("value","",(function(t,e){return t.setValue(e)}),!0),r("mode",null,(function(t,e){t.doc.modeOption=e,Oi(t);}),!0),r("indentUnit",2,Oi,!0),r("indentWithTabs",!1),r("smartIndent",!0),r("tabSize",4,(function(t){Ai(t),zr(t),ei(t);}),!0),r("lineSeparator",null,(function(t,e){if(t.doc.lineSep=e,e){var r=[],n=t.doc.first;t.doc.iter((function(t){for(var i=0;;){var o=t.text.indexOf(e,i);if(-1==o)break;i=o+e.length,r.push(vt(n,o));}n++;}));for(var i=r.length-1;i>=0;i--)po(t.doc,e,r[i],vt(r[i].line,r[i].ch+e.length));}})),r("specialChars",/[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g,(function(t,e,r){t.state.specialChars=new RegExp(e.source+(e.test("\t")?"":"|\t"),"g"),r!=xa&&t.refresh();})),r("specialCharPlaceholder",Qe,(function(t){return t.refresh()}),!0),r("electricChars",!0),r("inputStyle",m?"contenteditable":"textarea",(function(){throw new Error("inputStyle can not (yet) be changed in a running editor")}),!0),r("spellcheck",!1,(function(t,e){return t.getInputField().spellcheck=e}),!0),r("rtlMoveVisually",!w),r("wholeLineUpdateBefore",!0),r("theme","default",(function(t){wa(t),Sa(t);}),!0),r("keyMap","default",(function(t,e,r){var n=Xo(e),i=r!=xa&&Xo(r);i&&i.detach&&i.detach(t,n),n.attach&&n.attach(t,i||null);})),r("extraKeys",null),r("configureMouse",null),r("lineWrapping",!1,La,!0),r("gutters",[],(function(t){vi(t.options),Sa(t);}),!0),r("fixedGutter",!0,(function(t,e){t.display.gutters.style.left=e?sn(t.display)+"px":"0",t.refresh();}),!0),r("coverGutterNextToScrollbar",!1,(function(t){return In(t)}),!0),r("scrollbarStyle","native",(function(t){Bn(t),In(t),t.display.scrollbars.setScrollTop(t.doc.scrollTop),t.display.scrollbars.setScrollLeft(t.doc.scrollLeft);}),!0),r("lineNumbers",!1,(function(t){vi(t.options),Sa(t);}),!0),r("firstLineNumber",1,Sa,!0),r("lineNumberFormatter",(function(t){return t}),Sa,!0),r("showCursorWhenSelecting",!1,hn,!0),r("resetSelectionOnContextMenu",!0),r("lineWiseCopyCut",!0),r("pasteLinesPerSelection",!0),r("selectionsMayTouch",!1),r("readOnly",!1,(function(t,e){"nocursor"==e&&(xn(t),t.display.input.blur()),t.display.input.readOnlyChanged(e);})),r("disableInput",!1,(function(t,e){e||t.display.input.reset();}),!0),r("dragDrop",!0,ka),r("allowDropFileTypes",null),r("cursorBlinkRate",530),r("cursorScrollMargin",0),r("cursorHeight",1,hn,!0),r("singleCursorHeightPerLine",!0,hn,!0),r("workTime",100),r("workDelay",100),r("flattenSpans",!0,Ai,!0),r("addModeClass",!1,Ai,!0),r("pollInterval",100),r("undoDepth",200,(function(t,e){return t.doc.history.undoDepth=e})),r("historyEventDelay",1250),r("viewportMargin",10,(function(t){return t.refresh()}),!0),r("maxHighlightLength",1e4,Ai,!0),r("moveInputWithCursor",!0,(function(t,e){e||t.display.input.resetPosition();})),r("tabindex",null,(function(t,e){return t.display.input.getField().tabIndex=e||""})),r("autofocus",null),r("direction","ltr",(function(t,e){return t.doc.setDirection(e)}),!0),r("phrases",null);}(Ma),function(t){var e=t.optionHandlers,r=t.helpers={};t.prototype={constructor:t,focus:function(){window.focus(),this.display.input.focus();},setOption:function(t,r){var n=this.options,i=n[t];n[t]==r&&"mode"!=t||(n[t]=r,e.hasOwnProperty(t)&&Jn(this,e[t])(this,r,i),ne(this,"optionChange",this,t));},getOption:function(t){return this.options[t]},getDoc:function(){return this.doc},addKeyMap:function(t,e){this.state.keyMaps[e?"push":"unshift"](Xo(t));},removeKeyMap:function(t){for(var e=this.state.keyMaps,r=0;rr&&(Oa(this,i.head.line,t,!0),r=i.head.line,n==this.doc.sel.primIndex&&On(this));else {var o=i.from(),a=i.to(),s=Math.max(r,o.line);r=Math.min(this.lastLine(),a.line-(a.ch?0:1))+1;for(var l=s;l0&&Xi(this.doc,n,new Ci(o,u[n].to()),B);}}})),getTokenAt:function(t,e){return Ve(this,t,e)},getLineTokens:function(t,e){return Ve(this,vt(t),e,!0)},getTokenTypeAt:function(t){t=Ct(this.doc,t);var e,r=Fe(this,st(this.doc,t.line)),n=0,i=(r.length-1)/2,o=t.ch;if(0==o)e=r[2];else for(;;){var a=n+i>>1;if((a?r[2*a-1]:0)>=o)i=a;else {if(!(r[2*a+1]o&&(t=o,i=!0),n=st(this.doc,t);}else n=t;return Vr(this,n,{top:0,left:0},e||"page",r||i).top+(i?this.doc.height-Kt(n):0)},defaultTextHeight:function(){return nn(this.display)},defaultCharWidth:function(){return on(this.display)},getViewport:function(){return {from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(t,e,r,n,i){var o,a,s,l=this.display,u=(t=qr(this,Ct(this.doc,t))).bottom,c=t.left;if(e.style.position="absolute",e.setAttribute("cm-ignore-events","true"),this.display.input.setUneditable(e),l.sizer.appendChild(e),"over"==n)u=t.top;else if("above"==n||"near"==n){var f=Math.max(l.wrapper.clientHeight,this.doc.height),h=Math.max(l.sizer.clientWidth,l.lineSpace.clientWidth);("above"==n||t.bottom+e.offsetHeight>f)&&t.top>e.offsetHeight?u=t.top-e.offsetHeight:t.bottom+e.offsetHeight<=f&&(u=t.bottom),c+e.offsetWidth>h&&(c=h-e.offsetWidth);}e.style.top=u+"px",e.style.left=e.style.right="","right"==i?(c=l.sizer.clientWidth-e.offsetWidth,e.style.right="0px"):("left"==i?c=0:"middle"==i&&(c=(l.sizer.clientWidth-e.offsetWidth)/2),e.style.left=c+"px"),r&&(o=this,a={left:c,top:u,right:c+e.offsetWidth,bottom:u+e.offsetHeight},null!=(s=Mn(o,a)).scrollTop&&Wn(o,s.scrollTop),null!=s.scrollLeft&&Pn(o,s.scrollLeft));},triggerOnKeyDown:Qn(ua),triggerOnKeyPress:Qn(fa),triggerOnKeyUp:ca,triggerOnMouseDown:Qn(va),execCommand:function(t){if(ta.hasOwnProperty(t))return ta[t].call(null,this)},triggerElectric:Qn((function(t){Ea(this,t);})),findPosH:function(t,e,r,n){var i=1;e<0&&(i=-1,e=-e);for(var o=Ct(this.doc,t),a=0;a0&&a(e.charAt(r-1));)--r;for(;n.5)&&un(this),ne(this,"refresh",this);})),swapDoc:Qn((function(t){var e=this.doc;return e.cm=null,Ei(this,t),zr(this),this.display.input.reset(),An(this,t.scrollLeft,t.scrollTop),this.curOp.forceScroll=!0,lr(this,"swapDoc",this,e),e})),phrase:function(t){var e=this.options.phrases;return e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:t},getInputField:function(){return this.display.input.getField()},getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}},se(t),t.registerHelper=function(e,n,i){r.hasOwnProperty(e)||(r[e]=t[e]={_global:[]}),r[e][n]=i;},t.registerGlobalHelper=function(e,n,i,o){t.registerHelper(e,n,o),r[e]._global.push({pred:i,val:o});};}(Ma);var Ka="iter insert remove copy getEditor constructor".split(" ");for(var qa in Ao.prototype)Ao.prototype.hasOwnProperty(qa)&&z(Ka,qa)<0&&(Ma.prototype[qa]=function(t){return function(){return t.apply(this.doc,arguments)}}(Ao.prototype[qa]));return se(Ao),Ma.inputStyles={textarea:Ga,contenteditable:za},Ma.defineMode=function(t){Ma.defaults.mode||"null"==t||(Ma.defaults.mode=t),Le.apply(this,arguments);},Ma.defineMIME=function(t,e){ke[t]=e;},Ma.defineMode("null",(function(){return {token:function(t){return t.skipToEnd()}}})),Ma.defineMIME("text/plain","null"),Ma.defineExtension=function(t,e){Ma.prototype[t]=e;},Ma.defineDocExtension=function(t,e){Ao.prototype[t]=e;},Ma.fromTextArea=function(t,e){if((e=e?H(e):{}).value=t.value,!e.tabindex&&t.tabIndex&&(e.tabindex=t.tabIndex),!e.placeholder&&t.placeholder&&(e.placeholder=t.placeholder),null==e.autofocus){var r=D();e.autofocus=r==t||null!=t.getAttribute("autofocus")&&r==document.body;}function n(){t.value=s.getValue();}var i;if(t.form&&(te(t.form,"submit",n),!e.leaveSubmitMethodAlone)){var o=t.form;i=o.submit;try{var a=o.submit=function(){n(),o.submit=i,o.submit(),o.submit=a;};}catch(t){}}e.finishInit=function(e){e.save=n,e.getTextArea=function(){return t},e.toTextArea=function(){e.toTextArea=isNaN,n(),t.parentNode.removeChild(e.getWrapperElement()),t.style.display="",t.form&&(re(t.form,"submit",n),"function"==typeof t.form.submit&&(t.form.submit=i));};},t.style.display="none";var s=Ma((function(e){return t.parentNode.insertBefore(e,t.nextSibling)}),e);return s},function(t){t.off=re,t.on=te,t.wheelEventPixels=bi,t.Doc=Ao,t.splitLines=we,t.countColumn=F,t.findColumn=G,t.isWordChar=Q,t.Pass=j,t.signal=ne,t.Line=qe,t.changeEnd=ki,t.scrollbarModel=jn,t.Pos=vt,t.cmpPos=gt,t.modes=Se,t.mimeModes=ke,t.resolveMode=Me,t.getMode=Te,t.modeExtensions=Oe,t.extendMode=Ae,t.copyState=Ne,t.startState=We,t.innerMode=De,t.commands=ta,t.keyMap=Bo,t.keyName=$o,t.isModifierKey=Ko,t.lookupKey=Go,t.normalizeKeyMap=Vo,t.StringStream=Ee,t.SharedTextMarker=Lo,t.TextMarker=So,t.LineWidget=xo,t.e_preventDefault=le,t.e_stopPropagation=ue,t.e_stop=fe,t.addClass=W,t.contains=N,t.rmClass=L,t.keyNames=Fo;}(Ma),Ma.version="5.42.0",Ma}();},function(t,e,r){Object.defineProperty(e,"__esModule",{value:!0});var n=r(0),i=function(){function t(){}return t.prototype.isSeparator=function(t){return " "==t||"\r"==t||"\n"==t||"\t"==t||"("==t||")"==t},t.prototype.isWhiteSpace=function(t){return " "==t||"\r"==t||"\n"==t||"\t"==t},t.prototype.findLastSeparatorIndex=function(t){var e=this;return n.findLastIndex(t,(function(t){return e.isSeparator(t)}))},t.prototype.needSpaceAfter=function(t){return !("("==t)},t.prototype.isLastCharacterWhiteSpace=function(t){return !!t&&this.isWhiteSpace(t[t.length-1])},t.prototype.stripEndWithNonSeparatorCharacters=function(t){if(!t)return t;if(this.isSeparator(t[t.length-1]))return t;var e=this.findLastSeparatorIndex(t);return e<0?"":t.substr(0,e+1)},t.prototype.getEndNotSeparatorCharacers=function(t){if(!t)return t;if(this.isSeparator(t[t.length-1]))return "";var e=this.findLastSeparatorIndex(t);return e<0?t:t.substr(e+1)},t}();e.default=new i;},function(t,e,r){Object.defineProperty(e,"__esModule",{value:!0});var n=r(0),i=function(){function t(){}return t.prototype.quote=function(t){return /\s/g.test(t)?'"'+t+'"':t},t.prototype.buildDefaultObjOrGetOriginal=function(t,e){return n.isString(t)?{value:this.quote(t),type:e}:{value:t,type:e}},t.prototype.handleParseError=function(t,e,r){var i=this,o=e;return n.flatMap(r.expected,(function(t){var e=[];if("literal"==t.type&&(e=n.map([t.text||t.value],(function(t){return {value:t,type:"literal"}}))),"other"==t.type){var r=o.getLastTokenType()||"value";"value"==r&&(e=n.map(i.needCategories(),(function(t){return i.buildDefaultObjOrGetOriginal(t,"category")}))),"category"==r&&(e=n.map(i.needOperators(o.getLastCategory()),(function(t){return i.buildDefaultObjOrGetOriginal(t,"operator")}))),"operator"==r&&(e=n.map(i.needValues(o.getLastCategory(),o.getLastOperator()),(function(t){return i.buildDefaultObjOrGetOriginal(t,"value")})));}return e}))},t.prototype.hasCategory=function(t){return !1},t.prototype.hasOperator=function(t,e){return !1},t.prototype.needCategories=function(){return []},t.prototype.needOperators=function(t){return []},t.prototype.needValues=function(t,e){return []},t}();e.default=i;},function(t,e){t.exports=function(t){var e=[];return e.toString=function(){return this.map((function(e){var r=function(t,e){var r=t[1]||"",n=t[3];if(!n)return r;if(e&&"function"==typeof btoa){var i=(a=n,"/*# sourceMappingURL=data:application/json;charset=utf-8;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(a))))+" */"),o=n.sources.map((function(t){return "/*# sourceURL="+n.sourceRoot+t+" */"}));return [r].concat(o).concat([i]).join("\n")}var a;return [r].join("\n")}(e,t);return e[2]?"@media "+e[2]+"{"+r+"}":r})).join("")},e.i=function(t,r){"string"==typeof t&&(t=[[null,t,""]]);for(var n={},i=0;i=0&&f.splice(e,1);}function m(t){var e=document.createElement("style");if(void 0===t.attrs.type&&(t.attrs.type="text/css"),void 0===t.attrs.nonce){var n=function(){return r.nc}();n&&(t.attrs.nonce=n);}return y(e,t.attrs),v(t,e),e}function y(t,e){Object.keys(e).forEach((function(r){t.setAttribute(r,e[r]);}));}function b(t,e){var r,n,i,o;if(e.transform&&t.css){if(!(o="function"==typeof e.transform?e.transform(t.css):e.transform.default(t.css)))return function(){};t.css=o;}if(e.singleton){var a=c++;r=u||(u=m(e)),n=C.bind(null,r,a,!1),i=C.bind(null,r,a,!0);}else t.sourceMap&&"function"==typeof URL&&"function"==typeof URL.createObjectURL&&"function"==typeof URL.revokeObjectURL&&"function"==typeof Blob&&"function"==typeof btoa?(r=function(t){var e=document.createElement("link");return void 0===t.attrs.type&&(t.attrs.type="text/css"),t.attrs.rel="stylesheet",y(e,t.attrs),v(t,e),e}(e),n=S.bind(null,r,e),i=function(){g(r),r.href&&URL.revokeObjectURL(r.href);}):(r=m(e),n=_.bind(null,r),i=function(){g(r);});return n(t),function(e){if(e){if(e.css===t.css&&e.media===t.media&&e.sourceMap===t.sourceMap)return;n(t=e);}else i();}}t.exports=function(t,e){if("undefined"!=typeof DEBUG&&DEBUG&&"object"!=typeof document)throw new Error("The style-loader cannot be used in a non-browser environment");(e=e||{}).attrs="object"==typeof e.attrs?e.attrs:{},e.singleton||"boolean"==typeof e.singleton||(e.singleton=a()),e.insertInto||(e.insertInto="head"),e.insertAt||(e.insertAt="bottom");var r=p(t,e);return d(r,e),function(t){for(var n=[],i=0;i1)){if(this.somethingSelected()){if(!r.hint.supportsSelection)return;for(var i=0;iu.clientHeight+1,k=a.getScrollInfo();if(_>0){var L=C.bottom-C.top;if(g.top-(g.bottom-C.top)-L>0)u.style.top=(y=g.top-L)+"px",b=!1;else if(L>x){u.style.height=x-5+"px",u.style.top=(y=g.bottom-C.top)+"px";var M=a.getCursor();r.from.ch!=M.ch&&(g=a.cursorCoords(M),u.style.left=(m=g.left)+"px",C=u.getBoundingClientRect());}}var T,O=C.right-w;if(O>0&&(C.right-C.left>w&&(u.style.width=w-5+"px",O-=C.right-C.left-w),u.style.left=(m=g.left-O)+"px"),S)for(var A=u.firstChild;A;A=A.nextSibling)A.style.paddingRight=a.display.nativeBarWidth+"px";return a.addKeyMap(this.keyMap=function(t,e){var r={Up:function(){e.moveFocus(-1);},Down:function(){e.moveFocus(1);},PageUp:function(){e.moveFocus(1-e.menuSize(),!0);},PageDown:function(){e.moveFocus(e.menuSize()-1,!0);},Home:function(){e.setFocus(0);},End:function(){e.setFocus(e.length-1);},Enter:e.pick,Tab:e.pick,Esc:e.close},n=t.options.customKeys,i=n?{}:r;function o(t,n){var o;o="string"!=typeof n?function(t){return n(t,e)}:r.hasOwnProperty(n)?r[n]:n,i[t]=o;}if(n)for(var a in n)n.hasOwnProperty(a)&&o(a,n[a]);var s=t.options.extraKeys;if(s)for(var a in s)s.hasOwnProperty(a)&&o(a,s[a]);return i}(e,{moveFocus:function(t,e){n.changeActive(n.selectedHint+t,e);},setFocus:function(t){n.changeActive(t);},menuSize:function(){return n.screenAmount()},length:f.length,close:function(){e.close();},pick:function(){n.pick();},data:r})),e.options.closeOnUnfocus&&(a.on("blur",this.onBlur=function(){T=setTimeout((function(){e.close();}),100);}),a.on("focus",this.onFocus=function(){clearTimeout(T);})),a.on("scroll",this.onScroll=function(){var t=a.getScrollInfo(),r=a.getWrapperElement().getBoundingClientRect(),n=y+k.top-t.top,i=n-(l.pageYOffset||(s.documentElement||s.body).scrollTop);if(b||(i+=u.offsetHeight),i<=r.top||i>=r.bottom)return e.close();u.style.top=n+"px",u.style.left=m+k.left-t.left+"px";}),t.on(u,"dblclick",(function(t){var e=o(u,t.target||t.srcElement);e&&null!=e.hintId&&(n.changeActive(e.hintId),n.pick());})),t.on(u,"click",(function(t){var r=o(u,t.target||t.srcElement);r&&null!=r.hintId&&(n.changeActive(r.hintId),e.options.completeOnSingleClick&&n.pick());})),t.on(u,"mousedown",(function(){setTimeout((function(){a.focus();}),20);})),t.signal(r,"select",f[this.selectedHint],u.childNodes[this.selectedHint]),!0}function s(t,e,r,n){if(t.async)t(e,n,r);else {var i=t(e,r);i&&i.then?i.then(n):n(i);}}e.prototype={close:function(){this.active()&&(this.cm.state.completionActive=null,this.tick=null,this.cm.off("cursorActivity",this.activityFunc),this.widget&&this.data&&t.signal(this.data,"close"),this.widget&&this.widget.close(),t.signal(this.cm,"endCompletion",this.cm));},active:function(){return this.cm.state.completionActive==this},pick:function(e,r){var n=e.list[r];n.hint?n.hint(this.cm,e,n):this.cm.replaceRange(i(n),n.from||e.from,n.to||e.to,"complete"),t.signal(e,"pick",n),this.close();},cursorActivity:function(){this.debounce&&(n(this.debounce),this.debounce=0);var t=this.cm.getCursor(),e=this.cm.getLine(t.line);if(t.line!=this.startPos.line||e.length-t.ch!=this.startLen-this.startPos.ch||t.ch=this.data.list.length?e=r?this.data.list.length-1:0:e<0&&(e=r?0:this.data.list.length-1),this.selectedHint!=e){var n=this.hints.childNodes[this.selectedHint];n&&(n.className=n.className.replace(" CodeMirror-hint-active","")),(n=this.hints.childNodes[this.selectedHint=e]).className+=" CodeMirror-hint-active",n.offsetTopthis.hints.scrollTop+this.hints.clientHeight&&(this.hints.scrollTop=n.offsetTop+n.offsetHeight-this.hints.clientHeight+3),t.signal(this.data,"select",this.data.list[this.selectedHint],n);}},screenAmount:function(){return Math.floor(this.hints.clientHeight/this.hints.firstChild.offsetHeight)||1}},t.registerHelper("hint","auto",{resolve:function(e,r){var n,i=e.getHelpers(r,"hint");if(i.length){var o=function(t,e,r){var n=function(t,e){if(!t.somethingSelected())return e;for(var r=[],n=0;n0?e(t):i(o+1);}));}(0);};return o.async=!0,o.supportsSelection=!0,o}return (n=e.getHelper(e.getCursor(),"hintWords"))?function(e){return t.hint.fromList(e,{words:n})}:t.hint.anyword?function(e,r){return t.hint.anyword(e,r)}:function(){}}}),t.registerHelper("hint","fromList",(function(e,r){var n,i=e.getCursor(),o=e.getTokenAt(i),a=t.Pos(i.line,o.start),s=i;o.start,]/,closeOnUnfocus:!0,completeOnSingleClick:!0,container:null,customKeys:null,extraKeys:null};t.defineOption("hintOptions",null);}(r(2));},function(t,e,r){!function(t){function e(t){t.state.placeholder&&(t.state.placeholder.parentNode.removeChild(t.state.placeholder),t.state.placeholder=null);}function r(t){e(t);var r=t.state.placeholder=document.createElement("pre");r.style.cssText="height: 0; overflow: visible",r.style.direction=t.getOption("direction"),r.className="CodeMirror-placeholder";var n=t.getOption("placeholder");"string"==typeof n&&(n=document.createTextNode(n)),r.appendChild(n),t.display.lineSpace.insertBefore(r,t.display.lineSpace.firstChild);}function n(t){o(t)&&r(t);}function i(t){var n=t.getWrapperElement(),i=o(t);n.className=n.className.replace(" CodeMirror-empty","")+(i?" CodeMirror-empty":""),i?r(t):e(t);}function o(t){return 1===t.lineCount()&&""===t.getLine(0)}t.defineOption("placeholder","",(function(r,o,a){var s=a&&a!=t.Init;if(o&&!s)r.on("blur",n),r.on("change",i),r.on("swapDoc",i),i(r);else if(!o&&s){r.off("blur",n),r.off("change",i),r.off("swapDoc",i),e(r);var l=r.getWrapperElement();l.className=l.className.replace(" CodeMirror-empty","");}o&&!r.hasFocus()&&n(r);}));}(r(2));},function(t,e,r){Object.defineProperty(e,"__esModule",{value:!0}),r(2).defineMode("filter-mode",(function(t,e){function r(t){var e,r=(e=t.fieldState)==n.category?n.operator:e==n.operator?n.value:e==n.value?n.category:void 0,i=t.fieldState;return t.fieldState=r,i.toString()}return {startState:function(){return {inString:!1,fieldState:n.category}},token:function(t,e){return " "==(n=t.peek())||"\r"==n||"\n"==n||"\t"==n?(t.eatSpace(),null):"("==t.peek()||")"==t.peek()?(t.next(),"bracket"):t.match("AND",!0,!0)||t.match("OR",!0,!0)?"condition":(e.inString||'"'!=t.peek()||(t.next(),e.inString=!0),e.inString?(t.skipTo('"')?(t.next(),e.inString=!1):t.skipToEnd(),r(e)):(t.eatWhile(/[^\r\n\t\s\(\)]+/),r(e)));var n;}}}));var n=function(){function t(){}return t.none="none",t.category="category",t.operator="operator",t.value="value",t}();},function(t,e,r){var n=r(16);"string"==typeof n&&(n=[[t.i,n,""]]);var i={hmr:!0,transform:void 0,insertInto:void 0};r(6)(n,i);n.locals&&(t.exports=n.locals);},function(t,e,r){(t.exports=r(5)(!1)).push([t.i,".CodeMirror{font-family:monospace;height:300px;color:black;direction:ltr}.CodeMirror-lines{padding:4px 0}.CodeMirror pre{padding:0 4px}.CodeMirror-scrollbar-filler,.CodeMirror-gutter-filler{background-color:white}.CodeMirror-gutters{border-right:1px solid #ddd;background-color:#f7f7f7;white-space:nowrap}.CodeMirror-linenumber{padding:0 3px 0 5px;min-width:20px;text-align:right;color:#999;white-space:nowrap}.CodeMirror-guttermarker{color:black}.CodeMirror-guttermarker-subtle{color:#999}.CodeMirror-cursor{border-left:1px solid black;border-right:none;width:0}.CodeMirror div.CodeMirror-secondarycursor{border-left:1px solid silver}.cm-fat-cursor .CodeMirror-cursor{width:auto;border:0 !important;background:#7e7}.cm-fat-cursor div.CodeMirror-cursors{z-index:1}.cm-fat-cursor-mark{background-color:rgba(20,255,20,0.5);-webkit-animation:blink 1.06s steps(1) infinite;-moz-animation:blink 1.06s steps(1) infinite;animation:blink 1.06s steps(1) infinite}.cm-animate-fat-cursor{width:auto;border:0;-webkit-animation:blink 1.06s steps(1) infinite;-moz-animation:blink 1.06s steps(1) infinite;animation:blink 1.06s steps(1) infinite;background-color:#7e7}@-moz-keyframes blink{50%{background-color:transparent}}@-webkit-keyframes blink{50%{background-color:transparent}}@keyframes blink{50%{background-color:transparent}}.cm-tab{display:inline-block;text-decoration:inherit}.CodeMirror-rulers{position:absolute;left:0;right:0;top:-50px;bottom:-20px;overflow:hidden}.CodeMirror-ruler{border-left:1px solid #ccc;top:0;bottom:0;position:absolute}.cm-s-default .cm-header{color:blue}.cm-s-default .cm-quote{color:#090}.cm-negative{color:#d44}.cm-positive{color:#292}.cm-header,.cm-strong{font-weight:bold}.cm-em{font-style:italic}.cm-link{text-decoration:underline}.cm-strikethrough{text-decoration:line-through}.cm-s-default .cm-keyword{color:#708}.cm-s-default .cm-atom{color:#219}.cm-s-default .cm-number{color:#164}.cm-s-default .cm-def{color:#00f}.cm-s-default .cm-variable-2{color:#05a}.cm-s-default .cm-variable-3,.cm-s-default .cm-type{color:#085}.cm-s-default .cm-comment{color:#a50}.cm-s-default .cm-string{color:#a11}.cm-s-default .cm-string-2{color:#f50}.cm-s-default .cm-meta{color:#555}.cm-s-default .cm-qualifier{color:#555}.cm-s-default .cm-builtin{color:#30a}.cm-s-default .cm-bracket{color:#997}.cm-s-default .cm-tag{color:#170}.cm-s-default .cm-attribute{color:#00c}.cm-s-default .cm-hr{color:#999}.cm-s-default .cm-link{color:#00c}.cm-s-default .cm-error{color:#f00}.cm-invalidchar{color:#f00}.CodeMirror-composing{border-bottom:2px solid}div.CodeMirror span.CodeMirror-matchingbracket{color:#0b0}div.CodeMirror span.CodeMirror-nonmatchingbracket{color:#a22}.CodeMirror-matchingtag{background:rgba(255,150,0,0.3)}.CodeMirror-activeline-background{background:#e8f2ff}.CodeMirror{position:relative;overflow:hidden;background:white}.CodeMirror-scroll{overflow:scroll !important;margin-bottom:-30px;margin-right:-30px;padding-bottom:30px;height:100%;outline:none;position:relative}.CodeMirror-sizer{position:relative;border-right:30px solid transparent}.CodeMirror-vscrollbar,.CodeMirror-hscrollbar,.CodeMirror-scrollbar-filler,.CodeMirror-gutter-filler{position:absolute;z-index:6;display:none}.CodeMirror-vscrollbar{right:0;top:0;overflow-x:hidden;overflow-y:scroll}.CodeMirror-hscrollbar{bottom:0;left:0;overflow-y:hidden;overflow-x:scroll}.CodeMirror-scrollbar-filler{right:0;bottom:0}.CodeMirror-gutter-filler{left:0;bottom:0}.CodeMirror-gutters{position:absolute;left:0;top:0;min-height:100%;z-index:3}.CodeMirror-gutter{white-space:normal;height:100%;display:inline-block;vertical-align:top;margin-bottom:-30px}.CodeMirror-gutter-wrapper{position:absolute;z-index:4;background:none !important;border:none !important}.CodeMirror-gutter-background{position:absolute;top:0;bottom:0;z-index:4}.CodeMirror-gutter-elt{position:absolute;cursor:default;z-index:4}.CodeMirror-gutter-wrapper ::selection{background-color:transparent}.CodeMirror-gutter-wrapper ::-moz-selection{background-color:transparent}.CodeMirror-lines{cursor:text;min-height:1px}.CodeMirror pre{-moz-border-radius:0;-webkit-border-radius:0;border-radius:0;border-width:0;background:transparent;font-family:inherit;font-size:inherit;margin:0;white-space:pre;word-wrap:normal;line-height:inherit;color:inherit;z-index:2;position:relative;overflow:visible;-webkit-tap-highlight-color:transparent;-webkit-font-variant-ligatures:contextual;font-variant-ligatures:contextual}.CodeMirror-wrap pre{word-wrap:break-word;white-space:pre-wrap;word-break:normal}.CodeMirror-linebackground{position:absolute;left:0;right:0;top:0;bottom:0;z-index:0}.CodeMirror-linewidget{position:relative;z-index:2;padding:.1px}.CodeMirror-rtl pre{direction:rtl}.CodeMirror-code{outline:none}.CodeMirror-scroll,.CodeMirror-sizer,.CodeMirror-gutter,.CodeMirror-gutters,.CodeMirror-linenumber{-moz-box-sizing:content-box;box-sizing:content-box}.CodeMirror-measure{position:absolute;width:100%;height:0;overflow:hidden;visibility:hidden}.CodeMirror-cursor{position:absolute;pointer-events:none}.CodeMirror-measure pre{position:static}div.CodeMirror-cursors{visibility:hidden;position:relative;z-index:3}div.CodeMirror-dragcursors{visibility:visible}.CodeMirror-focused div.CodeMirror-cursors{visibility:visible}.CodeMirror-selected{background:#d9d9d9}.CodeMirror-focused .CodeMirror-selected{background:#d7d4f0}.CodeMirror-crosshair{cursor:crosshair}.CodeMirror-line::selection,.CodeMirror-line>span::selection,.CodeMirror-line>span>span::selection{background:#d7d4f0}.CodeMirror-line::-moz-selection,.CodeMirror-line>span::-moz-selection,.CodeMirror-line>span>span::-moz-selection{background:#d7d4f0}.cm-searching{background-color:#ffa;background-color:rgba(255,255,0,0.4)}.cm-force-border{padding-right:.1px}@media print{.CodeMirror div.CodeMirror-cursors{visibility:hidden}}.cm-tab-wrap-hack:after{content:''}span.CodeMirror-selectedtext{background:none}",""]);},function(t,e){t.exports=function(t){var e="undefined"!=typeof window&&window.location;if(!e)throw new Error("fixUrls requires window.location");if(!t||"string"!=typeof t)return t;var r=e.protocol+"//"+e.host,n=r+e.pathname.replace(/\/[^\/]*$/,"/");return t.replace(/url\s*\(((?:[^)(]|\((?:[^)(]+|\([^)(]*\))*\))*)\)/gi,(function(t,e){var i,o=e.trim().replace(/^"(.*)"$/,(function(t,e){return e})).replace(/^'(.*)'$/,(function(t,e){return e}));return /^(#|data:|http:\/\/|https:\/\/|file:\/\/\/|\s*$)/i.test(o)?t:(i=0===o.indexOf("//")?o:0===o.indexOf("/")?r+o:n+o.replace(/^\.\//,""),"url("+JSON.stringify(i)+")")}))};},function(t,e,r){var n=r(19);"string"==typeof n&&(n=[[t.i,n,""]]);var i={hmr:!0,transform:void 0,insertInto:void 0};r(6)(n,i);n.locals&&(t.exports=n.locals);},function(t,e,r){(t.exports=r(5)(!1)).push([t.i,".CodeMirror-hints{position:absolute;z-index:10;overflow:hidden;list-style:none;margin:0;padding:2px;-webkit-box-shadow:2px 3px 5px rgba(0,0,0,0.2);-moz-box-shadow:2px 3px 5px rgba(0,0,0,0.2);box-shadow:2px 3px 5px rgba(0,0,0,0.2);border-radius:3px;border:1px solid silver;background:white;font-size:90%;font-family:monospace;max-height:20em;overflow-y:auto}.CodeMirror-hint{margin:0;padding:0 4px;border-radius:2px;white-space:pre;color:black;cursor:pointer}li.CodeMirror-hint-active{background:#08f;color:white}",""]);},function(t,e,r){(function(t){var n,i=Object.assign||function(t){for(var e=1;e=0;case"!contains":return t[i].toLowerCase().indexOf(n.toLowerCase())<0}return !1},e}(r(8).default);e.default=a;},function(t,e,r){var n,i=this&&this.__extends||(n=function(t,e){return (n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e;}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r]);})(t,e)},function(t,e){function r(){this.constructor=t;}n(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r);});Object.defineProperty(e,"__esModule",{value:!0});var o=r(4),a=r(0),s=function(t){function e(e,r){var n=t.call(this)||this;return n.data=e,n.options=r,n.cache={},n.parseResult=null,n.categories=a.map(n.options,(function(t){return t.columnText?t.columnText:t.columnField})),n}return i(e,t),e.prototype.hasCategory=function(t){return void 0!==a.find(this.options,(function(e){return t===e.columnField||t===e.columnText}))},e.prototype.hasOperator=function(t,e){return this.needOperators(t).indexOf(e)>=0},e.prototype.needCategories=function(){return this.categories},e.prototype.needOperators=function(t){var e=a.find(this.options,(function(e){return null!=e.customOperatorFunc&&(e.columnText==t||e.columnField==t)}));return e?e.customOperatorFunc(t):["==","!=","contains","!contains"]},e.prototype.needValues=function(t,e){var r=a.find(this.options,(function(e){return e.columnField==t||e.columnText==t}));return null!=r&&"selection"==r.type&&null!=this.data?(this.cache[t]||(this.cache[t]=a.chain(this.data).map((function(e){return e[t]})).uniq().value()),this.cache[t]):null!=r&&r.customValuesFunc?r.customValuesFunc(t,e):[]},e}(o.default);e.default=s;},function(t,e,r){Object.defineProperty(e,"__esModule",{value:!0});var n=r(28),i=r(0),o=r(4),a=r(29),s=r(3),l=function(){function t(){this.autoCompleteHandler=new o.default,this.lastError=null,this.parseTrace=new a.default;}return t.prototype.parse=function(t){if(t=i.trim(t),i.isEmpty(t))return [];try{return this.parseQuery(t)}catch(t){return t.isError=!0,t}},t.prototype.parseQuery=function(t){return this.parseTrace.clear(),n.parse(t,{parseTrace:this.parseTrace})},t.prototype.getSuggestions=function(t){t=s.default.stripEndWithNonSeparatorCharacters(t);try{return this.parseQuery(t),!t||s.default.isLastCharacterWhiteSpace(t)?i.map(["AND","OR"],(function(t){return {value:t,type:"literal"}})):[]}catch(t){return this.autoCompleteHandler.handleParseError(n,this.parseTrace,t)}},t.prototype.setAutoCompleteHandler=function(t){this.autoCompleteHandler=t;},t}();e.default=l;},function(t,e,r){function n(t,e,r,i){this.message=t,this.expected=e,this.found=r,this.location=i,this.name="SyntaxError","function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,n);}!function(t,e){function r(){this.constructor=t;}r.prototype=e.prototype,t.prototype=new r;}(n,Error),n.buildMessage=function(t,e){var r={literal:function(t){return '"'+i(t.text)+'"'},class:function(t){var e,r="";for(e=0;e0){for(e=1,n=1;ek&&(k=C,L=[]),L.push(t));}function P(t,e,r){return new n(n.buildMessage(t,e),t,e,r)}function R(){var e,r,n,o,a,u,c,f;if(e=C,z()!==i)if((r=H())!==i){for(n=[],o=C,(a=I())!==i?("and"===t.substr(C,3).toLowerCase()?(u=t.substr(C,3),C+=3):(u=i,0===M&&E(s)),u===i&&("or"===t.substr(C,2).toLowerCase()?(u=t.substr(C,2),C+=2):(u=i,0===M&&E(l))),u!==i&&(c=I())!==i&&(f=H())!==i?o=a=[a,u,c,f]:(C=o,o=i)):(C=o,o=i);o!==i;)n.push(o),o=C,(a=I())!==i?("and"===t.substr(C,3).toLowerCase()?(u=t.substr(C,3),C+=3):(u=i,0===M&&E(s)),u===i&&("or"===t.substr(C,2).toLowerCase()?(u=t.substr(C,2),C+=2):(u=i,0===M&&E(l))),u!==i&&(c=I())!==i&&(f=H())!==i?o=a=[a,u,c,f]:(C=o,o=i)):(C=o,o=i);n!==i&&(o=z())!==i?(_=e,e=function(t,e){for(var r=[t],n=0;n!!element.type&&element.type.tabsRole===tabsRole}const isTab=makeTypeChecker("Tab");const isTabList=makeTypeChecker("TabList");const isTabPanel=makeTypeChecker("TabPanel"); + +function isTabChild(child){return isTab(child)||isTabList(child)||isTabPanel(child)}function deepMap(children,callback){return reactExports.Children.map(children,child=>{if(child===null)return null;if(isTabChild(child)){return callback(child)}if(child.props&&child.props.children&&typeof child.props.children==="object"){return reactExports.cloneElement(child,{...child.props,children:deepMap(child.props.children,callback)})}return child})}function deepForEach(children,callback){return reactExports.Children.forEach(children,child=>{if(child===null)return;if(isTab(child)||isTabPanel(child)){callback(child);}else if(child.props&&child.props.children&&typeof child.props.children==="object"){if(isTabList(child))callback(child);deepForEach(child.props.children,callback);}})} + +function r$1(e){var t,f,n="";if("string"==typeof e||"number"==typeof e)n+=e;else if("object"==typeof e)if(Array.isArray(e))for(t=0;t{if(isTab(child))tabCount++;});return tabCount} + +function isNode(node){return node&&"getAttribute"in node}function isTabNode(node){return isNode(node)&&node.getAttribute("data-rttab")}function isTabDisabled(node){return isNode(node)&&node.getAttribute("aria-disabled")==="true"}let canUseActiveElement;function determineCanUseActiveElement(environment){const env=environment||(typeof window!=="undefined"?window:undefined);try{canUseActiveElement=!!(typeof env!=="undefined"&&env.document&&env.document.activeElement);}catch(e){canUseActiveElement=false;}}const defaultProps$4={className:"react-tabs",focus:false};const UncontrolledTabs=props=>{let tabNodes=reactExports.useRef([]);let tabIds=reactExports.useRef([]);const ref=reactExports.useRef();function setSelected(index,event){if(index<0||index>=getTabsCount$1())return;const{onSelect,selectedIndex}=props;onSelect(index,selectedIndex,event);}function getNextTab(index){const count=getTabsCount$1();for(let i=index+1;iindex){if(!isTabDisabled(getTab(i))){return i}}return index}function getFirstTab(){const count=getTabsCount$1();for(let i=0;i{let result=child;if(isTabList(child)){let listIndex=0;let wasTabFocused=false;if(canUseActiveElement==null){determineCanUseActiveElement(environment);}const env=environment||(typeof window!=="undefined"?window:undefined);if(canUseActiveElement&&env){wasTabFocused=React.Children.toArray(child.props.children).filter(isTab).some((tab,i)=>env.document.activeElement===getTab(i));}result=reactExports.cloneElement(child,{children:deepMap(child.props.children,tab=>{const key=`tabs-${listIndex}`;const selected=selectedIndex===listIndex;const props={tabRef:node=>{tabNodes.current[key]=node;},id:tabIds.current[listIndex],selected,focus:selected&&(focus||wasTabFocused)};if(selectedTabClassName)props.selectedClassName=selectedTabClassName;if(disabledTabClassName)props.disabledClassName=disabledTabClassName;listIndex++;return reactExports.cloneElement(tab,props)})});}else if(isTabPanel(child)){const props={id:tabIds.current[index],selected:selectedIndex===index};if(forceRenderTabPanel)props.forceRender=forceRenderTabPanel;if(selectedTabPanelClassName)props.selectedClassName=selectedTabPanelClassName;index++;result=reactExports.cloneElement(child,props);}return result})}function handleKeyDown(e){const{direction,disableUpDownKeys,disableLeftRightKeys}=props;if(isTabFromContainer(e.target)){let{selectedIndex:index}=props;let preventDefault=false;let useSelectedIndex=false;if(e.code==="Space"||e.keyCode===32||e.code==="Enter"||e.keyCode===13){preventDefault=true;useSelectedIndex=false;handleClick(e);}if(!disableLeftRightKeys&&(e.keyCode===37||e.code==="ArrowLeft")||!disableUpDownKeys&&(e.keyCode===38||e.code==="ArrowUp")){if(direction==="rtl"){index=getNextTab(index);}else {index=getPrevTab(index);}preventDefault=true;useSelectedIndex=true;}else if(!disableLeftRightKeys&&(e.keyCode===39||e.code==="ArrowRight")||!disableUpDownKeys&&(e.keyCode===40||e.code==="ArrowDown")){if(direction==="rtl"){index=getPrevTab(index);}else {index=getNextTab(index);}preventDefault=true;useSelectedIndex=true;}else if(e.keyCode===35||e.code==="End"){index=getLastTab();preventDefault=true;useSelectedIndex=true;}else if(e.keyCode===36||e.code==="Home"){index=getFirstTab();preventDefault=true;useSelectedIndex=true;}if(preventDefault){e.preventDefault();}if(useSelectedIndex){setSelected(index,e);}}}function handleClick(e){let node=e.target;do{if(isTabFromContainer(node)){if(isTabDisabled(node)){return}const index=[].slice.call(node.parentNode.children).filter(isTabNode).indexOf(node);setSelected(index,e);return}}while((node=node.parentNode)!=null)}function isTabFromContainer(node){if(!isTabNode(node)){return false}let nodeAncestor=node.parentElement;do{if(nodeAncestor===ref.current)return true;if(nodeAncestor.getAttribute("data-rttabs"))break;nodeAncestor=nodeAncestor.parentElement;}while(nodeAncestor);return false}const{children,className,disabledTabClassName,domRef,focus,forceRenderTabPanel,onSelect,selectedIndex,selectedTabClassName,selectedTabPanelClassName,environment,disableUpDownKeys,disableLeftRightKeys,...attributes}={...defaultProps$4,...props};return React.createElement("div",Object.assign({},attributes,{className:clsx(className),onClick:handleClick,onKeyDown:handleKeyDown,ref:node=>{ref.current=node;if(domRef)domRef(node);},"data-rttabs":true}),getChildren())};UncontrolledTabs.propTypes={}; + +const MODE_CONTROLLED=0;const MODE_UNCONTROLLED=1;const defaultProps$3={defaultFocus:false,focusTabOnClick:true,forceRenderTabPanel:false,selectedIndex:null,defaultIndex:null,environment:null,disableUpDownKeys:false,disableLeftRightKeys:false};const getModeFromProps=props=>{return props.selectedIndex===null?MODE_UNCONTROLLED:MODE_CONTROLLED};const Tabs=props=>{const{children,defaultFocus,defaultIndex,focusTabOnClick,onSelect,...attributes}={...defaultProps$3,...props};const[focus,setFocus]=reactExports.useState(defaultFocus);const[mode]=reactExports.useState(getModeFromProps(attributes));const[selectedIndex,setSelectedIndex]=reactExports.useState(mode===MODE_UNCONTROLLED?defaultIndex||0:null);reactExports.useEffect(()=>{setFocus(false);},[]);if(mode===MODE_UNCONTROLLED){const tabsCount=getTabsCount(children);reactExports.useEffect(()=>{if(selectedIndex!=null){const maxTabIndex=Math.max(0,tabsCount-1);setSelectedIndex(Math.min(selectedIndex,maxTabIndex));}},[tabsCount]);}const handleSelected=(index,last,event)=>{if(typeof onSelect==="function"){if(onSelect(index,last,event)===false)return}if(focusTabOnClick){setFocus(true);}if(mode===MODE_UNCONTROLLED){setSelectedIndex(index);}};let subProps={...props,...attributes};subProps.focus=focus;subProps.onSelect=handleSelected;if(selectedIndex!=null){subProps.selectedIndex=selectedIndex;}delete subProps.defaultFocus;delete subProps.defaultIndex;delete subProps.focusTabOnClick;return React.createElement(UncontrolledTabs,subProps,children)};Tabs.propTypes={};Tabs.tabsRole="Tabs"; + +const defaultProps$2={className:"react-tabs__tab-list"};const TabList=props=>{const{children,className,...attributes}={...defaultProps$2,...props};return React.createElement("ul",Object.assign({},attributes,{className:clsx(className),role:"tablist"}),children)};TabList.tabsRole="TabList";TabList.propTypes={}; + +const DEFAULT_CLASS$1="react-tabs__tab";const defaultProps$1={className:DEFAULT_CLASS$1,disabledClassName:`${DEFAULT_CLASS$1}--disabled`,focus:false,id:null,selected:false,selectedClassName:`${DEFAULT_CLASS$1}--selected`};const Tab=props=>{let nodeRef=reactExports.useRef();const{children,className,disabled,disabledClassName,focus,id,selected,selectedClassName,tabIndex,tabRef,...attributes}={...defaultProps$1,...props};reactExports.useEffect(()=>{if(selected&&focus){nodeRef.current.focus();}},[selected,focus]);return React.createElement("li",Object.assign({},attributes,{className:clsx(className,{[selectedClassName]:selected,[disabledClassName]:disabled}),ref:node=>{nodeRef.current=node;if(tabRef)tabRef(node);},role:"tab",id:`tab${id}`,"aria-selected":selected?"true":"false","aria-disabled":disabled?"true":"false","aria-controls":`panel${id}`,tabIndex:tabIndex||(selected?"0":null),"data-rttab":true}),children)};Tab.propTypes={};Tab.tabsRole="Tab"; + +const DEFAULT_CLASS="react-tabs__tab-panel";const defaultProps={className:DEFAULT_CLASS,forceRender:false,selectedClassName:`${DEFAULT_CLASS}--selected`};const TabPanel=props=>{const{children,className,forceRender,id,selected,selectedClassName,...attributes}={...defaultProps,...props};return React.createElement("div",Object.assign({},attributes,{className:clsx(className,{[selectedClassName]:selected}),role:"tabpanel",id:`panel${id}`,"aria-labelledby":`tab${id}`}),forceRender||selected?children:null)};TabPanel.tabsRole="TabPanel";TabPanel.propTypes={}; + +function commonjsRequire(path) { + throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.'); +} + +var moment$1 = {exports: {}}; + +(function (module, exports) { +(function (global, factory) { + module.exports = factory() ; + }(commonjsGlobal, (function () { + var hookCallback; + + function hooks() { + return hookCallback.apply(null, arguments); + } + + // This is done to register the method called with moment() + // without creating circular dependencies. + function setHookCallback(callback) { + hookCallback = callback; + } + + function isArray(input) { + return ( + input instanceof Array || + Object.prototype.toString.call(input) === '[object Array]' + ); + } + + function isObject(input) { + // IE8 will treat undefined and null as object if it wasn't for + // input != null + return ( + input != null && + Object.prototype.toString.call(input) === '[object Object]' + ); + } + + function hasOwnProp(a, b) { + return Object.prototype.hasOwnProperty.call(a, b); + } + + function isObjectEmpty(obj) { + if (Object.getOwnPropertyNames) { + return Object.getOwnPropertyNames(obj).length === 0; + } else { + var k; + for (k in obj) { + if (hasOwnProp(obj, k)) { + return false; + } + } + return true; + } + } + + function isUndefined(input) { + return input === void 0; + } + + function isNumber(input) { + return ( + typeof input === 'number' || + Object.prototype.toString.call(input) === '[object Number]' + ); + } + + function isDate(input) { + return ( + input instanceof Date || + Object.prototype.toString.call(input) === '[object Date]' + ); + } + + function map(arr, fn) { + var res = [], + i, + arrLen = arr.length; + for (i = 0; i < arrLen; ++i) { + res.push(fn(arr[i], i)); + } + return res; + } + + function extend(a, b) { + for (var i in b) { + if (hasOwnProp(b, i)) { + a[i] = b[i]; + } + } + + if (hasOwnProp(b, 'toString')) { + a.toString = b.toString; + } + + if (hasOwnProp(b, 'valueOf')) { + a.valueOf = b.valueOf; + } + + return a; + } + + function createUTC(input, format, locale, strict) { + return createLocalOrUTC(input, format, locale, strict, true).utc(); + } + + function defaultParsingFlags() { + // We need to deep clone this object. + return { + empty: false, + unusedTokens: [], + unusedInput: [], + overflow: -2, + charsLeftOver: 0, + nullInput: false, + invalidEra: null, + invalidMonth: null, + invalidFormat: false, + userInvalidated: false, + iso: false, + parsedDateParts: [], + era: null, + meridiem: null, + rfc2822: false, + weekdayMismatch: false, + }; + } + + function getParsingFlags(m) { + if (m._pf == null) { + m._pf = defaultParsingFlags(); + } + return m._pf; + } + + var some; + if (Array.prototype.some) { + some = Array.prototype.some; + } else { + some = function (fun) { + var t = Object(this), + len = t.length >>> 0, + i; + + for (i = 0; i < len; i++) { + if (i in t && fun.call(this, t[i], i, t)) { + return true; + } + } + + return false; + }; + } + + function isValid(m) { + if (m._isValid == null) { + var flags = getParsingFlags(m), + parsedParts = some.call(flags.parsedDateParts, function (i) { + return i != null; + }), + isNowValid = + !isNaN(m._d.getTime()) && + flags.overflow < 0 && + !flags.empty && + !flags.invalidEra && + !flags.invalidMonth && + !flags.invalidWeekday && + !flags.weekdayMismatch && + !flags.nullInput && + !flags.invalidFormat && + !flags.userInvalidated && + (!flags.meridiem || (flags.meridiem && parsedParts)); + + if (m._strict) { + isNowValid = + isNowValid && + flags.charsLeftOver === 0 && + flags.unusedTokens.length === 0 && + flags.bigHour === undefined; + } + + if (Object.isFrozen == null || !Object.isFrozen(m)) { + m._isValid = isNowValid; + } else { + return isNowValid; + } + } + return m._isValid; + } + + function createInvalid(flags) { + var m = createUTC(NaN); + if (flags != null) { + extend(getParsingFlags(m), flags); + } else { + getParsingFlags(m).userInvalidated = true; + } + + return m; + } + + // Plugins that add properties should also add the key here (null value), + // so we can properly clone ourselves. + var momentProperties = (hooks.momentProperties = []), + updateInProgress = false; + + function copyConfig(to, from) { + var i, + prop, + val, + momentPropertiesLen = momentProperties.length; + + if (!isUndefined(from._isAMomentObject)) { + to._isAMomentObject = from._isAMomentObject; + } + if (!isUndefined(from._i)) { + to._i = from._i; + } + if (!isUndefined(from._f)) { + to._f = from._f; + } + if (!isUndefined(from._l)) { + to._l = from._l; + } + if (!isUndefined(from._strict)) { + to._strict = from._strict; + } + if (!isUndefined(from._tzm)) { + to._tzm = from._tzm; + } + if (!isUndefined(from._isUTC)) { + to._isUTC = from._isUTC; + } + if (!isUndefined(from._offset)) { + to._offset = from._offset; + } + if (!isUndefined(from._pf)) { + to._pf = getParsingFlags(from); + } + if (!isUndefined(from._locale)) { + to._locale = from._locale; + } + + if (momentPropertiesLen > 0) { + for (i = 0; i < momentPropertiesLen; i++) { + prop = momentProperties[i]; + val = from[prop]; + if (!isUndefined(val)) { + to[prop] = val; + } + } + } + + return to; + } + + // Moment prototype object + function Moment(config) { + copyConfig(this, config); + this._d = new Date(config._d != null ? config._d.getTime() : NaN); + if (!this.isValid()) { + this._d = new Date(NaN); + } + // Prevent infinite loop in case updateOffset creates new moment + // objects. + if (updateInProgress === false) { + updateInProgress = true; + hooks.updateOffset(this); + updateInProgress = false; + } + } + + function isMoment(obj) { + return ( + obj instanceof Moment || (obj != null && obj._isAMomentObject != null) + ); + } + + function warn(msg) { + if ( + hooks.suppressDeprecationWarnings === false && + typeof console !== 'undefined' && + console.warn + ) { + console.warn('Deprecation warning: ' + msg); + } + } + + function deprecate(msg, fn) { + var firstTime = true; + + return extend(function () { + if (hooks.deprecationHandler != null) { + hooks.deprecationHandler(null, msg); + } + if (firstTime) { + var args = [], + arg, + i, + key, + argLen = arguments.length; + for (i = 0; i < argLen; i++) { + arg = ''; + if (typeof arguments[i] === 'object') { + arg += '\n[' + i + '] '; + for (key in arguments[0]) { + if (hasOwnProp(arguments[0], key)) { + arg += key + ': ' + arguments[0][key] + ', '; + } + } + arg = arg.slice(0, -2); // Remove trailing comma and space + } else { + arg = arguments[i]; + } + args.push(arg); + } + warn( + msg + + '\nArguments: ' + + Array.prototype.slice.call(args).join('') + + '\n' + + new Error().stack + ); + firstTime = false; + } + return fn.apply(this, arguments); + }, fn); + } + + var deprecations = {}; + + function deprecateSimple(name, msg) { + if (hooks.deprecationHandler != null) { + hooks.deprecationHandler(name, msg); + } + if (!deprecations[name]) { + warn(msg); + deprecations[name] = true; + } + } + + hooks.suppressDeprecationWarnings = false; + hooks.deprecationHandler = null; + + function isFunction(input) { + return ( + (typeof Function !== 'undefined' && input instanceof Function) || + Object.prototype.toString.call(input) === '[object Function]' + ); + } + + function set(config) { + var prop, i; + for (i in config) { + if (hasOwnProp(config, i)) { + prop = config[i]; + if (isFunction(prop)) { + this[i] = prop; + } else { + this['_' + i] = prop; + } + } + } + this._config = config; + // Lenient ordinal parsing accepts just a number in addition to + // number + (possibly) stuff coming from _dayOfMonthOrdinalParse. + // TODO: Remove "ordinalParse" fallback in next major release. + this._dayOfMonthOrdinalParseLenient = new RegExp( + (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + + '|' + + /\d{1,2}/.source + ); + } + + function mergeConfigs(parentConfig, childConfig) { + var res = extend({}, parentConfig), + prop; + for (prop in childConfig) { + if (hasOwnProp(childConfig, prop)) { + if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) { + res[prop] = {}; + extend(res[prop], parentConfig[prop]); + extend(res[prop], childConfig[prop]); + } else if (childConfig[prop] != null) { + res[prop] = childConfig[prop]; + } else { + delete res[prop]; + } + } + } + for (prop in parentConfig) { + if ( + hasOwnProp(parentConfig, prop) && + !hasOwnProp(childConfig, prop) && + isObject(parentConfig[prop]) + ) { + // make sure changes to properties don't modify parent config + res[prop] = extend({}, res[prop]); + } + } + return res; + } + + function Locale(config) { + if (config != null) { + this.set(config); + } + } + + var keys; + + if (Object.keys) { + keys = Object.keys; + } else { + keys = function (obj) { + var i, + res = []; + for (i in obj) { + if (hasOwnProp(obj, i)) { + res.push(i); + } + } + return res; + }; + } + + var defaultCalendar = { + sameDay: '[Today at] LT', + nextDay: '[Tomorrow at] LT', + nextWeek: 'dddd [at] LT', + lastDay: '[Yesterday at] LT', + lastWeek: '[Last] dddd [at] LT', + sameElse: 'L', + }; + + function calendar(key, mom, now) { + var output = this._calendar[key] || this._calendar['sameElse']; + return isFunction(output) ? output.call(mom, now) : output; + } + + function zeroFill(number, targetLength, forceSign) { + var absNumber = '' + Math.abs(number), + zerosToFill = targetLength - absNumber.length, + sign = number >= 0; + return ( + (sign ? (forceSign ? '+' : '') : '-') + + Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + + absNumber + ); + } + + var formattingTokens = + /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g, + localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, + formatFunctions = {}, + formatTokenFunctions = {}; + + // token: 'M' + // padded: ['MM', 2] + // ordinal: 'Mo' + // callback: function () { this.month() + 1 } + function addFormatToken(token, padded, ordinal, callback) { + var func = callback; + if (typeof callback === 'string') { + func = function () { + return this[callback](); + }; + } + if (token) { + formatTokenFunctions[token] = func; + } + if (padded) { + formatTokenFunctions[padded[0]] = function () { + return zeroFill(func.apply(this, arguments), padded[1], padded[2]); + }; + } + if (ordinal) { + formatTokenFunctions[ordinal] = function () { + return this.localeData().ordinal( + func.apply(this, arguments), + token + ); + }; + } + } + + function removeFormattingTokens(input) { + if (input.match(/\[[\s\S]/)) { + return input.replace(/^\[|\]$/g, ''); + } + return input.replace(/\\/g, ''); + } + + function makeFormatFunction(format) { + var array = format.match(formattingTokens), + i, + length; + + for (i = 0, length = array.length; i < length; i++) { + if (formatTokenFunctions[array[i]]) { + array[i] = formatTokenFunctions[array[i]]; + } else { + array[i] = removeFormattingTokens(array[i]); + } + } + + return function (mom) { + var output = '', + i; + for (i = 0; i < length; i++) { + output += isFunction(array[i]) + ? array[i].call(mom, format) + : array[i]; + } + return output; + }; + } + + // format date using native date object + function formatMoment(m, format) { + if (!m.isValid()) { + return m.localeData().invalidDate(); + } + + format = expandFormat(format, m.localeData()); + formatFunctions[format] = + formatFunctions[format] || makeFormatFunction(format); + + return formatFunctions[format](m); + } + + function expandFormat(format, locale) { + var i = 5; + + function replaceLongDateFormatTokens(input) { + return locale.longDateFormat(input) || input; + } + + localFormattingTokens.lastIndex = 0; + while (i >= 0 && localFormattingTokens.test(format)) { + format = format.replace( + localFormattingTokens, + replaceLongDateFormatTokens + ); + localFormattingTokens.lastIndex = 0; + i -= 1; + } + + return format; + } + + var defaultLongDateFormat = { + LTS: 'h:mm:ss A', + LT: 'h:mm A', + L: 'MM/DD/YYYY', + LL: 'MMMM D, YYYY', + LLL: 'MMMM D, YYYY h:mm A', + LLLL: 'dddd, MMMM D, YYYY h:mm A', + }; + + function longDateFormat(key) { + var format = this._longDateFormat[key], + formatUpper = this._longDateFormat[key.toUpperCase()]; + + if (format || !formatUpper) { + return format; + } + + this._longDateFormat[key] = formatUpper + .match(formattingTokens) + .map(function (tok) { + if ( + tok === 'MMMM' || + tok === 'MM' || + tok === 'DD' || + tok === 'dddd' + ) { + return tok.slice(1); + } + return tok; + }) + .join(''); + + return this._longDateFormat[key]; + } + + var defaultInvalidDate = 'Invalid date'; + + function invalidDate() { + return this._invalidDate; + } + + var defaultOrdinal = '%d', + defaultDayOfMonthOrdinalParse = /\d{1,2}/; + + function ordinal(number) { + return this._ordinal.replace('%d', number); + } + + var defaultRelativeTime = { + future: 'in %s', + past: '%s ago', + s: 'a few seconds', + ss: '%d seconds', + m: 'a minute', + mm: '%d minutes', + h: 'an hour', + hh: '%d hours', + d: 'a day', + dd: '%d days', + w: 'a week', + ww: '%d weeks', + M: 'a month', + MM: '%d months', + y: 'a year', + yy: '%d years', + }; + + function relativeTime(number, withoutSuffix, string, isFuture) { + var output = this._relativeTime[string]; + return isFunction(output) + ? output(number, withoutSuffix, string, isFuture) + : output.replace(/%d/i, number); + } + + function pastFuture(diff, output) { + var format = this._relativeTime[diff > 0 ? 'future' : 'past']; + return isFunction(format) ? format(output) : format.replace(/%s/i, output); + } + + var aliases = {}; + + function addUnitAlias(unit, shorthand) { + var lowerCase = unit.toLowerCase(); + aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit; + } + + function normalizeUnits(units) { + return typeof units === 'string' + ? aliases[units] || aliases[units.toLowerCase()] + : undefined; + } + + function normalizeObjectUnits(inputObject) { + var normalizedInput = {}, + normalizedProp, + prop; + + for (prop in inputObject) { + if (hasOwnProp(inputObject, prop)) { + normalizedProp = normalizeUnits(prop); + if (normalizedProp) { + normalizedInput[normalizedProp] = inputObject[prop]; + } + } + } + + return normalizedInput; + } + + var priorities = {}; + + function addUnitPriority(unit, priority) { + priorities[unit] = priority; + } + + function getPrioritizedUnits(unitsObj) { + var units = [], + u; + for (u in unitsObj) { + if (hasOwnProp(unitsObj, u)) { + units.push({ unit: u, priority: priorities[u] }); + } + } + units.sort(function (a, b) { + return a.priority - b.priority; + }); + return units; + } + + function isLeapYear(year) { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; + } + + function absFloor(number) { + if (number < 0) { + // -0 -> 0 + return Math.ceil(number) || 0; + } else { + return Math.floor(number); + } + } + + function toInt(argumentForCoercion) { + var coercedNumber = +argumentForCoercion, + value = 0; + + if (coercedNumber !== 0 && isFinite(coercedNumber)) { + value = absFloor(coercedNumber); + } + + return value; + } + + function makeGetSet(unit, keepTime) { + return function (value) { + if (value != null) { + set$1(this, unit, value); + hooks.updateOffset(this, keepTime); + return this; + } else { + return get(this, unit); + } + }; + } + + function get(mom, unit) { + return mom.isValid() + ? mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() + : NaN; + } + + function set$1(mom, unit, value) { + if (mom.isValid() && !isNaN(value)) { + if ( + unit === 'FullYear' && + isLeapYear(mom.year()) && + mom.month() === 1 && + mom.date() === 29 + ) { + value = toInt(value); + mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit]( + value, + mom.month(), + daysInMonth(value, mom.month()) + ); + } else { + mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value); + } + } + } + + // MOMENTS + + function stringGet(units) { + units = normalizeUnits(units); + if (isFunction(this[units])) { + return this[units](); + } + return this; + } + + function stringSet(units, value) { + if (typeof units === 'object') { + units = normalizeObjectUnits(units); + var prioritized = getPrioritizedUnits(units), + i, + prioritizedLen = prioritized.length; + for (i = 0; i < prioritizedLen; i++) { + this[prioritized[i].unit](units[prioritized[i].unit]); + } + } else { + units = normalizeUnits(units); + if (isFunction(this[units])) { + return this[units](value); + } + } + return this; + } + + var match1 = /\d/, // 0 - 9 + match2 = /\d\d/, // 00 - 99 + match3 = /\d{3}/, // 000 - 999 + match4 = /\d{4}/, // 0000 - 9999 + match6 = /[+-]?\d{6}/, // -999999 - 999999 + match1to2 = /\d\d?/, // 0 - 99 + match3to4 = /\d\d\d\d?/, // 999 - 9999 + match5to6 = /\d\d\d\d\d\d?/, // 99999 - 999999 + match1to3 = /\d{1,3}/, // 0 - 999 + match1to4 = /\d{1,4}/, // 0 - 9999 + match1to6 = /[+-]?\d{1,6}/, // -999999 - 999999 + matchUnsigned = /\d+/, // 0 - inf + matchSigned = /[+-]?\d+/, // -inf - inf + matchOffset = /Z|[+-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z + matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi, // +00 -00 +00:00 -00:00 +0000 -0000 or Z + matchTimestamp = /[+-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123 + // any word (or two) characters or numbers including two/three word month in arabic. + // includes scottish gaelic two word and hyphenated months + 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, + regexes; + + regexes = {}; + + function addRegexToken(token, regex, strictRegex) { + regexes[token] = isFunction(regex) + ? regex + : function (isStrict, localeData) { + return isStrict && strictRegex ? strictRegex : regex; + }; + } + + function getParseRegexForToken(token, config) { + if (!hasOwnProp(regexes, token)) { + return new RegExp(unescapeFormat(token)); + } + + return regexes[token](config._strict, config._locale); + } + + // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript + function unescapeFormat(s) { + return regexEscape( + s + .replace('\\', '') + .replace( + /\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, + function (matched, p1, p2, p3, p4) { + return p1 || p2 || p3 || p4; + } + ) + ); + } + + function regexEscape(s) { + return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); + } + + var tokens = {}; + + function addParseToken(token, callback) { + var i, + func = callback, + tokenLen; + if (typeof token === 'string') { + token = [token]; + } + if (isNumber(callback)) { + func = function (input, array) { + array[callback] = toInt(input); + }; + } + tokenLen = token.length; + for (i = 0; i < tokenLen; i++) { + tokens[token[i]] = func; + } + } + + function addWeekParseToken(token, callback) { + addParseToken(token, function (input, array, config, token) { + config._w = config._w || {}; + callback(input, config._w, config, token); + }); + } + + function addTimeToArrayFromToken(token, input, config) { + if (input != null && hasOwnProp(tokens, token)) { + tokens[token](input, config._a, config, token); + } + } + + var YEAR = 0, + MONTH = 1, + DATE = 2, + HOUR = 3, + MINUTE = 4, + SECOND = 5, + MILLISECOND = 6, + WEEK = 7, + WEEKDAY = 8; + + function mod(n, x) { + return ((n % x) + x) % x; + } + + var indexOf; + + if (Array.prototype.indexOf) { + indexOf = Array.prototype.indexOf; + } else { + indexOf = function (o) { + // I know + var i; + for (i = 0; i < this.length; ++i) { + if (this[i] === o) { + return i; + } + } + return -1; + }; + } + + function daysInMonth(year, month) { + if (isNaN(year) || isNaN(month)) { + return NaN; + } + var modMonth = mod(month, 12); + year += (month - modMonth) / 12; + return modMonth === 1 + ? isLeapYear(year) + ? 29 + : 28 + : 31 - ((modMonth % 7) % 2); + } + + // FORMATTING + + addFormatToken('M', ['MM', 2], 'Mo', function () { + return this.month() + 1; + }); + + addFormatToken('MMM', 0, 0, function (format) { + return this.localeData().monthsShort(this, format); + }); + + addFormatToken('MMMM', 0, 0, function (format) { + return this.localeData().months(this, format); + }); + + // ALIASES + + addUnitAlias('month', 'M'); + + // PRIORITY + + addUnitPriority('month', 8); + + // PARSING + + addRegexToken('M', match1to2); + addRegexToken('MM', match1to2, match2); + addRegexToken('MMM', function (isStrict, locale) { + return locale.monthsShortRegex(isStrict); + }); + addRegexToken('MMMM', function (isStrict, locale) { + return locale.monthsRegex(isStrict); + }); + + addParseToken(['M', 'MM'], function (input, array) { + array[MONTH] = toInt(input) - 1; + }); + + addParseToken(['MMM', 'MMMM'], function (input, array, config, token) { + var month = config._locale.monthsParse(input, token, config._strict); + // if we didn't find a month name, mark the date as invalid. + if (month != null) { + array[MONTH] = month; + } else { + getParsingFlags(config).invalidMonth = input; + } + }); + + // LOCALES + + var defaultLocaleMonths = + 'January_February_March_April_May_June_July_August_September_October_November_December'.split( + '_' + ), + defaultLocaleMonthsShort = + 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), + MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/, + defaultMonthsShortRegex = matchWord, + defaultMonthsRegex = matchWord; + + function localeMonths(m, format) { + if (!m) { + return isArray(this._months) + ? this._months + : this._months['standalone']; + } + return isArray(this._months) + ? this._months[m.month()] + : this._months[ + (this._months.isFormat || MONTHS_IN_FORMAT).test(format) + ? 'format' + : 'standalone' + ][m.month()]; + } + + function localeMonthsShort(m, format) { + if (!m) { + return isArray(this._monthsShort) + ? this._monthsShort + : this._monthsShort['standalone']; + } + return isArray(this._monthsShort) + ? this._monthsShort[m.month()] + : this._monthsShort[ + MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone' + ][m.month()]; + } + + function handleStrictParse(monthName, format, strict) { + var i, + ii, + mom, + llc = monthName.toLocaleLowerCase(); + if (!this._monthsParse) { + // this is not used + this._monthsParse = []; + this._longMonthsParse = []; + this._shortMonthsParse = []; + for (i = 0; i < 12; ++i) { + mom = createUTC([2000, i]); + this._shortMonthsParse[i] = this.monthsShort( + mom, + '' + ).toLocaleLowerCase(); + this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase(); + } + } + + if (strict) { + if (format === 'MMM') { + ii = indexOf.call(this._shortMonthsParse, llc); + return ii !== -1 ? ii : null; + } else { + ii = indexOf.call(this._longMonthsParse, llc); + return ii !== -1 ? ii : null; + } + } else { + if (format === 'MMM') { + ii = indexOf.call(this._shortMonthsParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._longMonthsParse, llc); + return ii !== -1 ? ii : null; + } else { + ii = indexOf.call(this._longMonthsParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._shortMonthsParse, llc); + return ii !== -1 ? ii : null; + } + } + } + + function localeMonthsParse(monthName, format, strict) { + var i, mom, regex; + + if (this._monthsParseExact) { + return handleStrictParse.call(this, monthName, format, strict); + } + + if (!this._monthsParse) { + this._monthsParse = []; + this._longMonthsParse = []; + this._shortMonthsParse = []; + } + + // TODO: add sorting + // Sorting makes sure if one month (or abbr) is a prefix of another + // see sorting in computeMonthsParse + for (i = 0; i < 12; i++) { + // make the regex if we don't have it already + mom = createUTC([2000, i]); + if (strict && !this._longMonthsParse[i]) { + this._longMonthsParse[i] = new RegExp( + '^' + this.months(mom, '').replace('.', '') + '$', + 'i' + ); + this._shortMonthsParse[i] = new RegExp( + '^' + this.monthsShort(mom, '').replace('.', '') + '$', + 'i' + ); + } + if (!strict && !this._monthsParse[i]) { + regex = + '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); + this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); + } + // test the regex + if ( + strict && + format === 'MMMM' && + this._longMonthsParse[i].test(monthName) + ) { + return i; + } else if ( + strict && + format === 'MMM' && + this._shortMonthsParse[i].test(monthName) + ) { + return i; + } else if (!strict && this._monthsParse[i].test(monthName)) { + return i; + } + } + } + + // MOMENTS + + function setMonth(mom, value) { + var dayOfMonth; + + if (!mom.isValid()) { + // No op + return mom; + } + + if (typeof value === 'string') { + if (/^\d+$/.test(value)) { + value = toInt(value); + } else { + value = mom.localeData().monthsParse(value); + // TODO: Another silent failure? + if (!isNumber(value)) { + return mom; + } + } + } + + dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); + mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth); + return mom; + } + + function getSetMonth(value) { + if (value != null) { + setMonth(this, value); + hooks.updateOffset(this, true); + return this; + } else { + return get(this, 'Month'); + } + } + + function getDaysInMonth() { + return daysInMonth(this.year(), this.month()); + } + + function monthsShortRegex(isStrict) { + if (this._monthsParseExact) { + if (!hasOwnProp(this, '_monthsRegex')) { + computeMonthsParse.call(this); + } + if (isStrict) { + return this._monthsShortStrictRegex; + } else { + return this._monthsShortRegex; + } + } else { + if (!hasOwnProp(this, '_monthsShortRegex')) { + this._monthsShortRegex = defaultMonthsShortRegex; + } + return this._monthsShortStrictRegex && isStrict + ? this._monthsShortStrictRegex + : this._monthsShortRegex; + } + } + + function monthsRegex(isStrict) { + if (this._monthsParseExact) { + if (!hasOwnProp(this, '_monthsRegex')) { + computeMonthsParse.call(this); + } + if (isStrict) { + return this._monthsStrictRegex; + } else { + return this._monthsRegex; + } + } else { + if (!hasOwnProp(this, '_monthsRegex')) { + this._monthsRegex = defaultMonthsRegex; + } + return this._monthsStrictRegex && isStrict + ? this._monthsStrictRegex + : this._monthsRegex; + } + } + + function computeMonthsParse() { + function cmpLenRev(a, b) { + return b.length - a.length; + } + + var shortPieces = [], + longPieces = [], + mixedPieces = [], + i, + mom; + for (i = 0; i < 12; i++) { + // make the regex if we don't have it already + mom = createUTC([2000, i]); + shortPieces.push(this.monthsShort(mom, '')); + longPieces.push(this.months(mom, '')); + mixedPieces.push(this.months(mom, '')); + mixedPieces.push(this.monthsShort(mom, '')); + } + // Sorting makes sure if one month (or abbr) is a prefix of another it + // will match the longer piece. + shortPieces.sort(cmpLenRev); + longPieces.sort(cmpLenRev); + mixedPieces.sort(cmpLenRev); + for (i = 0; i < 12; i++) { + shortPieces[i] = regexEscape(shortPieces[i]); + longPieces[i] = regexEscape(longPieces[i]); + } + for (i = 0; i < 24; i++) { + mixedPieces[i] = regexEscape(mixedPieces[i]); + } + + this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); + this._monthsShortRegex = this._monthsRegex; + this._monthsStrictRegex = new RegExp( + '^(' + longPieces.join('|') + ')', + 'i' + ); + this._monthsShortStrictRegex = new RegExp( + '^(' + shortPieces.join('|') + ')', + 'i' + ); + } + + // FORMATTING + + addFormatToken('Y', 0, 0, function () { + var y = this.year(); + return y <= 9999 ? zeroFill(y, 4) : '+' + y; + }); + + addFormatToken(0, ['YY', 2], 0, function () { + return this.year() % 100; + }); + + addFormatToken(0, ['YYYY', 4], 0, 'year'); + addFormatToken(0, ['YYYYY', 5], 0, 'year'); + addFormatToken(0, ['YYYYYY', 6, true], 0, 'year'); + + // ALIASES + + addUnitAlias('year', 'y'); + + // PRIORITIES + + addUnitPriority('year', 1); + + // PARSING + + addRegexToken('Y', matchSigned); + addRegexToken('YY', match1to2, match2); + addRegexToken('YYYY', match1to4, match4); + addRegexToken('YYYYY', match1to6, match6); + addRegexToken('YYYYYY', match1to6, match6); + + addParseToken(['YYYYY', 'YYYYYY'], YEAR); + addParseToken('YYYY', function (input, array) { + array[YEAR] = + input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input); + }); + addParseToken('YY', function (input, array) { + array[YEAR] = hooks.parseTwoDigitYear(input); + }); + addParseToken('Y', function (input, array) { + array[YEAR] = parseInt(input, 10); + }); + + // HELPERS + + function daysInYear(year) { + return isLeapYear(year) ? 366 : 365; + } + + // HOOKS + + hooks.parseTwoDigitYear = function (input) { + return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); + }; + + // MOMENTS + + var getSetYear = makeGetSet('FullYear', true); + + function getIsLeapYear() { + return isLeapYear(this.year()); + } + + function createDate(y, m, d, h, M, s, ms) { + // can't just apply() to create a date: + // https://stackoverflow.com/q/181348 + var date; + // the date constructor remaps years 0-99 to 1900-1999 + if (y < 100 && y >= 0) { + // preserve leap years using a full 400 year cycle, then reset + date = new Date(y + 400, m, d, h, M, s, ms); + if (isFinite(date.getFullYear())) { + date.setFullYear(y); + } + } else { + date = new Date(y, m, d, h, M, s, ms); + } + + return date; + } + + function createUTCDate(y) { + var date, args; + // the Date.UTC function remaps years 0-99 to 1900-1999 + if (y < 100 && y >= 0) { + args = Array.prototype.slice.call(arguments); + // preserve leap years using a full 400 year cycle, then reset + args[0] = y + 400; + date = new Date(Date.UTC.apply(null, args)); + if (isFinite(date.getUTCFullYear())) { + date.setUTCFullYear(y); + } + } else { + date = new Date(Date.UTC.apply(null, arguments)); + } + + return date; + } + + // start-of-first-week - start-of-year + function firstWeekOffset(year, dow, doy) { + var // first-week day -- which january is always in the first week (4 for iso, 1 for other) + fwd = 7 + dow - doy, + // first-week day local weekday -- which local weekday is fwd + fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7; + + return -fwdlw + fwd - 1; + } + + // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday + function dayOfYearFromWeeks(year, week, weekday, dow, doy) { + var localWeekday = (7 + weekday - dow) % 7, + weekOffset = firstWeekOffset(year, dow, doy), + dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset, + resYear, + resDayOfYear; + + if (dayOfYear <= 0) { + resYear = year - 1; + resDayOfYear = daysInYear(resYear) + dayOfYear; + } else if (dayOfYear > daysInYear(year)) { + resYear = year + 1; + resDayOfYear = dayOfYear - daysInYear(year); + } else { + resYear = year; + resDayOfYear = dayOfYear; + } + + return { + year: resYear, + dayOfYear: resDayOfYear, + }; + } + + function weekOfYear(mom, dow, doy) { + var weekOffset = firstWeekOffset(mom.year(), dow, doy), + week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1, + resWeek, + resYear; + + if (week < 1) { + resYear = mom.year() - 1; + resWeek = week + weeksInYear(resYear, dow, doy); + } else if (week > weeksInYear(mom.year(), dow, doy)) { + resWeek = week - weeksInYear(mom.year(), dow, doy); + resYear = mom.year() + 1; + } else { + resYear = mom.year(); + resWeek = week; + } + + return { + week: resWeek, + year: resYear, + }; + } + + function weeksInYear(year, dow, doy) { + var weekOffset = firstWeekOffset(year, dow, doy), + weekOffsetNext = firstWeekOffset(year + 1, dow, doy); + return (daysInYear(year) - weekOffset + weekOffsetNext) / 7; + } + + // FORMATTING + + addFormatToken('w', ['ww', 2], 'wo', 'week'); + addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek'); + + // ALIASES + + addUnitAlias('week', 'w'); + addUnitAlias('isoWeek', 'W'); + + // PRIORITIES + + addUnitPriority('week', 5); + addUnitPriority('isoWeek', 5); + + // PARSING + + addRegexToken('w', match1to2); + addRegexToken('ww', match1to2, match2); + addRegexToken('W', match1to2); + addRegexToken('WW', match1to2, match2); + + addWeekParseToken( + ['w', 'ww', 'W', 'WW'], + function (input, week, config, token) { + week[token.substr(0, 1)] = toInt(input); + } + ); + + // HELPERS + + // LOCALES + + function localeWeek(mom) { + return weekOfYear(mom, this._week.dow, this._week.doy).week; + } + + var defaultLocaleWeek = { + dow: 0, // Sunday is the first day of the week. + doy: 6, // The week that contains Jan 6th is the first week of the year. + }; + + function localeFirstDayOfWeek() { + return this._week.dow; + } + + function localeFirstDayOfYear() { + return this._week.doy; + } + + // MOMENTS + + function getSetWeek(input) { + var week = this.localeData().week(this); + return input == null ? week : this.add((input - week) * 7, 'd'); + } + + function getSetISOWeek(input) { + var week = weekOfYear(this, 1, 4).week; + return input == null ? week : this.add((input - week) * 7, 'd'); + } + + // FORMATTING + + addFormatToken('d', 0, 'do', 'day'); + + addFormatToken('dd', 0, 0, function (format) { + return this.localeData().weekdaysMin(this, format); + }); + + addFormatToken('ddd', 0, 0, function (format) { + return this.localeData().weekdaysShort(this, format); + }); + + addFormatToken('dddd', 0, 0, function (format) { + return this.localeData().weekdays(this, format); + }); + + addFormatToken('e', 0, 0, 'weekday'); + addFormatToken('E', 0, 0, 'isoWeekday'); + + // ALIASES + + addUnitAlias('day', 'd'); + addUnitAlias('weekday', 'e'); + addUnitAlias('isoWeekday', 'E'); + + // PRIORITY + addUnitPriority('day', 11); + addUnitPriority('weekday', 11); + addUnitPriority('isoWeekday', 11); + + // PARSING + + addRegexToken('d', match1to2); + addRegexToken('e', match1to2); + addRegexToken('E', match1to2); + addRegexToken('dd', function (isStrict, locale) { + return locale.weekdaysMinRegex(isStrict); + }); + addRegexToken('ddd', function (isStrict, locale) { + return locale.weekdaysShortRegex(isStrict); + }); + addRegexToken('dddd', function (isStrict, locale) { + return locale.weekdaysRegex(isStrict); + }); + + addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) { + var weekday = config._locale.weekdaysParse(input, token, config._strict); + // if we didn't get a weekday name, mark the date as invalid + if (weekday != null) { + week.d = weekday; + } else { + getParsingFlags(config).invalidWeekday = input; + } + }); + + addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) { + week[token] = toInt(input); + }); + + // HELPERS + + function parseWeekday(input, locale) { + if (typeof input !== 'string') { + return input; + } + + if (!isNaN(input)) { + return parseInt(input, 10); + } + + input = locale.weekdaysParse(input); + if (typeof input === 'number') { + return input; + } + + return null; + } + + function parseIsoWeekday(input, locale) { + if (typeof input === 'string') { + return locale.weekdaysParse(input) % 7 || 7; + } + return isNaN(input) ? null : input; + } + + // LOCALES + function shiftWeekdays(ws, n) { + return ws.slice(n, 7).concat(ws.slice(0, n)); + } + + var defaultLocaleWeekdays = + 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), + defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), + defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), + defaultWeekdaysRegex = matchWord, + defaultWeekdaysShortRegex = matchWord, + defaultWeekdaysMinRegex = matchWord; + + function localeWeekdays(m, format) { + var weekdays = isArray(this._weekdays) + ? this._weekdays + : this._weekdays[ + m && m !== true && this._weekdays.isFormat.test(format) + ? 'format' + : 'standalone' + ]; + return m === true + ? shiftWeekdays(weekdays, this._week.dow) + : m + ? weekdays[m.day()] + : weekdays; + } + + function localeWeekdaysShort(m) { + return m === true + ? shiftWeekdays(this._weekdaysShort, this._week.dow) + : m + ? this._weekdaysShort[m.day()] + : this._weekdaysShort; + } + + function localeWeekdaysMin(m) { + return m === true + ? shiftWeekdays(this._weekdaysMin, this._week.dow) + : m + ? this._weekdaysMin[m.day()] + : this._weekdaysMin; + } + + function handleStrictParse$1(weekdayName, format, strict) { + var i, + ii, + mom, + llc = weekdayName.toLocaleLowerCase(); + if (!this._weekdaysParse) { + this._weekdaysParse = []; + this._shortWeekdaysParse = []; + this._minWeekdaysParse = []; + + for (i = 0; i < 7; ++i) { + mom = createUTC([2000, 1]).day(i); + this._minWeekdaysParse[i] = this.weekdaysMin( + mom, + '' + ).toLocaleLowerCase(); + this._shortWeekdaysParse[i] = this.weekdaysShort( + mom, + '' + ).toLocaleLowerCase(); + this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase(); + } + } + + if (strict) { + if (format === 'dddd') { + ii = indexOf.call(this._weekdaysParse, llc); + return ii !== -1 ? ii : null; + } else if (format === 'ddd') { + ii = indexOf.call(this._shortWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } else { + ii = indexOf.call(this._minWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } + } else { + if (format === 'dddd') { + ii = indexOf.call(this._weekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._shortWeekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._minWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } else if (format === 'ddd') { + ii = indexOf.call(this._shortWeekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._weekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._minWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } else { + ii = indexOf.call(this._minWeekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._weekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf.call(this._shortWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } + } + } + + function localeWeekdaysParse(weekdayName, format, strict) { + var i, mom, regex; + + if (this._weekdaysParseExact) { + return handleStrictParse$1.call(this, weekdayName, format, strict); + } + + if (!this._weekdaysParse) { + this._weekdaysParse = []; + this._minWeekdaysParse = []; + this._shortWeekdaysParse = []; + this._fullWeekdaysParse = []; + } + + for (i = 0; i < 7; i++) { + // make the regex if we don't have it already + + mom = createUTC([2000, 1]).day(i); + if (strict && !this._fullWeekdaysParse[i]) { + this._fullWeekdaysParse[i] = new RegExp( + '^' + this.weekdays(mom, '').replace('.', '\\.?') + '$', + 'i' + ); + this._shortWeekdaysParse[i] = new RegExp( + '^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$', + 'i' + ); + this._minWeekdaysParse[i] = new RegExp( + '^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$', + 'i' + ); + } + if (!this._weekdaysParse[i]) { + regex = + '^' + + this.weekdays(mom, '') + + '|^' + + this.weekdaysShort(mom, '') + + '|^' + + this.weekdaysMin(mom, ''); + this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); + } + // test the regex + if ( + strict && + format === 'dddd' && + this._fullWeekdaysParse[i].test(weekdayName) + ) { + return i; + } else if ( + strict && + format === 'ddd' && + this._shortWeekdaysParse[i].test(weekdayName) + ) { + return i; + } else if ( + strict && + format === 'dd' && + this._minWeekdaysParse[i].test(weekdayName) + ) { + return i; + } else if (!strict && this._weekdaysParse[i].test(weekdayName)) { + return i; + } + } + } + + // MOMENTS + + function getSetDayOfWeek(input) { + if (!this.isValid()) { + return input != null ? this : NaN; + } + var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); + if (input != null) { + input = parseWeekday(input, this.localeData()); + return this.add(input - day, 'd'); + } else { + return day; + } + } + + function getSetLocaleDayOfWeek(input) { + if (!this.isValid()) { + return input != null ? this : NaN; + } + var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; + return input == null ? weekday : this.add(input - weekday, 'd'); + } + + function getSetISODayOfWeek(input) { + if (!this.isValid()) { + return input != null ? this : NaN; + } + + // behaves the same as moment#day except + // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) + // as a setter, sunday should belong to the previous week. + + if (input != null) { + var weekday = parseIsoWeekday(input, this.localeData()); + return this.day(this.day() % 7 ? weekday : weekday - 7); + } else { + return this.day() || 7; + } + } + + function weekdaysRegex(isStrict) { + if (this._weekdaysParseExact) { + if (!hasOwnProp(this, '_weekdaysRegex')) { + computeWeekdaysParse.call(this); + } + if (isStrict) { + return this._weekdaysStrictRegex; + } else { + return this._weekdaysRegex; + } + } else { + if (!hasOwnProp(this, '_weekdaysRegex')) { + this._weekdaysRegex = defaultWeekdaysRegex; + } + return this._weekdaysStrictRegex && isStrict + ? this._weekdaysStrictRegex + : this._weekdaysRegex; + } + } + + function weekdaysShortRegex(isStrict) { + if (this._weekdaysParseExact) { + if (!hasOwnProp(this, '_weekdaysRegex')) { + computeWeekdaysParse.call(this); + } + if (isStrict) { + return this._weekdaysShortStrictRegex; + } else { + return this._weekdaysShortRegex; + } + } else { + if (!hasOwnProp(this, '_weekdaysShortRegex')) { + this._weekdaysShortRegex = defaultWeekdaysShortRegex; + } + return this._weekdaysShortStrictRegex && isStrict + ? this._weekdaysShortStrictRegex + : this._weekdaysShortRegex; + } + } + + function weekdaysMinRegex(isStrict) { + if (this._weekdaysParseExact) { + if (!hasOwnProp(this, '_weekdaysRegex')) { + computeWeekdaysParse.call(this); + } + if (isStrict) { + return this._weekdaysMinStrictRegex; + } else { + return this._weekdaysMinRegex; + } + } else { + if (!hasOwnProp(this, '_weekdaysMinRegex')) { + this._weekdaysMinRegex = defaultWeekdaysMinRegex; + } + return this._weekdaysMinStrictRegex && isStrict + ? this._weekdaysMinStrictRegex + : this._weekdaysMinRegex; + } + } + + function computeWeekdaysParse() { + function cmpLenRev(a, b) { + return b.length - a.length; + } + + var minPieces = [], + shortPieces = [], + longPieces = [], + mixedPieces = [], + i, + mom, + minp, + shortp, + longp; + for (i = 0; i < 7; i++) { + // make the regex if we don't have it already + mom = createUTC([2000, 1]).day(i); + minp = regexEscape(this.weekdaysMin(mom, '')); + shortp = regexEscape(this.weekdaysShort(mom, '')); + longp = regexEscape(this.weekdays(mom, '')); + minPieces.push(minp); + shortPieces.push(shortp); + longPieces.push(longp); + mixedPieces.push(minp); + mixedPieces.push(shortp); + mixedPieces.push(longp); + } + // Sorting makes sure if one weekday (or abbr) is a prefix of another it + // will match the longer piece. + minPieces.sort(cmpLenRev); + shortPieces.sort(cmpLenRev); + longPieces.sort(cmpLenRev); + mixedPieces.sort(cmpLenRev); + + this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); + this._weekdaysShortRegex = this._weekdaysRegex; + this._weekdaysMinRegex = this._weekdaysRegex; + + this._weekdaysStrictRegex = new RegExp( + '^(' + longPieces.join('|') + ')', + 'i' + ); + this._weekdaysShortStrictRegex = new RegExp( + '^(' + shortPieces.join('|') + ')', + 'i' + ); + this._weekdaysMinStrictRegex = new RegExp( + '^(' + minPieces.join('|') + ')', + 'i' + ); + } + + // FORMATTING + + function hFormat() { + return this.hours() % 12 || 12; + } + + function kFormat() { + return this.hours() || 24; + } + + addFormatToken('H', ['HH', 2], 0, 'hour'); + addFormatToken('h', ['hh', 2], 0, hFormat); + addFormatToken('k', ['kk', 2], 0, kFormat); + + addFormatToken('hmm', 0, 0, function () { + return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2); + }); + + addFormatToken('hmmss', 0, 0, function () { + return ( + '' + + hFormat.apply(this) + + zeroFill(this.minutes(), 2) + + zeroFill(this.seconds(), 2) + ); + }); + + addFormatToken('Hmm', 0, 0, function () { + return '' + this.hours() + zeroFill(this.minutes(), 2); + }); + + addFormatToken('Hmmss', 0, 0, function () { + return ( + '' + + this.hours() + + zeroFill(this.minutes(), 2) + + zeroFill(this.seconds(), 2) + ); + }); + + function meridiem(token, lowercase) { + addFormatToken(token, 0, 0, function () { + return this.localeData().meridiem( + this.hours(), + this.minutes(), + lowercase + ); + }); + } + + meridiem('a', true); + meridiem('A', false); + + // ALIASES + + addUnitAlias('hour', 'h'); + + // PRIORITY + addUnitPriority('hour', 13); + + // PARSING + + function matchMeridiem(isStrict, locale) { + return locale._meridiemParse; + } + + addRegexToken('a', matchMeridiem); + addRegexToken('A', matchMeridiem); + addRegexToken('H', match1to2); + addRegexToken('h', match1to2); + addRegexToken('k', match1to2); + addRegexToken('HH', match1to2, match2); + addRegexToken('hh', match1to2, match2); + addRegexToken('kk', match1to2, match2); + + addRegexToken('hmm', match3to4); + addRegexToken('hmmss', match5to6); + addRegexToken('Hmm', match3to4); + addRegexToken('Hmmss', match5to6); + + addParseToken(['H', 'HH'], HOUR); + addParseToken(['k', 'kk'], function (input, array, config) { + var kInput = toInt(input); + array[HOUR] = kInput === 24 ? 0 : kInput; + }); + addParseToken(['a', 'A'], function (input, array, config) { + config._isPm = config._locale.isPM(input); + config._meridiem = input; + }); + addParseToken(['h', 'hh'], function (input, array, config) { + array[HOUR] = toInt(input); + getParsingFlags(config).bigHour = true; + }); + addParseToken('hmm', function (input, array, config) { + var pos = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos)); + array[MINUTE] = toInt(input.substr(pos)); + getParsingFlags(config).bigHour = true; + }); + addParseToken('hmmss', function (input, array, config) { + var pos1 = input.length - 4, + pos2 = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos1)); + array[MINUTE] = toInt(input.substr(pos1, 2)); + array[SECOND] = toInt(input.substr(pos2)); + getParsingFlags(config).bigHour = true; + }); + addParseToken('Hmm', function (input, array, config) { + var pos = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos)); + array[MINUTE] = toInt(input.substr(pos)); + }); + addParseToken('Hmmss', function (input, array, config) { + var pos1 = input.length - 4, + pos2 = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos1)); + array[MINUTE] = toInt(input.substr(pos1, 2)); + array[SECOND] = toInt(input.substr(pos2)); + }); + + // LOCALES + + function localeIsPM(input) { + // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays + // Using charAt should be more compatible. + return (input + '').toLowerCase().charAt(0) === 'p'; + } + + var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i, + // Setting the hour should keep the time, because the user explicitly + // specified which hour they want. So trying to maintain the same hour (in + // a new timezone) makes sense. Adding/subtracting hours does not follow + // this rule. + getSetHour = makeGetSet('Hours', true); + + function localeMeridiem(hours, minutes, isLower) { + if (hours > 11) { + return isLower ? 'pm' : 'PM'; + } else { + return isLower ? 'am' : 'AM'; + } + } + + var baseConfig = { + calendar: defaultCalendar, + longDateFormat: defaultLongDateFormat, + invalidDate: defaultInvalidDate, + ordinal: defaultOrdinal, + dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse, + relativeTime: defaultRelativeTime, + + months: defaultLocaleMonths, + monthsShort: defaultLocaleMonthsShort, + + week: defaultLocaleWeek, + + weekdays: defaultLocaleWeekdays, + weekdaysMin: defaultLocaleWeekdaysMin, + weekdaysShort: defaultLocaleWeekdaysShort, + + meridiemParse: defaultLocaleMeridiemParse, + }; + + // internal storage for locale config files + var locales = {}, + localeFamilies = {}, + globalLocale; + + function commonPrefix(arr1, arr2) { + var i, + minl = Math.min(arr1.length, arr2.length); + for (i = 0; i < minl; i += 1) { + if (arr1[i] !== arr2[i]) { + return i; + } + } + return minl; + } + + function normalizeLocale(key) { + return key ? key.toLowerCase().replace('_', '-') : key; + } + + // pick the locale from the array + // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each + // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root + function chooseLocale(names) { + var i = 0, + j, + next, + locale, + split; + + while (i < names.length) { + split = normalizeLocale(names[i]).split('-'); + j = split.length; + next = normalizeLocale(names[i + 1]); + next = next ? next.split('-') : null; + while (j > 0) { + locale = loadLocale(split.slice(0, j).join('-')); + if (locale) { + return locale; + } + if ( + next && + next.length >= j && + commonPrefix(split, next) >= j - 1 + ) { + //the next array item is better than a shallower substring of this one + break; + } + j--; + } + i++; + } + return globalLocale; + } + + function isLocaleNameSane(name) { + // Prevent names that look like filesystem paths, i.e contain '/' or '\' + return name.match('^[^/\\\\]*$') != null; + } + + function loadLocale(name) { + var oldLocale = null, + aliasedRequire; + // TODO: Find a better way to register and load all the locales in Node + if ( + locales[name] === undefined && + 'object' !== 'undefined' && + module && + module.exports && + isLocaleNameSane(name) + ) { + try { + oldLocale = globalLocale._abbr; + aliasedRequire = commonjsRequire; + aliasedRequire('./locale/' + name); + getSetGlobalLocale(oldLocale); + } catch (e) { + // mark as not found to avoid repeating expensive file require call causing high CPU + // when trying to find en-US, en_US, en-us for every format call + locales[name] = null; // null means not found + } + } + return locales[name]; + } + + // This function will load locale and then set the global locale. If + // no arguments are passed in, it will simply return the current global + // locale key. + function getSetGlobalLocale(key, values) { + var data; + if (key) { + if (isUndefined(values)) { + data = getLocale(key); + } else { + data = defineLocale(key, values); + } + + if (data) { + // moment.duration._locale = moment._locale = data; + globalLocale = data; + } else { + if (typeof console !== 'undefined' && console.warn) { + //warn user if arguments are passed but the locale could not be set + console.warn( + 'Locale ' + key + ' not found. Did you forget to load it?' + ); + } + } + } + + return globalLocale._abbr; + } + + function defineLocale(name, config) { + if (config !== null) { + var locale, + parentConfig = baseConfig; + config.abbr = name; + if (locales[name] != null) { + 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.' + ); + parentConfig = locales[name]._config; + } else if (config.parentLocale != null) { + if (locales[config.parentLocale] != null) { + parentConfig = locales[config.parentLocale]._config; + } else { + locale = loadLocale(config.parentLocale); + if (locale != null) { + parentConfig = locale._config; + } else { + if (!localeFamilies[config.parentLocale]) { + localeFamilies[config.parentLocale] = []; + } + localeFamilies[config.parentLocale].push({ + name: name, + config: config, + }); + return null; + } + } + } + locales[name] = new Locale(mergeConfigs(parentConfig, config)); + + if (localeFamilies[name]) { + localeFamilies[name].forEach(function (x) { + defineLocale(x.name, x.config); + }); + } + + // backwards compat for now: also set the locale + // make sure we set the locale AFTER all child locales have been + // created, so we won't end up with the child locale set. + getSetGlobalLocale(name); + + return locales[name]; + } else { + // useful for testing + delete locales[name]; + return null; + } + } + + function updateLocale(name, config) { + if (config != null) { + var locale, + tmpLocale, + parentConfig = baseConfig; + + if (locales[name] != null && locales[name].parentLocale != null) { + // Update existing child locale in-place to avoid memory-leaks + locales[name].set(mergeConfigs(locales[name]._config, config)); + } else { + // MERGE + tmpLocale = loadLocale(name); + if (tmpLocale != null) { + parentConfig = tmpLocale._config; + } + config = mergeConfigs(parentConfig, config); + if (tmpLocale == null) { + // updateLocale is called for creating a new locale + // Set abbr so it will have a name (getters return + // undefined otherwise). + config.abbr = name; + } + locale = new Locale(config); + locale.parentLocale = locales[name]; + locales[name] = locale; + } + + // backwards compat for now: also set the locale + getSetGlobalLocale(name); + } else { + // pass null for config to unupdate, useful for tests + if (locales[name] != null) { + if (locales[name].parentLocale != null) { + locales[name] = locales[name].parentLocale; + if (name === getSetGlobalLocale()) { + getSetGlobalLocale(name); + } + } else if (locales[name] != null) { + delete locales[name]; + } + } + } + return locales[name]; + } + + // returns locale data + function getLocale(key) { + var locale; + + if (key && key._locale && key._locale._abbr) { + key = key._locale._abbr; + } + + if (!key) { + return globalLocale; + } + + if (!isArray(key)) { + //short-circuit everything else + locale = loadLocale(key); + if (locale) { + return locale; + } + key = [key]; + } + + return chooseLocale(key); + } + + function listLocales() { + return keys(locales); + } + + function checkOverflow(m) { + var overflow, + a = m._a; + + if (a && getParsingFlags(m).overflow === -2) { + 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; + + if ( + getParsingFlags(m)._overflowDayOfYear && + (overflow < YEAR || overflow > DATE) + ) { + overflow = DATE; + } + if (getParsingFlags(m)._overflowWeeks && overflow === -1) { + overflow = WEEK; + } + if (getParsingFlags(m)._overflowWeekday && overflow === -1) { + overflow = WEEKDAY; + } + + getParsingFlags(m).overflow = overflow; + } + + return m; + } + + // iso 8601 regex + // 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) + 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)?)?$/, + 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)?)?$/, + tzRegex = /Z|[+-]\d\d(?::?\d\d)?/, + 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}/], + ['GGGG[W]WWE', /\d{4}W\d{3}/], + ['GGGG[W]WW', /\d{4}W\d{2}/, false], + ['YYYYDDD', /\d{7}/], + ['YYYYMM', /\d{6}/, false], + ['YYYY', /\d{4}/, false], + ], + // iso time formats and regexes + 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/], + ], + aspNetJsonRegex = /^\/?Date\((-?\d+)/i, + // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3 + 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}))$/, + obsOffsets = { + UT: 0, + GMT: 0, + EDT: -4 * 60, + EST: -5 * 60, + CDT: -5 * 60, + CST: -6 * 60, + MDT: -6 * 60, + MST: -7 * 60, + PDT: -7 * 60, + PST: -8 * 60, + }; + + // date from iso format + function configFromISO(config) { + var i, + l, + string = config._i, + match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string), + allowTime, + dateFormat, + timeFormat, + tzFormat, + isoDatesLen = isoDates.length, + isoTimesLen = isoTimes.length; + + if (match) { + getParsingFlags(config).iso = true; + for (i = 0, l = isoDatesLen; i < l; i++) { + if (isoDates[i][1].exec(match[1])) { + dateFormat = isoDates[i][0]; + allowTime = isoDates[i][2] !== false; + break; + } + } + if (dateFormat == null) { + config._isValid = false; + return; + } + if (match[3]) { + for (i = 0, l = isoTimesLen; i < l; i++) { + if (isoTimes[i][1].exec(match[3])) { + // match[2] should be 'T' or space + timeFormat = (match[2] || ' ') + isoTimes[i][0]; + break; + } + } + if (timeFormat == null) { + config._isValid = false; + return; + } + } + if (!allowTime && timeFormat != null) { + config._isValid = false; + return; + } + if (match[4]) { + if (tzRegex.exec(match[4])) { + tzFormat = 'Z'; + } else { + config._isValid = false; + return; + } + } + config._f = dateFormat + (timeFormat || '') + (tzFormat || ''); + configFromStringAndFormat(config); + } else { + config._isValid = false; + } + } + + function extractFromRFC2822Strings( + yearStr, + monthStr, + dayStr, + hourStr, + minuteStr, + secondStr + ) { + var result = [ + untruncateYear(yearStr), + defaultLocaleMonthsShort.indexOf(monthStr), + parseInt(dayStr, 10), + parseInt(hourStr, 10), + parseInt(minuteStr, 10), + ]; + + if (secondStr) { + result.push(parseInt(secondStr, 10)); + } + + return result; + } + + function untruncateYear(yearStr) { + var year = parseInt(yearStr, 10); + if (year <= 49) { + return 2000 + year; + } else if (year <= 999) { + return 1900 + year; + } + return year; + } + + function preprocessRFC2822(s) { + // Remove comments and folding whitespace and replace multiple-spaces with a single space + return s + .replace(/\([^()]*\)|[\n\t]/g, ' ') + .replace(/(\s\s+)/g, ' ') + .replace(/^\s\s*/, '') + .replace(/\s\s*$/, ''); + } + + function checkWeekday(weekdayStr, parsedInput, config) { + if (weekdayStr) { + // TODO: Replace the vanilla JS Date object with an independent day-of-week check. + var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr), + weekdayActual = new Date( + parsedInput[0], + parsedInput[1], + parsedInput[2] + ).getDay(); + if (weekdayProvided !== weekdayActual) { + getParsingFlags(config).weekdayMismatch = true; + config._isValid = false; + return false; + } + } + return true; + } + + function calculateOffset(obsOffset, militaryOffset, numOffset) { + if (obsOffset) { + return obsOffsets[obsOffset]; + } else if (militaryOffset) { + // the only allowed military tz is Z + return 0; + } else { + var hm = parseInt(numOffset, 10), + m = hm % 100, + h = (hm - m) / 100; + return h * 60 + m; + } + } + + // date and time from ref 2822 format + function configFromRFC2822(config) { + var match = rfc2822.exec(preprocessRFC2822(config._i)), + parsedArray; + if (match) { + parsedArray = extractFromRFC2822Strings( + match[4], + match[3], + match[2], + match[5], + match[6], + match[7] + ); + if (!checkWeekday(match[1], parsedArray, config)) { + return; + } + + config._a = parsedArray; + config._tzm = calculateOffset(match[8], match[9], match[10]); + + config._d = createUTCDate.apply(null, config._a); + config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); + + getParsingFlags(config).rfc2822 = true; + } else { + config._isValid = false; + } + } + + // date from 1) ASP.NET, 2) ISO, 3) RFC 2822 formats, or 4) optional fallback if parsing isn't strict + function configFromString(config) { + var matched = aspNetJsonRegex.exec(config._i); + if (matched !== null) { + config._d = new Date(+matched[1]); + return; + } + + configFromISO(config); + if (config._isValid === false) { + delete config._isValid; + } else { + return; + } + + configFromRFC2822(config); + if (config._isValid === false) { + delete config._isValid; + } else { + return; + } + + if (config._strict) { + config._isValid = false; + } else { + // Final attempt, use Input Fallback + hooks.createFromInputFallback(config); + } + } + + 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. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.', + function (config) { + config._d = new Date(config._i + (config._useUTC ? ' UTC' : '')); + } + ); + + // Pick the first defined of two or three arguments. + function defaults(a, b, c) { + if (a != null) { + return a; + } + if (b != null) { + return b; + } + return c; + } + + function currentDateArray(config) { + // hooks is actually the exported moment object + var nowValue = new Date(hooks.now()); + if (config._useUTC) { + return [ + nowValue.getUTCFullYear(), + nowValue.getUTCMonth(), + nowValue.getUTCDate(), + ]; + } + return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()]; + } + + // convert an array to a date. + // the array should mirror the parameters below + // note: all values past the year are optional and will default to the lowest possible value. + // [year, month, day , hour, minute, second, millisecond] + function configFromArray(config) { + var i, + date, + input = [], + currentDate, + expectedWeekday, + yearToUse; + + if (config._d) { + return; + } + + currentDate = currentDateArray(config); + + //compute day of the year from weeks and weekdays + if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { + dayOfYearFromWeekInfo(config); + } + + //if the day of the year is set, figure out what it is + if (config._dayOfYear != null) { + yearToUse = defaults(config._a[YEAR], currentDate[YEAR]); + + if ( + config._dayOfYear > daysInYear(yearToUse) || + config._dayOfYear === 0 + ) { + getParsingFlags(config)._overflowDayOfYear = true; + } + + date = createUTCDate(yearToUse, 0, config._dayOfYear); + config._a[MONTH] = date.getUTCMonth(); + config._a[DATE] = date.getUTCDate(); + } + + // Default to current date. + // * if no year, month, day of month are given, default to today + // * if day of month is given, default month and year + // * if month is given, default only year + // * if year is given, don't default anything + for (i = 0; i < 3 && config._a[i] == null; ++i) { + config._a[i] = input[i] = currentDate[i]; + } + + // Zero out whatever was not defaulted, including time + for (; i < 7; i++) { + config._a[i] = input[i] = + config._a[i] == null ? (i === 2 ? 1 : 0) : config._a[i]; + } + + // Check for 24:00:00.000 + if ( + config._a[HOUR] === 24 && + config._a[MINUTE] === 0 && + config._a[SECOND] === 0 && + config._a[MILLISECOND] === 0 + ) { + config._nextDay = true; + config._a[HOUR] = 0; + } + + config._d = (config._useUTC ? createUTCDate : createDate).apply( + null, + input + ); + expectedWeekday = config._useUTC + ? config._d.getUTCDay() + : config._d.getDay(); + + // Apply timezone offset from input. The actual utcOffset can be changed + // with parseZone. + if (config._tzm != null) { + config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); + } + + if (config._nextDay) { + config._a[HOUR] = 24; + } + + // check for mismatching day of week + if ( + config._w && + typeof config._w.d !== 'undefined' && + config._w.d !== expectedWeekday + ) { + getParsingFlags(config).weekdayMismatch = true; + } + } + + function dayOfYearFromWeekInfo(config) { + var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow, curWeek; + + w = config._w; + if (w.GG != null || w.W != null || w.E != null) { + dow = 1; + doy = 4; + + // TODO: We need to take the current isoWeekYear, but that depends on + // how we interpret now (local, utc, fixed offset). So create + // a now version of current config (take local/utc/offset flags, and + // create now). + weekYear = defaults( + w.GG, + config._a[YEAR], + weekOfYear(createLocal(), 1, 4).year + ); + week = defaults(w.W, 1); + weekday = defaults(w.E, 1); + if (weekday < 1 || weekday > 7) { + weekdayOverflow = true; + } + } else { + dow = config._locale._week.dow; + doy = config._locale._week.doy; + + curWeek = weekOfYear(createLocal(), dow, doy); + + weekYear = defaults(w.gg, config._a[YEAR], curWeek.year); + + // Default to current week. + week = defaults(w.w, curWeek.week); + + if (w.d != null) { + // weekday -- low day numbers are considered next week + weekday = w.d; + if (weekday < 0 || weekday > 6) { + weekdayOverflow = true; + } + } else if (w.e != null) { + // local weekday -- counting starts from beginning of week + weekday = w.e + dow; + if (w.e < 0 || w.e > 6) { + weekdayOverflow = true; + } + } else { + // default to beginning of week + weekday = dow; + } + } + if (week < 1 || week > weeksInYear(weekYear, dow, doy)) { + getParsingFlags(config)._overflowWeeks = true; + } else if (weekdayOverflow != null) { + getParsingFlags(config)._overflowWeekday = true; + } else { + temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy); + config._a[YEAR] = temp.year; + config._dayOfYear = temp.dayOfYear; + } + } + + // constant that refers to the ISO standard + hooks.ISO_8601 = function () {}; + + // constant that refers to the RFC 2822 form + hooks.RFC_2822 = function () {}; + + // date from string and format string + function configFromStringAndFormat(config) { + // TODO: Move this to another part of the creation flow to prevent circular deps + if (config._f === hooks.ISO_8601) { + configFromISO(config); + return; + } + if (config._f === hooks.RFC_2822) { + configFromRFC2822(config); + return; + } + config._a = []; + getParsingFlags(config).empty = true; + + // This array is used to make a Date, either with `new Date` or `Date.UTC` + var string = '' + config._i, + i, + parsedInput, + tokens, + token, + skipped, + stringLength = string.length, + totalParsedInputLength = 0, + era, + tokenLen; + + tokens = + expandFormat(config._f, config._locale).match(formattingTokens) || []; + tokenLen = tokens.length; + for (i = 0; i < tokenLen; i++) { + token = tokens[i]; + parsedInput = (string.match(getParseRegexForToken(token, config)) || + [])[0]; + if (parsedInput) { + skipped = string.substr(0, string.indexOf(parsedInput)); + if (skipped.length > 0) { + getParsingFlags(config).unusedInput.push(skipped); + } + string = string.slice( + string.indexOf(parsedInput) + parsedInput.length + ); + totalParsedInputLength += parsedInput.length; + } + // don't parse if it's not a known token + if (formatTokenFunctions[token]) { + if (parsedInput) { + getParsingFlags(config).empty = false; + } else { + getParsingFlags(config).unusedTokens.push(token); + } + addTimeToArrayFromToken(token, parsedInput, config); + } else if (config._strict && !parsedInput) { + getParsingFlags(config).unusedTokens.push(token); + } + } + + // add remaining unparsed input length to the string + getParsingFlags(config).charsLeftOver = + stringLength - totalParsedInputLength; + if (string.length > 0) { + getParsingFlags(config).unusedInput.push(string); + } + + // clear _12h flag if hour is <= 12 + if ( + config._a[HOUR] <= 12 && + getParsingFlags(config).bigHour === true && + config._a[HOUR] > 0 + ) { + getParsingFlags(config).bigHour = undefined; + } + + getParsingFlags(config).parsedDateParts = config._a.slice(0); + getParsingFlags(config).meridiem = config._meridiem; + // handle meridiem + config._a[HOUR] = meridiemFixWrap( + config._locale, + config._a[HOUR], + config._meridiem + ); + + // handle era + era = getParsingFlags(config).era; + if (era !== null) { + config._a[YEAR] = config._locale.erasConvertYear(era, config._a[YEAR]); + } + + configFromArray(config); + checkOverflow(config); + } + + function meridiemFixWrap(locale, hour, meridiem) { + var isPm; + + if (meridiem == null) { + // nothing to do + return hour; + } + if (locale.meridiemHour != null) { + return locale.meridiemHour(hour, meridiem); + } else if (locale.isPM != null) { + // Fallback + isPm = locale.isPM(meridiem); + if (isPm && hour < 12) { + hour += 12; + } + if (!isPm && hour === 12) { + hour = 0; + } + return hour; + } else { + // this is not supposed to happen + return hour; + } + } + + // date from string and array of format strings + function configFromStringAndArray(config) { + var tempConfig, + bestMoment, + scoreToBeat, + i, + currentScore, + validFormatFound, + bestFormatIsValid = false, + configfLen = config._f.length; + + if (configfLen === 0) { + getParsingFlags(config).invalidFormat = true; + config._d = new Date(NaN); + return; + } + + for (i = 0; i < configfLen; i++) { + currentScore = 0; + validFormatFound = false; + tempConfig = copyConfig({}, config); + if (config._useUTC != null) { + tempConfig._useUTC = config._useUTC; + } + tempConfig._f = config._f[i]; + configFromStringAndFormat(tempConfig); + + if (isValid(tempConfig)) { + validFormatFound = true; + } + + // if there is any input that was not parsed add a penalty for that format + currentScore += getParsingFlags(tempConfig).charsLeftOver; + + //or tokens + currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10; + + getParsingFlags(tempConfig).score = currentScore; + + if (!bestFormatIsValid) { + if ( + scoreToBeat == null || + currentScore < scoreToBeat || + validFormatFound + ) { + scoreToBeat = currentScore; + bestMoment = tempConfig; + if (validFormatFound) { + bestFormatIsValid = true; + } + } + } else { + if (currentScore < scoreToBeat) { + scoreToBeat = currentScore; + bestMoment = tempConfig; + } + } + } + + extend(config, bestMoment || tempConfig); + } + + function configFromObject(config) { + if (config._d) { + return; + } + + var i = normalizeObjectUnits(config._i), + dayOrDate = i.day === undefined ? i.date : i.day; + config._a = map( + [i.year, i.month, dayOrDate, i.hour, i.minute, i.second, i.millisecond], + function (obj) { + return obj && parseInt(obj, 10); + } + ); + + configFromArray(config); + } + + function createFromConfig(config) { + var res = new Moment(checkOverflow(prepareConfig(config))); + if (res._nextDay) { + // Adding is smart enough around DST + res.add(1, 'd'); + res._nextDay = undefined; + } + + return res; + } + + function prepareConfig(config) { + var input = config._i, + format = config._f; + + config._locale = config._locale || getLocale(config._l); + + if (input === null || (format === undefined && input === '')) { + return createInvalid({ nullInput: true }); + } + + if (typeof input === 'string') { + config._i = input = config._locale.preparse(input); + } + + if (isMoment(input)) { + return new Moment(checkOverflow(input)); + } else if (isDate(input)) { + config._d = input; + } else if (isArray(format)) { + configFromStringAndArray(config); + } else if (format) { + configFromStringAndFormat(config); + } else { + configFromInput(config); + } + + if (!isValid(config)) { + config._d = null; + } + + return config; + } + + function configFromInput(config) { + var input = config._i; + if (isUndefined(input)) { + config._d = new Date(hooks.now()); + } else if (isDate(input)) { + config._d = new Date(input.valueOf()); + } else if (typeof input === 'string') { + configFromString(config); + } else if (isArray(input)) { + config._a = map(input.slice(0), function (obj) { + return parseInt(obj, 10); + }); + configFromArray(config); + } else if (isObject(input)) { + configFromObject(config); + } else if (isNumber(input)) { + // from milliseconds + config._d = new Date(input); + } else { + hooks.createFromInputFallback(config); + } + } + + function createLocalOrUTC(input, format, locale, strict, isUTC) { + var c = {}; + + if (format === true || format === false) { + strict = format; + format = undefined; + } + + if (locale === true || locale === false) { + strict = locale; + locale = undefined; + } + + if ( + (isObject(input) && isObjectEmpty(input)) || + (isArray(input) && input.length === 0) + ) { + input = undefined; + } + // object construction must be done this way. + // https://github.com/moment/moment/issues/1423 + c._isAMomentObject = true; + c._useUTC = c._isUTC = isUTC; + c._l = locale; + c._i = input; + c._f = format; + c._strict = strict; + + return createFromConfig(c); + } + + function createLocal(input, format, locale, strict) { + return createLocalOrUTC(input, format, locale, strict, false); + } + + var prototypeMin = deprecate( + 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/', + function () { + var other = createLocal.apply(null, arguments); + if (this.isValid() && other.isValid()) { + return other < this ? this : other; + } else { + return createInvalid(); + } + } + ), + prototypeMax = deprecate( + 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/', + function () { + var other = createLocal.apply(null, arguments); + if (this.isValid() && other.isValid()) { + return other > this ? this : other; + } else { + return createInvalid(); + } + } + ); + + // Pick a moment m from moments so that m[fn](other) is true for all + // other. This relies on the function fn to be transitive. + // + // moments should either be an array of moment objects or an array, whose + // first element is an array of moment objects. + function pickBy(fn, moments) { + var res, i; + if (moments.length === 1 && isArray(moments[0])) { + moments = moments[0]; + } + if (!moments.length) { + return createLocal(); + } + res = moments[0]; + for (i = 1; i < moments.length; ++i) { + if (!moments[i].isValid() || moments[i][fn](res)) { + res = moments[i]; + } + } + return res; + } + + // TODO: Use [].sort instead? + function min() { + var args = [].slice.call(arguments, 0); + + return pickBy('isBefore', args); + } + + function max() { + var args = [].slice.call(arguments, 0); + + return pickBy('isAfter', args); + } + + var now = function () { + return Date.now ? Date.now() : +new Date(); + }; + + var ordering = [ + 'year', + 'quarter', + 'month', + 'week', + 'day', + 'hour', + 'minute', + 'second', + 'millisecond', + ]; + + function isDurationValid(m) { + var key, + unitHasDecimal = false, + i, + orderLen = ordering.length; + for (key in m) { + if ( + hasOwnProp(m, key) && + !( + indexOf.call(ordering, key) !== -1 && + (m[key] == null || !isNaN(m[key])) + ) + ) { + return false; + } + } + + for (i = 0; i < orderLen; ++i) { + if (m[ordering[i]]) { + if (unitHasDecimal) { + return false; // only allow non-integers for smallest unit + } + if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) { + unitHasDecimal = true; + } + } + } + + return true; + } + + function isValid$1() { + return this._isValid; + } + + function createInvalid$1() { + return createDuration(NaN); + } + + function Duration(duration) { + var normalizedInput = normalizeObjectUnits(duration), + years = normalizedInput.year || 0, + quarters = normalizedInput.quarter || 0, + months = normalizedInput.month || 0, + weeks = normalizedInput.week || normalizedInput.isoWeek || 0, + days = normalizedInput.day || 0, + hours = normalizedInput.hour || 0, + minutes = normalizedInput.minute || 0, + seconds = normalizedInput.second || 0, + milliseconds = normalizedInput.millisecond || 0; + + this._isValid = isDurationValid(normalizedInput); + + // representation for dateAddRemove + this._milliseconds = + +milliseconds + + seconds * 1e3 + // 1000 + minutes * 6e4 + // 1000 * 60 + hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978 + // Because of dateAddRemove treats 24 hours as different from a + // day when working around DST, we need to store them separately + this._days = +days + weeks * 7; + // It is impossible to translate months into days without knowing + // which months you are are talking about, so we have to store + // it separately. + this._months = +months + quarters * 3 + years * 12; + + this._data = {}; + + this._locale = getLocale(); + + this._bubble(); + } + + function isDuration(obj) { + return obj instanceof Duration; + } + + function absRound(number) { + if (number < 0) { + return Math.round(-1 * number) * -1; + } else { + return Math.round(number); + } + } + + // compare two arrays, return the number of differences + function compareArrays(array1, array2, dontConvert) { + var len = Math.min(array1.length, array2.length), + lengthDiff = Math.abs(array1.length - array2.length), + diffs = 0, + i; + for (i = 0; i < len; i++) { + if ( + (dontConvert && array1[i] !== array2[i]) || + (!dontConvert && toInt(array1[i]) !== toInt(array2[i])) + ) { + diffs++; + } + } + return diffs + lengthDiff; + } + + // FORMATTING + + function offset(token, separator) { + addFormatToken(token, 0, 0, function () { + var offset = this.utcOffset(), + sign = '+'; + if (offset < 0) { + offset = -offset; + sign = '-'; + } + return ( + sign + + zeroFill(~~(offset / 60), 2) + + separator + + zeroFill(~~offset % 60, 2) + ); + }); + } + + offset('Z', ':'); + offset('ZZ', ''); + + // PARSING + + addRegexToken('Z', matchShortOffset); + addRegexToken('ZZ', matchShortOffset); + addParseToken(['Z', 'ZZ'], function (input, array, config) { + config._useUTC = true; + config._tzm = offsetFromString(matchShortOffset, input); + }); + + // HELPERS + + // timezone chunker + // '+10:00' > ['10', '00'] + // '-1530' > ['-15', '30'] + var chunkOffset = /([\+\-]|\d\d)/gi; + + function offsetFromString(matcher, string) { + var matches = (string || '').match(matcher), + chunk, + parts, + minutes; + + if (matches === null) { + return null; + } + + chunk = matches[matches.length - 1] || []; + parts = (chunk + '').match(chunkOffset) || ['-', 0, 0]; + minutes = +(parts[1] * 60) + toInt(parts[2]); + + return minutes === 0 ? 0 : parts[0] === '+' ? minutes : -minutes; + } + + // Return a moment from input, that is local/utc/zone equivalent to model. + function cloneWithOffset(input, model) { + var res, diff; + if (model._isUTC) { + res = model.clone(); + diff = + (isMoment(input) || isDate(input) + ? input.valueOf() + : createLocal(input).valueOf()) - res.valueOf(); + // Use low-level api, because this fn is low-level api. + res._d.setTime(res._d.valueOf() + diff); + hooks.updateOffset(res, false); + return res; + } else { + return createLocal(input).local(); + } + } + + function getDateOffset(m) { + // On Firefox.24 Date#getTimezoneOffset returns a floating point. + // https://github.com/moment/moment/pull/1871 + return -Math.round(m._d.getTimezoneOffset()); + } + + // HOOKS + + // This function will be called whenever a moment is mutated. + // It is intended to keep the offset in sync with the timezone. + hooks.updateOffset = function () {}; + + // MOMENTS + + // keepLocalTime = true means only change the timezone, without + // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]--> + // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset + // +0200, so we adjust the time as needed, to be valid. + // + // Keeping the time actually adds/subtracts (one hour) + // from the actual represented time. That is why we call updateOffset + // a second time. In case it wants us to change the offset again + // _changeInProgress == true case, then we have to adjust, because + // there is no such time in the given timezone. + function getSetOffset(input, keepLocalTime, keepMinutes) { + var offset = this._offset || 0, + localAdjust; + if (!this.isValid()) { + return input != null ? this : NaN; + } + if (input != null) { + if (typeof input === 'string') { + input = offsetFromString(matchShortOffset, input); + if (input === null) { + return this; + } + } else if (Math.abs(input) < 16 && !keepMinutes) { + input = input * 60; + } + if (!this._isUTC && keepLocalTime) { + localAdjust = getDateOffset(this); + } + this._offset = input; + this._isUTC = true; + if (localAdjust != null) { + this.add(localAdjust, 'm'); + } + if (offset !== input) { + if (!keepLocalTime || this._changeInProgress) { + addSubtract( + this, + createDuration(input - offset, 'm'), + 1, + false + ); + } else if (!this._changeInProgress) { + this._changeInProgress = true; + hooks.updateOffset(this, true); + this._changeInProgress = null; + } + } + return this; + } else { + return this._isUTC ? offset : getDateOffset(this); + } + } + + function getSetZone(input, keepLocalTime) { + if (input != null) { + if (typeof input !== 'string') { + input = -input; + } + + this.utcOffset(input, keepLocalTime); + + return this; + } else { + return -this.utcOffset(); + } + } + + function setOffsetToUTC(keepLocalTime) { + return this.utcOffset(0, keepLocalTime); + } + + function setOffsetToLocal(keepLocalTime) { + if (this._isUTC) { + this.utcOffset(0, keepLocalTime); + this._isUTC = false; + + if (keepLocalTime) { + this.subtract(getDateOffset(this), 'm'); + } + } + return this; + } + + function setOffsetToParsedOffset() { + if (this._tzm != null) { + this.utcOffset(this._tzm, false, true); + } else if (typeof this._i === 'string') { + var tZone = offsetFromString(matchOffset, this._i); + if (tZone != null) { + this.utcOffset(tZone); + } else { + this.utcOffset(0, true); + } + } + return this; + } + + function hasAlignedHourOffset(input) { + if (!this.isValid()) { + return false; + } + input = input ? createLocal(input).utcOffset() : 0; + + return (this.utcOffset() - input) % 60 === 0; + } + + function isDaylightSavingTime() { + return ( + this.utcOffset() > this.clone().month(0).utcOffset() || + this.utcOffset() > this.clone().month(5).utcOffset() + ); + } + + function isDaylightSavingTimeShifted() { + if (!isUndefined(this._isDSTShifted)) { + return this._isDSTShifted; + } + + var c = {}, + other; + + copyConfig(c, this); + c = prepareConfig(c); + + if (c._a) { + other = c._isUTC ? createUTC(c._a) : createLocal(c._a); + this._isDSTShifted = + this.isValid() && compareArrays(c._a, other.toArray()) > 0; + } else { + this._isDSTShifted = false; + } + + return this._isDSTShifted; + } + + function isLocal() { + return this.isValid() ? !this._isUTC : false; + } + + function isUtcOffset() { + return this.isValid() ? this._isUTC : false; + } + + function isUtc() { + return this.isValid() ? this._isUTC && this._offset === 0 : false; + } + + // ASP.NET json date format regex + var aspNetRegex = /^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/, + // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html + // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere + // and further modified to allow for strings containing both week and day + isoRegex = + /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; + + function createDuration(input, key) { + var duration = input, + // matching against regexp is expensive, do it on demand + match = null, + sign, + ret, + diffRes; + + if (isDuration(input)) { + duration = { + ms: input._milliseconds, + d: input._days, + M: input._months, + }; + } else if (isNumber(input) || !isNaN(+input)) { + duration = {}; + if (key) { + duration[key] = +input; + } else { + duration.milliseconds = +input; + } + } else if ((match = aspNetRegex.exec(input))) { + sign = match[1] === '-' ? -1 : 1; + duration = { + y: 0, + d: toInt(match[DATE]) * sign, + h: toInt(match[HOUR]) * sign, + m: toInt(match[MINUTE]) * sign, + s: toInt(match[SECOND]) * sign, + ms: toInt(absRound(match[MILLISECOND] * 1000)) * sign, // the millisecond decimal point is included in the match + }; + } else if ((match = isoRegex.exec(input))) { + sign = match[1] === '-' ? -1 : 1; + duration = { + y: parseIso(match[2], sign), + M: parseIso(match[3], sign), + w: parseIso(match[4], sign), + d: parseIso(match[5], sign), + h: parseIso(match[6], sign), + m: parseIso(match[7], sign), + s: parseIso(match[8], sign), + }; + } else if (duration == null) { + // checks for null or undefined + duration = {}; + } else if ( + typeof duration === 'object' && + ('from' in duration || 'to' in duration) + ) { + diffRes = momentsDifference( + createLocal(duration.from), + createLocal(duration.to) + ); + + duration = {}; + duration.ms = diffRes.milliseconds; + duration.M = diffRes.months; + } + + ret = new Duration(duration); + + if (isDuration(input) && hasOwnProp(input, '_locale')) { + ret._locale = input._locale; + } + + if (isDuration(input) && hasOwnProp(input, '_isValid')) { + ret._isValid = input._isValid; + } + + return ret; + } + + createDuration.fn = Duration.prototype; + createDuration.invalid = createInvalid$1; + + function parseIso(inp, sign) { + // We'd normally use ~~inp for this, but unfortunately it also + // converts floats to ints. + // inp may be undefined, so careful calling replace on it. + var res = inp && parseFloat(inp.replace(',', '.')); + // apply sign while we're at it + return (isNaN(res) ? 0 : res) * sign; + } + + function positiveMomentsDifference(base, other) { + var res = {}; + + res.months = + other.month() - base.month() + (other.year() - base.year()) * 12; + if (base.clone().add(res.months, 'M').isAfter(other)) { + --res.months; + } + + res.milliseconds = +other - +base.clone().add(res.months, 'M'); + + return res; + } + + function momentsDifference(base, other) { + var res; + if (!(base.isValid() && other.isValid())) { + return { milliseconds: 0, months: 0 }; + } + + other = cloneWithOffset(other, base); + if (base.isBefore(other)) { + res = positiveMomentsDifference(base, other); + } else { + res = positiveMomentsDifference(other, base); + res.milliseconds = -res.milliseconds; + res.months = -res.months; + } + + return res; + } + + // TODO: remove 'name' arg after deprecation is removed + function createAdder(direction, name) { + return function (val, period) { + var dur, tmp; + //invert the arguments, but complain about it + if (period !== null && !isNaN(+period)) { + 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.' + ); + tmp = val; + val = period; + period = tmp; + } + + dur = createDuration(val, period); + addSubtract(this, dur, direction); + return this; + }; + } + + function addSubtract(mom, duration, isAdding, updateOffset) { + var milliseconds = duration._milliseconds, + days = absRound(duration._days), + months = absRound(duration._months); + + if (!mom.isValid()) { + // No op + return; + } + + updateOffset = updateOffset == null ? true : updateOffset; + + if (months) { + setMonth(mom, get(mom, 'Month') + months * isAdding); + } + if (days) { + set$1(mom, 'Date', get(mom, 'Date') + days * isAdding); + } + if (milliseconds) { + mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding); + } + if (updateOffset) { + hooks.updateOffset(mom, days || months); + } + } + + var add = createAdder(1, 'add'), + subtract = createAdder(-1, 'subtract'); + + function isString(input) { + return typeof input === 'string' || input instanceof String; + } + + // type MomentInput = Moment | Date | string | number | (number | string)[] | MomentInputObject | void; // null | undefined + function isMomentInput(input) { + return ( + isMoment(input) || + isDate(input) || + isString(input) || + isNumber(input) || + isNumberOrStringArray(input) || + isMomentInputObject(input) || + input === null || + input === undefined + ); + } + + function isMomentInputObject(input) { + var objectTest = isObject(input) && !isObjectEmpty(input), + propertyTest = false, + properties = [ + 'years', + 'year', + 'y', + 'months', + 'month', + 'M', + 'days', + 'day', + 'd', + 'dates', + 'date', + 'D', + 'hours', + 'hour', + 'h', + 'minutes', + 'minute', + 'm', + 'seconds', + 'second', + 's', + 'milliseconds', + 'millisecond', + 'ms', + ], + i, + property, + propertyLen = properties.length; + + for (i = 0; i < propertyLen; i += 1) { + property = properties[i]; + propertyTest = propertyTest || hasOwnProp(input, property); + } + + return objectTest && propertyTest; + } + + function isNumberOrStringArray(input) { + var arrayTest = isArray(input), + dataTypeTest = false; + if (arrayTest) { + dataTypeTest = + input.filter(function (item) { + return !isNumber(item) && isString(input); + }).length === 0; + } + return arrayTest && dataTypeTest; + } + + function isCalendarSpec(input) { + var objectTest = isObject(input) && !isObjectEmpty(input), + propertyTest = false, + properties = [ + 'sameDay', + 'nextDay', + 'lastDay', + 'nextWeek', + 'lastWeek', + 'sameElse', + ], + i, + property; + + for (i = 0; i < properties.length; i += 1) { + property = properties[i]; + propertyTest = propertyTest || hasOwnProp(input, property); + } + + return objectTest && propertyTest; + } + + function getCalendarFormat(myMoment, now) { + var diff = myMoment.diff(now, 'days', true); + return diff < -6 + ? 'sameElse' + : diff < -1 + ? 'lastWeek' + : diff < 0 + ? 'lastDay' + : diff < 1 + ? 'sameDay' + : diff < 2 + ? 'nextDay' + : diff < 7 + ? 'nextWeek' + : 'sameElse'; + } + + function calendar$1(time, formats) { + // Support for single parameter, formats only overload to the calendar function + if (arguments.length === 1) { + if (!arguments[0]) { + time = undefined; + formats = undefined; + } else if (isMomentInput(arguments[0])) { + time = arguments[0]; + formats = undefined; + } else if (isCalendarSpec(arguments[0])) { + formats = arguments[0]; + time = undefined; + } + } + // We want to compare the start of today, vs this. + // Getting start-of-today depends on whether we're local/utc/offset or not. + var now = time || createLocal(), + sod = cloneWithOffset(now, this).startOf('day'), + format = hooks.calendarFormat(this, sod) || 'sameElse', + output = + formats && + (isFunction(formats[format]) + ? formats[format].call(this, now) + : formats[format]); + + return this.format( + output || this.localeData().calendar(format, this, createLocal(now)) + ); + } + + function clone() { + return new Moment(this); + } + + function isAfter(input, units) { + var localInput = isMoment(input) ? input : createLocal(input); + if (!(this.isValid() && localInput.isValid())) { + return false; + } + units = normalizeUnits(units) || 'millisecond'; + if (units === 'millisecond') { + return this.valueOf() > localInput.valueOf(); + } else { + return localInput.valueOf() < this.clone().startOf(units).valueOf(); + } + } + + function isBefore(input, units) { + var localInput = isMoment(input) ? input : createLocal(input); + if (!(this.isValid() && localInput.isValid())) { + return false; + } + units = normalizeUnits(units) || 'millisecond'; + if (units === 'millisecond') { + return this.valueOf() < localInput.valueOf(); + } else { + return this.clone().endOf(units).valueOf() < localInput.valueOf(); + } + } + + function isBetween(from, to, units, inclusivity) { + var localFrom = isMoment(from) ? from : createLocal(from), + localTo = isMoment(to) ? to : createLocal(to); + if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) { + return false; + } + inclusivity = inclusivity || '()'; + return ( + (inclusivity[0] === '(' + ? this.isAfter(localFrom, units) + : !this.isBefore(localFrom, units)) && + (inclusivity[1] === ')' + ? this.isBefore(localTo, units) + : !this.isAfter(localTo, units)) + ); + } + + function isSame(input, units) { + var localInput = isMoment(input) ? input : createLocal(input), + inputMs; + if (!(this.isValid() && localInput.isValid())) { + return false; + } + units = normalizeUnits(units) || 'millisecond'; + if (units === 'millisecond') { + return this.valueOf() === localInput.valueOf(); + } else { + inputMs = localInput.valueOf(); + return ( + this.clone().startOf(units).valueOf() <= inputMs && + inputMs <= this.clone().endOf(units).valueOf() + ); + } + } + + function isSameOrAfter(input, units) { + return this.isSame(input, units) || this.isAfter(input, units); + } + + function isSameOrBefore(input, units) { + return this.isSame(input, units) || this.isBefore(input, units); + } + + function diff(input, units, asFloat) { + var that, zoneDelta, output; + + if (!this.isValid()) { + return NaN; + } + + that = cloneWithOffset(input, this); + + if (!that.isValid()) { + return NaN; + } + + zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4; + + units = normalizeUnits(units); + + switch (units) { + case 'year': + output = monthDiff(this, that) / 12; + break; + case 'month': + output = monthDiff(this, that); + break; + case 'quarter': + output = monthDiff(this, that) / 3; + break; + case 'second': + output = (this - that) / 1e3; + break; // 1000 + case 'minute': + output = (this - that) / 6e4; + break; // 1000 * 60 + case 'hour': + output = (this - that) / 36e5; + break; // 1000 * 60 * 60 + case 'day': + output = (this - that - zoneDelta) / 864e5; + break; // 1000 * 60 * 60 * 24, negate dst + case 'week': + output = (this - that - zoneDelta) / 6048e5; + break; // 1000 * 60 * 60 * 24 * 7, negate dst + default: + output = this - that; + } + + return asFloat ? output : absFloor(output); + } + + function monthDiff(a, b) { + if (a.date() < b.date()) { + // end-of-month calculations work correct when the start month has more + // days than the end month. + return -monthDiff(b, a); + } + // difference in months + var wholeMonthDiff = (b.year() - a.year()) * 12 + (b.month() - a.month()), + // b is in (anchor - 1 month, anchor + 1 month) + anchor = a.clone().add(wholeMonthDiff, 'months'), + anchor2, + adjust; + + if (b - anchor < 0) { + anchor2 = a.clone().add(wholeMonthDiff - 1, 'months'); + // linear across the month + adjust = (b - anchor) / (anchor - anchor2); + } else { + anchor2 = a.clone().add(wholeMonthDiff + 1, 'months'); + // linear across the month + adjust = (b - anchor) / (anchor2 - anchor); + } + + //check for negative zero, return zero if negative zero + return -(wholeMonthDiff + adjust) || 0; + } + + hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ'; + hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]'; + + function toString() { + return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); + } + + function toISOString(keepOffset) { + if (!this.isValid()) { + return null; + } + var utc = keepOffset !== true, + m = utc ? this.clone().utc() : this; + if (m.year() < 0 || m.year() > 9999) { + return formatMoment( + m, + utc + ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]' + : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ' + ); + } + if (isFunction(Date.prototype.toISOString)) { + // native implementation is ~50x faster, use it when we can + if (utc) { + return this.toDate().toISOString(); + } else { + return new Date(this.valueOf() + this.utcOffset() * 60 * 1000) + .toISOString() + .replace('Z', formatMoment(m, 'Z')); + } + } + return formatMoment( + m, + utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ' + ); + } + + /** + * Return a human readable representation of a moment that can + * also be evaluated to get a new moment which is the same + * + * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects + */ + function inspect() { + if (!this.isValid()) { + return 'moment.invalid(/* ' + this._i + ' */)'; + } + var func = 'moment', + zone = '', + prefix, + year, + datetime, + suffix; + if (!this.isLocal()) { + func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone'; + zone = 'Z'; + } + prefix = '[' + func + '("]'; + year = 0 <= this.year() && this.year() <= 9999 ? 'YYYY' : 'YYYYYY'; + datetime = '-MM-DD[T]HH:mm:ss.SSS'; + suffix = zone + '[")]'; + + return this.format(prefix + year + datetime + suffix); + } + + function format(inputString) { + if (!inputString) { + inputString = this.isUtc() + ? hooks.defaultFormatUtc + : hooks.defaultFormat; + } + var output = formatMoment(this, inputString); + return this.localeData().postformat(output); + } + + function from(time, withoutSuffix) { + if ( + this.isValid() && + ((isMoment(time) && time.isValid()) || createLocal(time).isValid()) + ) { + return createDuration({ to: this, from: time }) + .locale(this.locale()) + .humanize(!withoutSuffix); + } else { + return this.localeData().invalidDate(); + } + } + + function fromNow(withoutSuffix) { + return this.from(createLocal(), withoutSuffix); + } + + function to(time, withoutSuffix) { + if ( + this.isValid() && + ((isMoment(time) && time.isValid()) || createLocal(time).isValid()) + ) { + return createDuration({ from: this, to: time }) + .locale(this.locale()) + .humanize(!withoutSuffix); + } else { + return this.localeData().invalidDate(); + } + } + + function toNow(withoutSuffix) { + return this.to(createLocal(), withoutSuffix); + } + + // If passed a locale key, it will set the locale for this + // instance. Otherwise, it will return the locale configuration + // variables for this instance. + function locale(key) { + var newLocaleData; + + if (key === undefined) { + return this._locale._abbr; + } else { + newLocaleData = getLocale(key); + if (newLocaleData != null) { + this._locale = newLocaleData; + } + return this; + } + } + + var lang = deprecate( + 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', + function (key) { + if (key === undefined) { + return this.localeData(); + } else { + return this.locale(key); + } + } + ); + + function localeData() { + return this._locale; + } + + var MS_PER_SECOND = 1000, + MS_PER_MINUTE = 60 * MS_PER_SECOND, + MS_PER_HOUR = 60 * MS_PER_MINUTE, + MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR; + + // actual modulo - handles negative numbers (for dates before 1970): + function mod$1(dividend, divisor) { + return ((dividend % divisor) + divisor) % divisor; + } + + function localStartOfDate(y, m, d) { + // the date constructor remaps years 0-99 to 1900-1999 + if (y < 100 && y >= 0) { + // preserve leap years using a full 400 year cycle, then reset + return new Date(y + 400, m, d) - MS_PER_400_YEARS; + } else { + return new Date(y, m, d).valueOf(); + } + } + + function utcStartOfDate(y, m, d) { + // Date.UTC remaps years 0-99 to 1900-1999 + if (y < 100 && y >= 0) { + // preserve leap years using a full 400 year cycle, then reset + return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS; + } else { + return Date.UTC(y, m, d); + } + } + + function startOf(units) { + var time, startOfDate; + units = normalizeUnits(units); + if (units === undefined || units === 'millisecond' || !this.isValid()) { + return this; + } + + startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate; + + switch (units) { + case 'year': + time = startOfDate(this.year(), 0, 1); + break; + case 'quarter': + time = startOfDate( + this.year(), + this.month() - (this.month() % 3), + 1 + ); + break; + case 'month': + time = startOfDate(this.year(), this.month(), 1); + break; + case 'week': + time = startOfDate( + this.year(), + this.month(), + this.date() - this.weekday() + ); + break; + case 'isoWeek': + time = startOfDate( + this.year(), + this.month(), + this.date() - (this.isoWeekday() - 1) + ); + break; + case 'day': + case 'date': + time = startOfDate(this.year(), this.month(), this.date()); + break; + case 'hour': + time = this._d.valueOf(); + time -= mod$1( + time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), + MS_PER_HOUR + ); + break; + case 'minute': + time = this._d.valueOf(); + time -= mod$1(time, MS_PER_MINUTE); + break; + case 'second': + time = this._d.valueOf(); + time -= mod$1(time, MS_PER_SECOND); + break; + } + + this._d.setTime(time); + hooks.updateOffset(this, true); + return this; + } + + function endOf(units) { + var time, startOfDate; + units = normalizeUnits(units); + if (units === undefined || units === 'millisecond' || !this.isValid()) { + return this; + } + + startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate; + + switch (units) { + case 'year': + time = startOfDate(this.year() + 1, 0, 1) - 1; + break; + case 'quarter': + time = + startOfDate( + this.year(), + this.month() - (this.month() % 3) + 3, + 1 + ) - 1; + break; + case 'month': + time = startOfDate(this.year(), this.month() + 1, 1) - 1; + break; + case 'week': + time = + startOfDate( + this.year(), + this.month(), + this.date() - this.weekday() + 7 + ) - 1; + break; + case 'isoWeek': + time = + startOfDate( + this.year(), + this.month(), + this.date() - (this.isoWeekday() - 1) + 7 + ) - 1; + break; + case 'day': + case 'date': + time = startOfDate(this.year(), this.month(), this.date() + 1) - 1; + break; + case 'hour': + time = this._d.valueOf(); + time += + MS_PER_HOUR - + mod$1( + time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), + MS_PER_HOUR + ) - + 1; + break; + case 'minute': + time = this._d.valueOf(); + time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1; + break; + case 'second': + time = this._d.valueOf(); + time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1; + break; + } + + this._d.setTime(time); + hooks.updateOffset(this, true); + return this; + } + + function valueOf() { + return this._d.valueOf() - (this._offset || 0) * 60000; + } + + function unix() { + return Math.floor(this.valueOf() / 1000); + } + + function toDate() { + return new Date(this.valueOf()); + } + + function toArray() { + var m = this; + return [ + m.year(), + m.month(), + m.date(), + m.hour(), + m.minute(), + m.second(), + m.millisecond(), + ]; + } + + function toObject() { + var m = this; + return { + years: m.year(), + months: m.month(), + date: m.date(), + hours: m.hours(), + minutes: m.minutes(), + seconds: m.seconds(), + milliseconds: m.milliseconds(), + }; + } + + function toJSON() { + // new Date(NaN).toJSON() === null + return this.isValid() ? this.toISOString() : null; + } + + function isValid$2() { + return isValid(this); + } + + function parsingFlags() { + return extend({}, getParsingFlags(this)); + } + + function invalidAt() { + return getParsingFlags(this).overflow; + } + + function creationData() { + return { + input: this._i, + format: this._f, + locale: this._locale, + isUTC: this._isUTC, + strict: this._strict, + }; + } + + addFormatToken('N', 0, 0, 'eraAbbr'); + addFormatToken('NN', 0, 0, 'eraAbbr'); + addFormatToken('NNN', 0, 0, 'eraAbbr'); + addFormatToken('NNNN', 0, 0, 'eraName'); + addFormatToken('NNNNN', 0, 0, 'eraNarrow'); + + addFormatToken('y', ['y', 1], 'yo', 'eraYear'); + addFormatToken('y', ['yy', 2], 0, 'eraYear'); + addFormatToken('y', ['yyy', 3], 0, 'eraYear'); + addFormatToken('y', ['yyyy', 4], 0, 'eraYear'); + + addRegexToken('N', matchEraAbbr); + addRegexToken('NN', matchEraAbbr); + addRegexToken('NNN', matchEraAbbr); + addRegexToken('NNNN', matchEraName); + addRegexToken('NNNNN', matchEraNarrow); + + addParseToken( + ['N', 'NN', 'NNN', 'NNNN', 'NNNNN'], + function (input, array, config, token) { + var era = config._locale.erasParse(input, token, config._strict); + if (era) { + getParsingFlags(config).era = era; + } else { + getParsingFlags(config).invalidEra = input; + } + } + ); + + addRegexToken('y', matchUnsigned); + addRegexToken('yy', matchUnsigned); + addRegexToken('yyy', matchUnsigned); + addRegexToken('yyyy', matchUnsigned); + addRegexToken('yo', matchEraYearOrdinal); + + addParseToken(['y', 'yy', 'yyy', 'yyyy'], YEAR); + addParseToken(['yo'], function (input, array, config, token) { + var match; + if (config._locale._eraYearOrdinalRegex) { + match = input.match(config._locale._eraYearOrdinalRegex); + } + + if (config._locale.eraYearOrdinalParse) { + array[YEAR] = config._locale.eraYearOrdinalParse(input, match); + } else { + array[YEAR] = parseInt(input, 10); + } + }); + + function localeEras(m, format) { + var i, + l, + date, + eras = this._eras || getLocale('en')._eras; + for (i = 0, l = eras.length; i < l; ++i) { + switch (typeof eras[i].since) { + case 'string': + // truncate time + date = hooks(eras[i].since).startOf('day'); + eras[i].since = date.valueOf(); + break; + } + + switch (typeof eras[i].until) { + case 'undefined': + eras[i].until = +Infinity; + break; + case 'string': + // truncate time + date = hooks(eras[i].until).startOf('day').valueOf(); + eras[i].until = date.valueOf(); + break; + } + } + return eras; + } + + function localeErasParse(eraName, format, strict) { + var i, + l, + eras = this.eras(), + name, + abbr, + narrow; + eraName = eraName.toUpperCase(); + + for (i = 0, l = eras.length; i < l; ++i) { + name = eras[i].name.toUpperCase(); + abbr = eras[i].abbr.toUpperCase(); + narrow = eras[i].narrow.toUpperCase(); + + if (strict) { + switch (format) { + case 'N': + case 'NN': + case 'NNN': + if (abbr === eraName) { + return eras[i]; + } + break; + + case 'NNNN': + if (name === eraName) { + return eras[i]; + } + break; + + case 'NNNNN': + if (narrow === eraName) { + return eras[i]; + } + break; + } + } else if ([name, abbr, narrow].indexOf(eraName) >= 0) { + return eras[i]; + } + } + } + + function localeErasConvertYear(era, year) { + var dir = era.since <= era.until ? +1 : -1; + if (year === undefined) { + return hooks(era.since).year(); + } else { + return hooks(era.since).year() + (year - era.offset) * dir; + } + } + + function getEraName() { + var i, + l, + val, + eras = this.localeData().eras(); + for (i = 0, l = eras.length; i < l; ++i) { + // truncate time + val = this.clone().startOf('day').valueOf(); + + if (eras[i].since <= val && val <= eras[i].until) { + return eras[i].name; + } + if (eras[i].until <= val && val <= eras[i].since) { + return eras[i].name; + } + } + + return ''; + } + + function getEraNarrow() { + var i, + l, + val, + eras = this.localeData().eras(); + for (i = 0, l = eras.length; i < l; ++i) { + // truncate time + val = this.clone().startOf('day').valueOf(); + + if (eras[i].since <= val && val <= eras[i].until) { + return eras[i].narrow; + } + if (eras[i].until <= val && val <= eras[i].since) { + return eras[i].narrow; + } + } + + return ''; + } + + function getEraAbbr() { + var i, + l, + val, + eras = this.localeData().eras(); + for (i = 0, l = eras.length; i < l; ++i) { + // truncate time + val = this.clone().startOf('day').valueOf(); + + if (eras[i].since <= val && val <= eras[i].until) { + return eras[i].abbr; + } + if (eras[i].until <= val && val <= eras[i].since) { + return eras[i].abbr; + } + } + + return ''; + } + + function getEraYear() { + var i, + l, + dir, + val, + eras = this.localeData().eras(); + for (i = 0, l = eras.length; i < l; ++i) { + dir = eras[i].since <= eras[i].until ? +1 : -1; + + // truncate time + val = this.clone().startOf('day').valueOf(); + + if ( + (eras[i].since <= val && val <= eras[i].until) || + (eras[i].until <= val && val <= eras[i].since) + ) { + return ( + (this.year() - hooks(eras[i].since).year()) * dir + + eras[i].offset + ); + } + } + + return this.year(); + } + + function erasNameRegex(isStrict) { + if (!hasOwnProp(this, '_erasNameRegex')) { + computeErasParse.call(this); + } + return isStrict ? this._erasNameRegex : this._erasRegex; + } + + function erasAbbrRegex(isStrict) { + if (!hasOwnProp(this, '_erasAbbrRegex')) { + computeErasParse.call(this); + } + return isStrict ? this._erasAbbrRegex : this._erasRegex; + } + + function erasNarrowRegex(isStrict) { + if (!hasOwnProp(this, '_erasNarrowRegex')) { + computeErasParse.call(this); + } + return isStrict ? this._erasNarrowRegex : this._erasRegex; + } + + function matchEraAbbr(isStrict, locale) { + return locale.erasAbbrRegex(isStrict); + } + + function matchEraName(isStrict, locale) { + return locale.erasNameRegex(isStrict); + } + + function matchEraNarrow(isStrict, locale) { + return locale.erasNarrowRegex(isStrict); + } + + function matchEraYearOrdinal(isStrict, locale) { + return locale._eraYearOrdinalRegex || matchUnsigned; + } + + function computeErasParse() { + var abbrPieces = [], + namePieces = [], + narrowPieces = [], + mixedPieces = [], + i, + l, + eras = this.eras(); + + for (i = 0, l = eras.length; i < l; ++i) { + namePieces.push(regexEscape(eras[i].name)); + abbrPieces.push(regexEscape(eras[i].abbr)); + narrowPieces.push(regexEscape(eras[i].narrow)); + + mixedPieces.push(regexEscape(eras[i].name)); + mixedPieces.push(regexEscape(eras[i].abbr)); + mixedPieces.push(regexEscape(eras[i].narrow)); + } + + this._erasRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); + this._erasNameRegex = new RegExp('^(' + namePieces.join('|') + ')', 'i'); + this._erasAbbrRegex = new RegExp('^(' + abbrPieces.join('|') + ')', 'i'); + this._erasNarrowRegex = new RegExp( + '^(' + narrowPieces.join('|') + ')', + 'i' + ); + } + + // FORMATTING + + addFormatToken(0, ['gg', 2], 0, function () { + return this.weekYear() % 100; + }); + + addFormatToken(0, ['GG', 2], 0, function () { + return this.isoWeekYear() % 100; + }); + + function addWeekYearFormatToken(token, getter) { + addFormatToken(0, [token, token.length], 0, getter); + } + + addWeekYearFormatToken('gggg', 'weekYear'); + addWeekYearFormatToken('ggggg', 'weekYear'); + addWeekYearFormatToken('GGGG', 'isoWeekYear'); + addWeekYearFormatToken('GGGGG', 'isoWeekYear'); + + // ALIASES + + addUnitAlias('weekYear', 'gg'); + addUnitAlias('isoWeekYear', 'GG'); + + // PRIORITY + + addUnitPriority('weekYear', 1); + addUnitPriority('isoWeekYear', 1); + + // PARSING + + addRegexToken('G', matchSigned); + addRegexToken('g', matchSigned); + addRegexToken('GG', match1to2, match2); + addRegexToken('gg', match1to2, match2); + addRegexToken('GGGG', match1to4, match4); + addRegexToken('gggg', match1to4, match4); + addRegexToken('GGGGG', match1to6, match6); + addRegexToken('ggggg', match1to6, match6); + + addWeekParseToken( + ['gggg', 'ggggg', 'GGGG', 'GGGGG'], + function (input, week, config, token) { + week[token.substr(0, 2)] = toInt(input); + } + ); + + addWeekParseToken(['gg', 'GG'], function (input, week, config, token) { + week[token] = hooks.parseTwoDigitYear(input); + }); + + // MOMENTS + + function getSetWeekYear(input) { + return getSetWeekYearHelper.call( + this, + input, + this.week(), + this.weekday(), + this.localeData()._week.dow, + this.localeData()._week.doy + ); + } + + function getSetISOWeekYear(input) { + return getSetWeekYearHelper.call( + this, + input, + this.isoWeek(), + this.isoWeekday(), + 1, + 4 + ); + } + + function getISOWeeksInYear() { + return weeksInYear(this.year(), 1, 4); + } + + function getISOWeeksInISOWeekYear() { + return weeksInYear(this.isoWeekYear(), 1, 4); + } + + function getWeeksInYear() { + var weekInfo = this.localeData()._week; + return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); + } + + function getWeeksInWeekYear() { + var weekInfo = this.localeData()._week; + return weeksInYear(this.weekYear(), weekInfo.dow, weekInfo.doy); + } + + function getSetWeekYearHelper(input, week, weekday, dow, doy) { + var weeksTarget; + if (input == null) { + return weekOfYear(this, dow, doy).year; + } else { + weeksTarget = weeksInYear(input, dow, doy); + if (week > weeksTarget) { + week = weeksTarget; + } + return setWeekAll.call(this, input, week, weekday, dow, doy); + } + } + + function setWeekAll(weekYear, week, weekday, dow, doy) { + var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy), + date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear); + + this.year(date.getUTCFullYear()); + this.month(date.getUTCMonth()); + this.date(date.getUTCDate()); + return this; + } + + // FORMATTING + + addFormatToken('Q', 0, 'Qo', 'quarter'); + + // ALIASES + + addUnitAlias('quarter', 'Q'); + + // PRIORITY + + addUnitPriority('quarter', 7); + + // PARSING + + addRegexToken('Q', match1); + addParseToken('Q', function (input, array) { + array[MONTH] = (toInt(input) - 1) * 3; + }); + + // MOMENTS + + function getSetQuarter(input) { + return input == null + ? Math.ceil((this.month() + 1) / 3) + : this.month((input - 1) * 3 + (this.month() % 3)); + } + + // FORMATTING + + addFormatToken('D', ['DD', 2], 'Do', 'date'); + + // ALIASES + + addUnitAlias('date', 'D'); + + // PRIORITY + addUnitPriority('date', 9); + + // PARSING + + addRegexToken('D', match1to2); + addRegexToken('DD', match1to2, match2); + addRegexToken('Do', function (isStrict, locale) { + // TODO: Remove "ordinalParse" fallback in next major release. + return isStrict + ? locale._dayOfMonthOrdinalParse || locale._ordinalParse + : locale._dayOfMonthOrdinalParseLenient; + }); + + addParseToken(['D', 'DD'], DATE); + addParseToken('Do', function (input, array) { + array[DATE] = toInt(input.match(match1to2)[0]); + }); + + // MOMENTS + + var getSetDayOfMonth = makeGetSet('Date', true); + + // FORMATTING + + addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear'); + + // ALIASES + + addUnitAlias('dayOfYear', 'DDD'); + + // PRIORITY + addUnitPriority('dayOfYear', 4); + + // PARSING + + addRegexToken('DDD', match1to3); + addRegexToken('DDDD', match3); + addParseToken(['DDD', 'DDDD'], function (input, array, config) { + config._dayOfYear = toInt(input); + }); + + // HELPERS + + // MOMENTS + + function getSetDayOfYear(input) { + var dayOfYear = + Math.round( + (this.clone().startOf('day') - this.clone().startOf('year')) / 864e5 + ) + 1; + return input == null ? dayOfYear : this.add(input - dayOfYear, 'd'); + } + + // FORMATTING + + addFormatToken('m', ['mm', 2], 0, 'minute'); + + // ALIASES + + addUnitAlias('minute', 'm'); + + // PRIORITY + + addUnitPriority('minute', 14); + + // PARSING + + addRegexToken('m', match1to2); + addRegexToken('mm', match1to2, match2); + addParseToken(['m', 'mm'], MINUTE); + + // MOMENTS + + var getSetMinute = makeGetSet('Minutes', false); + + // FORMATTING + + addFormatToken('s', ['ss', 2], 0, 'second'); + + // ALIASES + + addUnitAlias('second', 's'); + + // PRIORITY + + addUnitPriority('second', 15); + + // PARSING + + addRegexToken('s', match1to2); + addRegexToken('ss', match1to2, match2); + addParseToken(['s', 'ss'], SECOND); + + // MOMENTS + + var getSetSecond = makeGetSet('Seconds', false); + + // FORMATTING + + addFormatToken('S', 0, 0, function () { + return ~~(this.millisecond() / 100); + }); + + addFormatToken(0, ['SS', 2], 0, function () { + return ~~(this.millisecond() / 10); + }); + + addFormatToken(0, ['SSS', 3], 0, 'millisecond'); + addFormatToken(0, ['SSSS', 4], 0, function () { + return this.millisecond() * 10; + }); + addFormatToken(0, ['SSSSS', 5], 0, function () { + return this.millisecond() * 100; + }); + addFormatToken(0, ['SSSSSS', 6], 0, function () { + return this.millisecond() * 1000; + }); + addFormatToken(0, ['SSSSSSS', 7], 0, function () { + return this.millisecond() * 10000; + }); + addFormatToken(0, ['SSSSSSSS', 8], 0, function () { + return this.millisecond() * 100000; + }); + addFormatToken(0, ['SSSSSSSSS', 9], 0, function () { + return this.millisecond() * 1000000; + }); + + // ALIASES + + addUnitAlias('millisecond', 'ms'); + + // PRIORITY + + addUnitPriority('millisecond', 16); + + // PARSING + + addRegexToken('S', match1to3, match1); + addRegexToken('SS', match1to3, match2); + addRegexToken('SSS', match1to3, match3); + + var token, getSetMillisecond; + for (token = 'SSSS'; token.length <= 9; token += 'S') { + addRegexToken(token, matchUnsigned); + } + + function parseMs(input, array) { + array[MILLISECOND] = toInt(('0.' + input) * 1000); + } + + for (token = 'S'; token.length <= 9; token += 'S') { + addParseToken(token, parseMs); + } + + getSetMillisecond = makeGetSet('Milliseconds', false); + + // FORMATTING + + addFormatToken('z', 0, 0, 'zoneAbbr'); + addFormatToken('zz', 0, 0, 'zoneName'); + + // MOMENTS + + function getZoneAbbr() { + return this._isUTC ? 'UTC' : ''; + } + + function getZoneName() { + return this._isUTC ? 'Coordinated Universal Time' : ''; + } + + var proto = Moment.prototype; + + proto.add = add; + proto.calendar = calendar$1; + proto.clone = clone; + proto.diff = diff; + proto.endOf = endOf; + proto.format = format; + proto.from = from; + proto.fromNow = fromNow; + proto.to = to; + proto.toNow = toNow; + proto.get = stringGet; + proto.invalidAt = invalidAt; + proto.isAfter = isAfter; + proto.isBefore = isBefore; + proto.isBetween = isBetween; + proto.isSame = isSame; + proto.isSameOrAfter = isSameOrAfter; + proto.isSameOrBefore = isSameOrBefore; + proto.isValid = isValid$2; + proto.lang = lang; + proto.locale = locale; + proto.localeData = localeData; + proto.max = prototypeMax; + proto.min = prototypeMin; + proto.parsingFlags = parsingFlags; + proto.set = stringSet; + proto.startOf = startOf; + proto.subtract = subtract; + proto.toArray = toArray; + proto.toObject = toObject; + proto.toDate = toDate; + proto.toISOString = toISOString; + proto.inspect = inspect; + if (typeof Symbol !== 'undefined' && Symbol.for != null) { + proto[Symbol.for('nodejs.util.inspect.custom')] = function () { + return 'Moment<' + this.format() + '>'; + }; + } + proto.toJSON = toJSON; + proto.toString = toString; + proto.unix = unix; + proto.valueOf = valueOf; + proto.creationData = creationData; + proto.eraName = getEraName; + proto.eraNarrow = getEraNarrow; + proto.eraAbbr = getEraAbbr; + proto.eraYear = getEraYear; + proto.year = getSetYear; + proto.isLeapYear = getIsLeapYear; + proto.weekYear = getSetWeekYear; + proto.isoWeekYear = getSetISOWeekYear; + proto.quarter = proto.quarters = getSetQuarter; + proto.month = getSetMonth; + proto.daysInMonth = getDaysInMonth; + proto.week = proto.weeks = getSetWeek; + proto.isoWeek = proto.isoWeeks = getSetISOWeek; + proto.weeksInYear = getWeeksInYear; + proto.weeksInWeekYear = getWeeksInWeekYear; + proto.isoWeeksInYear = getISOWeeksInYear; + proto.isoWeeksInISOWeekYear = getISOWeeksInISOWeekYear; + proto.date = getSetDayOfMonth; + proto.day = proto.days = getSetDayOfWeek; + proto.weekday = getSetLocaleDayOfWeek; + proto.isoWeekday = getSetISODayOfWeek; + proto.dayOfYear = getSetDayOfYear; + proto.hour = proto.hours = getSetHour; + proto.minute = proto.minutes = getSetMinute; + proto.second = proto.seconds = getSetSecond; + proto.millisecond = proto.milliseconds = getSetMillisecond; + proto.utcOffset = getSetOffset; + proto.utc = setOffsetToUTC; + proto.local = setOffsetToLocal; + proto.parseZone = setOffsetToParsedOffset; + proto.hasAlignedHourOffset = hasAlignedHourOffset; + proto.isDST = isDaylightSavingTime; + proto.isLocal = isLocal; + proto.isUtcOffset = isUtcOffset; + proto.isUtc = isUtc; + proto.isUTC = isUtc; + proto.zoneAbbr = getZoneAbbr; + proto.zoneName = getZoneName; + proto.dates = deprecate( + 'dates accessor is deprecated. Use date instead.', + getSetDayOfMonth + ); + proto.months = deprecate( + 'months accessor is deprecated. Use month instead', + getSetMonth + ); + proto.years = deprecate( + 'years accessor is deprecated. Use year instead', + getSetYear + ); + proto.zone = deprecate( + 'moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', + getSetZone + ); + proto.isDSTShifted = deprecate( + 'isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', + isDaylightSavingTimeShifted + ); + + function createUnix(input) { + return createLocal(input * 1000); + } + + function createInZone() { + return createLocal.apply(null, arguments).parseZone(); + } + + function preParsePostFormat(string) { + return string; + } + + var proto$1 = Locale.prototype; + + proto$1.calendar = calendar; + proto$1.longDateFormat = longDateFormat; + proto$1.invalidDate = invalidDate; + proto$1.ordinal = ordinal; + proto$1.preparse = preParsePostFormat; + proto$1.postformat = preParsePostFormat; + proto$1.relativeTime = relativeTime; + proto$1.pastFuture = pastFuture; + proto$1.set = set; + proto$1.eras = localeEras; + proto$1.erasParse = localeErasParse; + proto$1.erasConvertYear = localeErasConvertYear; + proto$1.erasAbbrRegex = erasAbbrRegex; + proto$1.erasNameRegex = erasNameRegex; + proto$1.erasNarrowRegex = erasNarrowRegex; + + proto$1.months = localeMonths; + proto$1.monthsShort = localeMonthsShort; + proto$1.monthsParse = localeMonthsParse; + proto$1.monthsRegex = monthsRegex; + proto$1.monthsShortRegex = monthsShortRegex; + proto$1.week = localeWeek; + proto$1.firstDayOfYear = localeFirstDayOfYear; + proto$1.firstDayOfWeek = localeFirstDayOfWeek; + + proto$1.weekdays = localeWeekdays; + proto$1.weekdaysMin = localeWeekdaysMin; + proto$1.weekdaysShort = localeWeekdaysShort; + proto$1.weekdaysParse = localeWeekdaysParse; + + proto$1.weekdaysRegex = weekdaysRegex; + proto$1.weekdaysShortRegex = weekdaysShortRegex; + proto$1.weekdaysMinRegex = weekdaysMinRegex; + + proto$1.isPM = localeIsPM; + proto$1.meridiem = localeMeridiem; + + function get$1(format, index, field, setter) { + var locale = getLocale(), + utc = createUTC().set(setter, index); + return locale[field](utc, format); + } + + function listMonthsImpl(format, index, field) { + if (isNumber(format)) { + index = format; + format = undefined; + } + + format = format || ''; + + if (index != null) { + return get$1(format, index, field, 'month'); + } + + var i, + out = []; + for (i = 0; i < 12; i++) { + out[i] = get$1(format, i, field, 'month'); + } + return out; + } + + // () + // (5) + // (fmt, 5) + // (fmt) + // (true) + // (true, 5) + // (true, fmt, 5) + // (true, fmt) + function listWeekdaysImpl(localeSorted, format, index, field) { + if (typeof localeSorted === 'boolean') { + if (isNumber(format)) { + index = format; + format = undefined; + } + + format = format || ''; + } else { + format = localeSorted; + index = format; + localeSorted = false; + + if (isNumber(format)) { + index = format; + format = undefined; + } + + format = format || ''; + } + + var locale = getLocale(), + shift = localeSorted ? locale._week.dow : 0, + i, + out = []; + + if (index != null) { + return get$1(format, (index + shift) % 7, field, 'day'); + } + + for (i = 0; i < 7; i++) { + out[i] = get$1(format, (i + shift) % 7, field, 'day'); + } + return out; + } + + function listMonths(format, index) { + return listMonthsImpl(format, index, 'months'); + } + + function listMonthsShort(format, index) { + return listMonthsImpl(format, index, 'monthsShort'); + } + + function listWeekdays(localeSorted, format, index) { + return listWeekdaysImpl(localeSorted, format, index, 'weekdays'); + } + + function listWeekdaysShort(localeSorted, format, index) { + return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort'); + } + + function listWeekdaysMin(localeSorted, format, index) { + return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin'); + } + + getSetGlobalLocale('en', { + eras: [ + { + since: '0001-01-01', + until: +Infinity, + offset: 1, + name: 'Anno Domini', + narrow: 'AD', + abbr: 'AD', + }, + { + since: '0000-12-31', + until: -Infinity, + offset: 1, + name: 'Before Christ', + narrow: 'BC', + abbr: 'BC', + }, + ], + dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, + ordinal: function (number) { + var b = number % 10, + output = + toInt((number % 100) / 10) === 1 + ? 'th' + : b === 1 + ? 'st' + : b === 2 + ? 'nd' + : b === 3 + ? 'rd' + : 'th'; + return number + output; + }, + }); + + // Side effect imports + + hooks.lang = deprecate( + 'moment.lang is deprecated. Use moment.locale instead.', + getSetGlobalLocale + ); + hooks.langData = deprecate( + 'moment.langData is deprecated. Use moment.localeData instead.', + getLocale + ); + + var mathAbs = Math.abs; + + function abs() { + var data = this._data; + + this._milliseconds = mathAbs(this._milliseconds); + this._days = mathAbs(this._days); + this._months = mathAbs(this._months); + + data.milliseconds = mathAbs(data.milliseconds); + data.seconds = mathAbs(data.seconds); + data.minutes = mathAbs(data.minutes); + data.hours = mathAbs(data.hours); + data.months = mathAbs(data.months); + data.years = mathAbs(data.years); + + return this; + } + + function addSubtract$1(duration, input, value, direction) { + var other = createDuration(input, value); + + duration._milliseconds += direction * other._milliseconds; + duration._days += direction * other._days; + duration._months += direction * other._months; + + return duration._bubble(); + } + + // supports only 2.0-style add(1, 's') or add(duration) + function add$1(input, value) { + return addSubtract$1(this, input, value, 1); + } + + // supports only 2.0-style subtract(1, 's') or subtract(duration) + function subtract$1(input, value) { + return addSubtract$1(this, input, value, -1); + } + + function absCeil(number) { + if (number < 0) { + return Math.floor(number); + } else { + return Math.ceil(number); + } + } + + function bubble() { + var milliseconds = this._milliseconds, + days = this._days, + months = this._months, + data = this._data, + seconds, + minutes, + hours, + years, + monthsFromDays; + + // if we have a mix of positive and negative values, bubble down first + // check: https://github.com/moment/moment/issues/2166 + if ( + !( + (milliseconds >= 0 && days >= 0 && months >= 0) || + (milliseconds <= 0 && days <= 0 && months <= 0) + ) + ) { + milliseconds += absCeil(monthsToDays(months) + days) * 864e5; + days = 0; + months = 0; + } + + // The following code bubbles up values, see the tests for + // examples of what that means. + data.milliseconds = milliseconds % 1000; + + seconds = absFloor(milliseconds / 1000); + data.seconds = seconds % 60; + + minutes = absFloor(seconds / 60); + data.minutes = minutes % 60; + + hours = absFloor(minutes / 60); + data.hours = hours % 24; + + days += absFloor(hours / 24); + + // convert days to months + monthsFromDays = absFloor(daysToMonths(days)); + months += monthsFromDays; + days -= absCeil(monthsToDays(monthsFromDays)); + + // 12 months -> 1 year + years = absFloor(months / 12); + months %= 12; + + data.days = days; + data.months = months; + data.years = years; + + return this; + } + + function daysToMonths(days) { + // 400 years have 146097 days (taking into account leap year rules) + // 400 years have 12 months === 4800 + return (days * 4800) / 146097; + } + + function monthsToDays(months) { + // the reverse of daysToMonths + return (months * 146097) / 4800; + } + + function as(units) { + if (!this.isValid()) { + return NaN; + } + var days, + months, + milliseconds = this._milliseconds; + + units = normalizeUnits(units); + + if (units === 'month' || units === 'quarter' || units === 'year') { + days = this._days + milliseconds / 864e5; + months = this._months + daysToMonths(days); + switch (units) { + case 'month': + return months; + case 'quarter': + return months / 3; + case 'year': + return months / 12; + } + } else { + // handle milliseconds separately because of floating point math errors (issue #1867) + days = this._days + Math.round(monthsToDays(this._months)); + switch (units) { + case 'week': + return days / 7 + milliseconds / 6048e5; + case 'day': + return days + milliseconds / 864e5; + case 'hour': + return days * 24 + milliseconds / 36e5; + case 'minute': + return days * 1440 + milliseconds / 6e4; + case 'second': + return days * 86400 + milliseconds / 1000; + // Math.floor prevents floating point math errors here + case 'millisecond': + return Math.floor(days * 864e5) + milliseconds; + default: + throw new Error('Unknown unit ' + units); + } + } + } + + // TODO: Use this.as('ms')? + function valueOf$1() { + if (!this.isValid()) { + return NaN; + } + return ( + this._milliseconds + + this._days * 864e5 + + (this._months % 12) * 2592e6 + + toInt(this._months / 12) * 31536e6 + ); + } + + function makeAs(alias) { + return function () { + return this.as(alias); + }; + } + + var asMilliseconds = makeAs('ms'), + asSeconds = makeAs('s'), + asMinutes = makeAs('m'), + asHours = makeAs('h'), + asDays = makeAs('d'), + asWeeks = makeAs('w'), + asMonths = makeAs('M'), + asQuarters = makeAs('Q'), + asYears = makeAs('y'); + + function clone$1() { + return createDuration(this); + } + + function get$2(units) { + units = normalizeUnits(units); + return this.isValid() ? this[units + 's']() : NaN; + } + + function makeGetter(name) { + return function () { + return this.isValid() ? this._data[name] : NaN; + }; + } + + var milliseconds = makeGetter('milliseconds'), + seconds = makeGetter('seconds'), + minutes = makeGetter('minutes'), + hours = makeGetter('hours'), + days = makeGetter('days'), + months = makeGetter('months'), + years = makeGetter('years'); + + function weeks() { + return absFloor(this.days() / 7); + } + + var round = Math.round, + thresholds = { + ss: 44, // a few seconds to seconds + s: 45, // seconds to minute + m: 45, // minutes to hour + h: 22, // hours to day + d: 26, // days to month/week + w: null, // weeks to month + M: 11, // months to year + }; + + // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize + function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) { + return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); + } + + function relativeTime$1(posNegDuration, withoutSuffix, thresholds, locale) { + var duration = createDuration(posNegDuration).abs(), + seconds = round(duration.as('s')), + minutes = round(duration.as('m')), + hours = round(duration.as('h')), + days = round(duration.as('d')), + months = round(duration.as('M')), + weeks = round(duration.as('w')), + years = round(duration.as('y')), + 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]); + + if (thresholds.w != null) { + a = + a || + (weeks <= 1 && ['w']) || + (weeks < thresholds.w && ['ww', weeks]); + } + a = a || + (months <= 1 && ['M']) || + (months < thresholds.M && ['MM', months]) || + (years <= 1 && ['y']) || ['yy', years]; + + a[2] = withoutSuffix; + a[3] = +posNegDuration > 0; + a[4] = locale; + return substituteTimeAgo.apply(null, a); + } + + // This function allows you to set the rounding function for relative time strings + function getSetRelativeTimeRounding(roundingFunction) { + if (roundingFunction === undefined) { + return round; + } + if (typeof roundingFunction === 'function') { + round = roundingFunction; + return true; + } + return false; + } + + // This function allows you to set a threshold for relative time strings + function getSetRelativeTimeThreshold(threshold, limit) { + if (thresholds[threshold] === undefined) { + return false; + } + if (limit === undefined) { + return thresholds[threshold]; + } + thresholds[threshold] = limit; + if (threshold === 's') { + thresholds.ss = limit - 1; + } + return true; + } + + function humanize(argWithSuffix, argThresholds) { + if (!this.isValid()) { + return this.localeData().invalidDate(); + } + + var withSuffix = false, + th = thresholds, + locale, + output; + + if (typeof argWithSuffix === 'object') { + argThresholds = argWithSuffix; + argWithSuffix = false; + } + if (typeof argWithSuffix === 'boolean') { + withSuffix = argWithSuffix; + } + if (typeof argThresholds === 'object') { + th = Object.assign({}, thresholds, argThresholds); + if (argThresholds.s != null && argThresholds.ss == null) { + th.ss = argThresholds.s - 1; + } + } + + locale = this.localeData(); + output = relativeTime$1(this, !withSuffix, th, locale); + + if (withSuffix) { + output = locale.pastFuture(+this, output); + } + + return locale.postformat(output); + } + + var abs$1 = Math.abs; + + function sign(x) { + return (x > 0) - (x < 0) || +x; + } + + function toISOString$1() { + // for ISO strings we do not use the normal bubbling rules: + // * milliseconds bubble up until they become hours + // * days do not bubble at all + // * months bubble up until they become years + // This is because there is no context-free conversion between hours and days + // (think of clock changes) + // and also not between days and months (28-31 days per month) + if (!this.isValid()) { + return this.localeData().invalidDate(); + } + + var seconds = abs$1(this._milliseconds) / 1000, + days = abs$1(this._days), + months = abs$1(this._months), + minutes, + hours, + years, + s, + total = this.asSeconds(), + totalSign, + ymSign, + daysSign, + hmsSign; + + if (!total) { + // this is the same as C#'s (Noda) and python (isodate)... + // but not other JS (goog.date) + return 'P0D'; + } + + // 3600 seconds -> 60 minutes -> 1 hour + minutes = absFloor(seconds / 60); + hours = absFloor(minutes / 60); + seconds %= 60; + minutes %= 60; + + // 12 months -> 1 year + years = absFloor(months / 12); + months %= 12; + + // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js + s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : ''; + + totalSign = total < 0 ? '-' : ''; + ymSign = sign(this._months) !== sign(total) ? '-' : ''; + daysSign = sign(this._days) !== sign(total) ? '-' : ''; + hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : ''; + + return ( + totalSign + + 'P' + + (years ? ymSign + years + 'Y' : '') + + (months ? ymSign + months + 'M' : '') + + (days ? daysSign + days + 'D' : '') + + (hours || minutes || seconds ? 'T' : '') + + (hours ? hmsSign + hours + 'H' : '') + + (minutes ? hmsSign + minutes + 'M' : '') + + (seconds ? hmsSign + s + 'S' : '') + ); + } + + var proto$2 = Duration.prototype; + + proto$2.isValid = isValid$1; + proto$2.abs = abs; + proto$2.add = add$1; + proto$2.subtract = subtract$1; + proto$2.as = as; + proto$2.asMilliseconds = asMilliseconds; + proto$2.asSeconds = asSeconds; + proto$2.asMinutes = asMinutes; + proto$2.asHours = asHours; + proto$2.asDays = asDays; + proto$2.asWeeks = asWeeks; + proto$2.asMonths = asMonths; + proto$2.asQuarters = asQuarters; + proto$2.asYears = asYears; + proto$2.valueOf = valueOf$1; + proto$2._bubble = bubble; + proto$2.clone = clone$1; + proto$2.get = get$2; + proto$2.milliseconds = milliseconds; + proto$2.seconds = seconds; + proto$2.minutes = minutes; + proto$2.hours = hours; + proto$2.days = days; + proto$2.weeks = weeks; + proto$2.months = months; + proto$2.years = years; + proto$2.humanize = humanize; + proto$2.toISOString = toISOString$1; + proto$2.toString = toISOString$1; + proto$2.toJSON = toISOString$1; + proto$2.locale = locale; + proto$2.localeData = localeData; + + proto$2.toIsoString = deprecate( + 'toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', + toISOString$1 + ); + proto$2.lang = lang; + + // FORMATTING + + addFormatToken('X', 0, 0, 'unix'); + addFormatToken('x', 0, 0, 'valueOf'); + + // PARSING + + addRegexToken('x', matchSigned); + addRegexToken('X', matchTimestamp); + addParseToken('X', function (input, array, config) { + config._d = new Date(parseFloat(input) * 1000); + }); + addParseToken('x', function (input, array, config) { + config._d = new Date(toInt(input)); + }); + + //! moment.js + + hooks.version = '2.29.4'; + + setHookCallback(createLocal); + + hooks.fn = proto; + hooks.min = min; + hooks.max = max; + hooks.now = now; + hooks.utc = createUTC; + hooks.unix = createUnix; + hooks.months = listMonths; + hooks.isDate = isDate; + hooks.locale = getSetGlobalLocale; + hooks.invalid = createInvalid; + hooks.duration = createDuration; + hooks.isMoment = isMoment; + hooks.weekdays = listWeekdays; + hooks.parseZone = createInZone; + hooks.localeData = getLocale; + hooks.isDuration = isDuration; + hooks.monthsShort = listMonthsShort; + hooks.weekdaysMin = listWeekdaysMin; + hooks.defineLocale = defineLocale; + hooks.updateLocale = updateLocale; + hooks.locales = listLocales; + hooks.weekdaysShort = listWeekdaysShort; + hooks.normalizeUnits = normalizeUnits; + hooks.relativeTimeRounding = getSetRelativeTimeRounding; + hooks.relativeTimeThreshold = getSetRelativeTimeThreshold; + hooks.calendarFormat = getCalendarFormat; + hooks.prototype = proto; + + // currently HTML5 input type only supports 24-hour formats + hooks.HTML5_FMT = { + DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', // + DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', // + DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', // + DATE: 'YYYY-MM-DD', // + TIME: 'HH:mm', // + TIME_SECONDS: 'HH:mm:ss', // + TIME_MS: 'HH:mm:ss.SSS', // + WEEK: 'GGGG-[W]WW', // + MONTH: 'YYYY-MM', // + }; + + return hooks; + + }))); +} (moment$1)); + +var momentExports = moment$1.exports; +var moment = /*@__PURE__*/getDefaultExportFromCjs(momentExports); + +var DefaultContext = { + color: undefined, + size: undefined, + className: undefined, + style: undefined, + attr: undefined +}; +var IconContext = React.createContext && React.createContext(DefaultContext); + +var __assign = undefined && undefined.__assign || function () { + __assign = Object.assign || function (t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +var __rest = undefined && undefined.__rest || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; + } + return t; +}; +function Tree2Element(tree) { + return tree && tree.map(function (node, i) { + return React.createElement(node.tag, __assign({ + key: i + }, node.attr), Tree2Element(node.child)); + }); +} +function GenIcon(data) { + // eslint-disable-next-line react/display-name + return function (props) { + return React.createElement(IconBase, __assign({ + attr: __assign({}, data.attr) + }, props), Tree2Element(data.child)); + }; +} +function IconBase(props) { + var elem = function (conf) { + var attr = props.attr, + size = props.size, + title = props.title, + svgProps = __rest(props, ["attr", "size", "title"]); + var computedSize = size || conf.size || "1em"; + var className; + if (conf.className) className = conf.className; + if (props.className) className = (className ? className + " " : "") + props.className; + return React.createElement("svg", __assign({ + stroke: "currentColor", + fill: "currentColor", + strokeWidth: "0" + }, conf.attr, attr, svgProps, { + className: className, + style: __assign(__assign({ + color: props.color || conf.color + }, conf.style), props.style), + height: computedSize, + width: computedSize, + xmlns: "http://www.w3.org/2000/svg" + }), title && React.createElement("title", null, title), props.children); + }; + return IconContext !== undefined ? React.createElement(IconContext.Consumer, null, function (conf) { + return elem(conf); + }) : elem(DefaultContext); +} + +// THIS FILE IS AUTO GENERATED +function GoChevronDown (props) { + return GenIcon({"tag":"svg","attr":{"viewBox":"0 0 10 16"},"child":[{"tag":"path","attr":{"fillRule":"evenodd","d":"M5 11L0 6l1.5-1.5L5 8.25 8.5 4.5 10 6l-5 5z"}}]})(props); +}function GoChevronUp (props) { + return GenIcon({"tag":"svg","attr":{"viewBox":"0 0 10 16"},"child":[{"tag":"path","attr":{"fillRule":"evenodd","d":"M10 10l-1.5 1.5L5 7.75 1.5 11.5 0 10l5-5 5 5z"}}]})(props); +} + +// THIS FILE IS AUTO GENERATED +function TiMinus (props) { + return GenIcon({"tag":"svg","attr":{"version":"1.2","baseProfile":"tiny","viewBox":"0 0 24 24"},"child":[{"tag":"path","attr":{"d":"M18 11h-12c-1.104 0-2 .896-2 2s.896 2 2 2h12c1.104 0 2-.896 2-2s-.896-2-2-2z"}}]})(props); +} + +var reactTable = {exports: {}}; + +var reactTable_production_min = {exports: {}}; + +(function (module, exports) { + !function(e,t){t(exports,reactExports);}(commonjsGlobal,(function(e,t){function n(e,t,n,o,r,i,u){try{var l=e[i](u),s=l.value;}catch(e){return void n(e)}l.done?t(s):Promise.resolve(s).then(o,r);}function o(e){return function(){var t=this,o=arguments;return new Promise((function(r,i){var u=e.apply(t,o);function l(e){n(u,r,i,l,s,"next",e);}function s(e){n(u,r,i,l,s,"throw",e);}l(void 0);}))}}function r(){return (r=Object.assign||function(e){for(var t=1;t=0||(r[n]=e[n]);return r}function u(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var o=n.call(e,t||"default");if("object"!=typeof o)return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return ("string"===t?String:Number)(e)}(e,"string");return "symbol"==typeof t?t:String(t)}t=t&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t;var l={init:"init"},s=function(e){var t=e.value;return void 0===t?"":t},a=function(){return t.createElement(t.Fragment,null," ")},c={Cell:s,width:150,minWidth:0,maxWidth:Number.MAX_SAFE_INTEGER};function d(){for(var e=arguments.length,t=new Array(e),n=0;n(i="number"==typeof i?i:1/0)){var u=r;r=i,i=u;}return e.filter((function(e){return t.some((function(t){var n=e.values[t];return n>=r&&n<=i}))}))};Ce.autoRemove=function(e){return !e||"number"!=typeof e[0]&&"number"!=typeof e[1]};var xe=Object.freeze({__proto__:null,text:ge,exactText:ve,exactTextCase:me,includes:he,includesAll:ye,includesSome:we,includesValue:Re,exact:be,equals:Se,between:Ce});l.resetFilters="resetFilters",l.setFilter="setFilter",l.setAllFilters="setAllFilters";var Pe=function(e){e.stateReducers.push(Be),e.useInstance.push(Ee);};function Be(e,t,n,o){if(t.type===l.init)return r({filters:[]},e);if(t.type===l.resetFilters)return r({},e,{filters:o.initialState.filters||[]});if(t.type===l.setFilter){var i=t.columnId,u=t.filterValue,s=o.allColumns,a=o.filterTypes,c=s.find((function(e){return e.id===i}));if(!c)throw new Error("React-Table: Could not find a column with id: "+i);var d=k(c.filter,a||{},xe),f=e.filters.find((function(e){return e.id===i})),p=m(u,f&&f.value);return H(d.autoRemove,p,c)?r({},e,{filters:e.filters.filter((function(e){return e.id!==i}))}):r({},e,f?{filters:e.filters.map((function(e){return e.id===i?{id:i,value:p}:e}))}:{filters:[].concat(e.filters,[{id:i,value:p}])})}if(t.type===l.setAllFilters){var g=t.filters,v=o.allColumns,h=o.filterTypes;return r({},e,{filters:m(g,e.filters).filter((function(e){var t=v.find((function(t){return t.id===e.id}));return !H(k(t.filter,h||{},xe).autoRemove,e.value,t)}))})}}function Ee(e){var n=e.data,o=e.rows,r=e.flatRows,i=e.rowsById,u=e.allColumns,s=e.filterTypes,a=e.manualFilters,c=e.defaultCanFilter,d=void 0!==c&&c,f=e.disableFilters,p=e.state.filters,g=e.dispatch,v=e.autoResetFilters,m=void 0===v||v,y=t.useCallback((function(e,t){g({type:l.setFilter,columnId:e,filterValue:t});}),[g]),R=t.useCallback((function(e){g({type:l.setAllFilters,filters:e});}),[g]);u.forEach((function(e){var t=e.id,n=e.accessor,o=e.defaultCanFilter,r=e.disableFilters;e.canFilter=n?I(!0!==r&&void 0,!0!==f&&void 0,!0):I(o,d,!1),e.setFilter=function(t){return y(e.id,t)};var i=p.find((function(e){return e.id===t}));e.filterValue=i&&i.value;}));var b=t.useMemo((function(){if(a||!p.length)return [o,r,i];var e=[],t={};return [function n(o,r){void 0===r&&(r=0);var i=o;return (i=p.reduce((function(e,t){var n=t.id,o=t.value,i=u.find((function(e){return e.id===n}));if(!i)return e;0===r&&(i.preFilteredRows=e);var l=k(i.filter,s||{},xe);return l?(i.filteredRows=l(e,[n],o),i.filteredRows):(console.warn("Could not find a valid 'column.filter' for column with the ID: "+i.id+"."),e)}),o)).forEach((function(o){e.push(o),t[o.id]=o,o.subRows&&(o.subRows=o.subRows&&o.subRows.length>0?n(o.subRows,r+1):o.subRows);})),i}(o),e,t]}),[a,p,o,r,i,u,s]),S=b[0],C=b[1],x=b[2];t.useMemo((function(){u.filter((function(e){return !p.find((function(t){return t.id===e.id}))})).forEach((function(e){e.preFilteredRows=S,e.filteredRows=S;}));}),[S,p,u]);var P=h(m);w((function(){P()&&g({type:l.resetFilters});}),[g,a?null:n]),Object.assign(e,{preFilteredRows:o,preFilteredFlatRows:r,preFilteredRowsById:i,filteredRows:S,filteredFlatRows:C,filteredRowsById:x,rows:S,flatRows:C,rowsById:x,setFilter:y,setAllFilters:R});}Pe.pluginName="useFilters",l.resetGlobalFilter="resetGlobalFilter",l.setGlobalFilter="setGlobalFilter";var Ie=function(e){e.stateReducers.push(Fe),e.useInstance.push(Ge);};function Fe(e,t,n,o){if(t.type===l.resetGlobalFilter)return r({},e,{globalFilter:o.initialState.globalFilter||void 0});if(t.type===l.setGlobalFilter){var u=t.filterValue,s=o.userFilterTypes,a=k(o.globalFilter,s||{},xe),c=m(u,e.globalFilter);if(H(a.autoRemove,c)){e.globalFilter;return i(e,["globalFilter"])}return r({},e,{globalFilter:c})}}function Ge(e){var n=e.data,o=e.rows,r=e.flatRows,i=e.rowsById,u=e.allColumns,s=e.filterTypes,a=e.globalFilter,c=e.manualGlobalFilter,d=e.state.globalFilter,f=e.dispatch,p=e.autoResetGlobalFilter,g=void 0===p||p,v=e.disableGlobalFilter,m=t.useCallback((function(e){f({type:l.setGlobalFilter,filterValue:e});}),[f]),y=t.useMemo((function(){if(c||void 0===d)return [o,r,i];var e=[],t={},n=k(a,s||{},xe);if(!n)return console.warn("Could not find a valid 'globalFilter' option."),o;u.forEach((function(e){var t=e.disableGlobalFilter;e.canFilter=I(!0!==t&&void 0,!0!==v&&void 0,!0);}));var l=u.filter((function(e){return !0===e.canFilter}));return [function o(r){return (r=n(r,l.map((function(e){return e.id})),d)).forEach((function(n){e.push(n),t[n.id]=n,n.subRows=n.subRows&&n.subRows.length?o(n.subRows):n.subRows;})),r}(o),e,t]}),[c,d,a,s,u,o,r,i,v]),R=y[0],b=y[1],S=y[2],C=h(g);w((function(){C()&&f({type:l.resetGlobalFilter});}),[f,c?null:n]),Object.assign(e,{preGlobalFilteredRows:o,preGlobalFilteredFlatRows:r,preGlobalFilteredRowsById:i,globalFilteredRows:R,globalFilteredFlatRows:b,globalFilteredRowsById:S,rows:R,flatRows:b,rowsById:S,setGlobalFilter:m,disableGlobalFilter:v});}function Ae(e,t){return t.reduce((function(e,t){return e+("number"==typeof t?t:0)}),0)}Ie.pluginName="useGlobalFilter";var ke=Object.freeze({__proto__:null,sum:Ae,min:function(e){var t=e[0]||0;return e.forEach((function(e){"number"==typeof e&&(t=Math.min(t,e));})),t},max:function(e){var t=e[0]||0;return e.forEach((function(e){"number"==typeof e&&(t=Math.max(t,e));})),t},minMax:function(e){var t=e[0]||0,n=e[0]||0;return e.forEach((function(e){"number"==typeof e&&(t=Math.min(t,e),n=Math.max(n,e));})),t+".."+n},average:function(e){return Ae(0,e)/e.length},median:function(e){if(!e.length)return null;var t=Math.floor(e.length/2),n=[].concat(e).sort((function(e,t){return e-t}));return e.length%2!=0?n[t]:(n[t-1]+n[t])/2},unique:function(e){return Array.from(new Set(e).values())},uniqueCount:function(e){return new Set(e).size},count:function(e){return e.length}}),He=[],We={};l.resetGroupBy="resetGroupBy",l.setGroupBy="setGroupBy",l.toggleGroupBy="toggleGroupBy";var ze=function(e){e.getGroupByToggleProps=[Te],e.stateReducers.push(Oe),e.visibleColumnsDeps.push((function(e,t){var n=t.instance;return [].concat(e,[n.state.groupBy])})),e.visibleColumns.push(Me),e.useInstance.push(Le),e.prepareRow.push(Ne);};ze.pluginName="useGroupBy";var Te=function(e,t){var n=t.header;return [e,{onClick:n.canGroupBy?function(e){e.persist(),n.toggleGroupBy();}:void 0,style:{cursor:n.canGroupBy?"pointer":void 0},title:"Toggle GroupBy"}]};function Oe(e,t,n,o){if(t.type===l.init)return r({groupBy:[]},e);if(t.type===l.resetGroupBy)return r({},e,{groupBy:o.initialState.groupBy||[]});if(t.type===l.setGroupBy)return r({},e,{groupBy:t.value});if(t.type===l.toggleGroupBy){var i=t.columnId,u=t.value,s=void 0!==u?u:!e.groupBy.includes(i);return r({},e,s?{groupBy:[].concat(e.groupBy,[i])}:{groupBy:e.groupBy.filter((function(e){return e!==i}))})}}function Me(e,t){var n=t.instance.state.groupBy,o=n.map((function(t){return e.find((function(e){return e.id===t}))})).filter(Boolean),r=e.filter((function(e){return !n.includes(e.id)}));return (e=[].concat(o,r)).forEach((function(e){e.isGrouped=n.includes(e.id),e.groupedIndex=n.indexOf(e.id);})),e}var je={};function Le(e){var n=e.data,o=e.rows,i=e.flatRows,u=e.rowsById,s=e.allColumns,a=e.flatHeaders,c=e.groupByFn,d=void 0===c?De:c,p=e.manualGroupBy,g=e.aggregations,m=void 0===g?je:g,y=e.plugins,R=e.state.groupBy,b=e.dispatch,S=e.autoResetGroupBy,C=void 0===S||S,x=e.disableGroupBy,P=e.defaultCanGroupBy,B=e.getHooks;v(y,["useColumnOrder","useFilters"],"useGroupBy");var E=h(e);s.forEach((function(t){var n=t.accessor,o=t.defaultGroupBy,r=t.disableGroupBy;t.canGroupBy=n?I(t.canGroupBy,!0!==r&&void 0,!0!==x&&void 0,!0):I(t.canGroupBy,o,P,!1),t.canGroupBy&&(t.toggleGroupBy=function(){return e.toggleGroupBy(t.id)}),t.Aggregated=t.Aggregated||t.Cell;}));var F=t.useCallback((function(e,t){b({type:l.toggleGroupBy,columnId:e,value:t});}),[b]),A=t.useCallback((function(e){b({type:l.setGroupBy,value:e});}),[b]);a.forEach((function(e){e.getGroupByToggleProps=f(B().getGroupByToggleProps,{instance:E(),header:e});}));var k=t.useMemo((function(){if(p||!R.length)return [o,i,u,He,We,i,u];var e=R.filter((function(e){return s.find((function(t){return t.id===e}))})),t=[],n={},l=[],a={},c=[],f={},g=function o(i,u,p){if(void 0===u&&(u=0),u===e.length)return i.map((function(e){return r({},e,{depth:u})}));var g=e[u],v=d(i,g);return Object.entries(v).map((function(r,i){var d=r[0],v=r[1],h=g+":"+d,y=o(v,u+1,h=p?p+">"+h:h),w=u?G(v,"leafRows"):v,R=function(t,n,o){var r={};return s.forEach((function(i){if(e.includes(i.id))r[i.id]=n[0]?n[0].values[i.id]:null;else {var u="function"==typeof i.aggregate?i.aggregate:m[i.aggregate]||ke[i.aggregate];if(u){var l=n.map((function(e){return e.values[i.id]})),s=t.map((function(e){var t=e.values[i.id];if(!o&&i.aggregateValue){var n="function"==typeof i.aggregateValue?i.aggregateValue:m[i.aggregateValue]||ke[i.aggregateValue];if(!n)throw console.info({column:i}),new Error("React Table: Invalid column.aggregateValue option for column listed above");t=n(t,e,i);}return t}));r[i.id]=u(s,l);}else {if(i.aggregate)throw console.info({column:i}),new Error("React Table: Invalid column.aggregate option for column listed above");r[i.id]=null;}}})),r}(w,v,u),b={id:h,isGrouped:!0,groupByID:g,groupByVal:d,values:R,subRows:y,leafRows:w,depth:u,index:i};return y.forEach((function(e){t.push(e),n[e.id]=e,e.isGrouped?(l.push(e),a[e.id]=e):(c.push(e),f[e.id]=e);})),b}))}(o);return g.forEach((function(e){t.push(e),n[e.id]=e,e.isGrouped?(l.push(e),a[e.id]=e):(c.push(e),f[e.id]=e);})),[g,t,n,l,a,c,f]}),[p,R,o,i,u,s,m,d]),H=k[0],W=k[1],z=k[2],T=k[3],O=k[4],M=k[5],j=k[6],L=h(C);w((function(){L()&&b({type:l.resetGroupBy});}),[b,p?null:n]),Object.assign(e,{preGroupedRows:o,preGroupedFlatRow:i,preGroupedRowsById:u,groupedRows:H,groupedFlatRows:W,groupedRowsById:z,onlyGroupedFlatRows:T,onlyGroupedRowsById:O,nonGroupedFlatRows:M,nonGroupedRowsById:j,rows:H,flatRows:W,rowsById:z,toggleGroupBy:F,setGroupBy:A});}function Ne(e){e.allCells.forEach((function(t){var n;t.isGrouped=t.column.isGrouped&&t.column.id===e.groupByID,t.isPlaceholder=!t.isGrouped&&t.column.isGrouped,t.isAggregated=!t.isGrouped&&!t.isPlaceholder&&(null==(n=e.subRows)?void 0:n.length);}));}function De(e,t){return e.reduce((function(e,n,o){var r=""+n.values[t];return e[r]=Array.isArray(e[r])?e[r]:[],e[r].push(n),e}),{})}var Ve=/([0-9]+)/gm;function _e(e,t){return e===t?0:e>t?1:-1}function Xe(e,t,n){return [e.values[n],t.values[n]]}function qe(e){return "number"==typeof e?isNaN(e)||e===1/0||e===-1/0?"":String(e):"string"==typeof e?e:""}var Ke=Object.freeze({__proto__:null,alphanumeric:function(e,t,n){var o=Xe(e,t,n),r=o[0],i=o[1];for(r=qe(r),i=qe(i),r=r.split(Ve).filter(Boolean),i=i.split(Ve).filter(Boolean);r.length&&i.length;){var u=r.shift(),l=i.shift(),s=parseInt(u,10),a=parseInt(l,10),c=[s,a].sort();if(isNaN(c[0])){if(u>l)return 1;if(l>u)return -1}else {if(isNaN(c[1]))return isNaN(s)?-1:1;if(s>a)return 1;if(a>s)return -1}}return r.length-i.length},datetime:function(e,t,n){var o=Xe(e,t,n),r=o[0],i=o[1];return _e(r=r.getTime(),i=i.getTime())},basic:function(e,t,n){var o=Xe(e,t,n);return _e(o[0],o[1])},string:function(e,t,n){var o=Xe(e,t,n),r=o[0],i=o[1];for(r=r.split("").filter(Boolean),i=i.split("").filter(Boolean);r.length&&i.length;){var u=r.shift(),l=i.shift(),s=u.toLowerCase(),a=l.toLowerCase();if(s>a)return 1;if(a>s)return -1;if(u>l)return 1;if(l>u)return -1}return r.length-i.length},number:function(e,t,n){var o=Xe(e,t,n),r=o[0],i=o[1],u=/[^0-9.]/gi;return _e(r=Number(String(r).replace(u,"")),i=Number(String(i).replace(u,"")))}});l.resetSortBy="resetSortBy",l.setSortBy="setSortBy",l.toggleSortBy="toggleSortBy",l.clearSortBy="clearSortBy",c.sortType="alphanumeric",c.sortDescFirst=!1;var Ue=function(e){e.getSortByToggleProps=[$e],e.stateReducers.push(Je),e.useInstance.push(Ye);};Ue.pluginName="useSortBy";var $e=function(e,t){var n=t.instance,o=t.column,r=n.isMultiSortEvent,i=void 0===r?function(e){return e.shiftKey}:r;return [e,{onClick:o.canSort?function(e){e.persist(),o.toggleSortBy(void 0,!n.disableMultiSort&&i(e));}:void 0,style:{cursor:o.canSort?"pointer":void 0},title:o.canSort?"Toggle SortBy":void 0}]};function Je(e,t,n,o){if(t.type===l.init)return r({sortBy:[]},e);if(t.type===l.resetSortBy)return r({},e,{sortBy:o.initialState.sortBy||[]});if(t.type===l.clearSortBy)return r({},e,{sortBy:e.sortBy.filter((function(e){return e.id!==t.columnId}))});if(t.type===l.setSortBy)return r({},e,{sortBy:t.sortBy});if(t.type===l.toggleSortBy){var i,u=t.columnId,s=t.desc,a=t.multi,c=o.allColumns,d=o.disableMultiSort,f=o.disableSortRemove,p=o.disableMultiRemove,g=o.maxMultiSortColCount,v=void 0===g?Number.MAX_SAFE_INTEGER:g,m=e.sortBy,h=c.find((function(e){return e.id===u})).sortDescFirst,y=m.find((function(e){return e.id===u})),w=m.findIndex((function(e){return e.id===u})),R=null!=s,b=[];return "toggle"!==(i=!d&&a?y?"toggle":"add":w!==m.length-1||1!==m.length?"replace":y?"toggle":"replace")||f||R||a&&p||!(y&&y.desc&&!h||!y.desc&&h)||(i="remove"),"replace"===i?b=[{id:u,desc:R?s:h}]:"add"===i?(b=[].concat(m,[{id:u,desc:R?s:h}])).splice(0,b.length-v):"toggle"===i?b=m.map((function(e){return e.id===u?r({},e,{desc:R?s:!y.desc}):e})):"remove"===i&&(b=m.filter((function(e){return e.id!==u}))),r({},e,{sortBy:b})}}function Ye(e){var n=e.data,o=e.rows,r=e.flatRows,i=e.allColumns,u=e.orderByFn,s=void 0===u?Qe:u,a=e.sortTypes,c=e.manualSortBy,d=e.defaultCanSort,p=e.disableSortBy,g=e.flatHeaders,m=e.state.sortBy,y=e.dispatch,R=e.plugins,b=e.getHooks,S=e.autoResetSortBy,C=void 0===S||S;v(R,["useFilters","useGlobalFilter","useGroupBy","usePivotColumns"],"useSortBy");var x=t.useCallback((function(e){y({type:l.setSortBy,sortBy:e});}),[y]),P=t.useCallback((function(e,t,n){y({type:l.toggleSortBy,columnId:e,desc:t,multi:n});}),[y]),B=h(e);g.forEach((function(e){var t=e.accessor,n=e.canSort,o=e.disableSortBy,r=e.id,i=t?I(!0!==o&&void 0,!0!==p&&void 0,!0):I(d,n,!1);e.canSort=i,e.canSort&&(e.toggleSortBy=function(t,n){return P(e.id,t,n)},e.clearSortBy=function(){y({type:l.clearSortBy,columnId:e.id});}),e.getSortByToggleProps=f(b().getSortByToggleProps,{instance:B(),column:e});var u=m.find((function(e){return e.id===r}));e.isSorted=!!u,e.sortedIndex=m.findIndex((function(e){return e.id===r})),e.isSortedDesc=e.isSorted?u.desc:void 0;}));var E=t.useMemo((function(){if(c||!m.length)return [o,r];var e=[],t=m.filter((function(e){return i.find((function(t){return t.id===e.id}))}));return [function n(o){var r=s(o,t.map((function(e){var t=i.find((function(t){return t.id===e.id}));if(!t)throw new Error("React-Table: Could not find a column with id: "+e.id+" while sorting");var n=t.sortType,o=F(n)||(a||{})[n]||Ke[n];if(!o)throw new Error("React-Table: Could not find a valid sortType of '"+n+"' for column '"+e.id+"'.");return function(t,n){return o(t,n,e.id,e.desc)}})),t.map((function(e){var t=i.find((function(t){return t.id===e.id}));return t&&t.sortInverted?e.desc:!e.desc})));return r.forEach((function(t){e.push(t),t.subRows&&0!==t.subRows.length&&(t.subRows=n(t.subRows));})),r}(o),e]}),[c,m,o,r,i,s,a]),G=E[0],A=E[1],k=h(C);w((function(){k()&&y({type:l.resetSortBy});}),[c?null:n]),Object.assign(e,{preSortedRows:o,preSortedFlatRows:r,sortedRows:G,sortedFlatRows:A,rows:G,flatRows:A,setSortBy:x,toggleSortBy:P});}function Qe(e,t,n){return [].concat(e).sort((function(e,o){for(var r=0;re.pageIndex?a=-1===i?u.length>=e.pageSize:s-1),a?r({},e,{pageIndex:s}):e}if(t.type===l.setPageSize){var c=t.pageSize,d=e.pageSize*e.pageIndex;return r({},e,{pageIndex:Math.floor(d/c),pageSize:c})}}function tt(e){var n=e.rows,o=e.autoResetPage,r=void 0===o||o,i=e.manualExpandedKey,u=void 0===i?"expanded":i,s=e.plugins,a=e.pageCount,c=e.paginateExpandedRows,d=void 0===c||c,f=e.expandSubRows,p=void 0===f||f,g=e.state,m=g.pageSize,y=g.pageIndex,R=g.expanded,b=g.globalFilter,S=g.filters,C=g.groupBy,x=g.sortBy,P=e.dispatch,B=e.data,E=e.manualPagination;v(s,["useGlobalFilter","useFilters","useGroupBy","useSortBy","useExpanded"],"usePagination");var I=h(r);w((function(){I()&&P({type:l.resetPage});}),[P,E?null:B,b,S,C,x]);var F=E?a:Math.ceil(n.length/m),G=t.useMemo((function(){return F>0?[].concat(new Array(F)).fill(null).map((function(e,t){return t})):[]}),[F]),k=t.useMemo((function(){var e;if(E)e=n;else {var t=m*y,o=t+m;e=n.slice(t,o);}return d?e:A(e,{manualExpandedKey:u,expanded:R,expandSubRows:p})}),[p,R,u,E,y,m,d,n]),H=y>0,W=-1===F?k.length>=m:y-1&&i.push(r.splice(t,1)[0]);};r.length&&o.length;)u();return [].concat(i,r)}function At(e){var n=e.dispatch;e.setColumnOrder=t.useCallback((function(e){return n({type:l.setColumnOrder,columnOrder:e})}),[n]);}It.pluginName="useColumnOrder",c.canResize=!0,l.columnStartResizing="columnStartResizing",l.columnResizing="columnResizing",l.columnDoneResizing="columnDoneResizing",l.resetResize="resetResize";var kt=function(e){e.getResizerProps=[Ht],e.getHeaderProps.push({style:{position:"relative"}}),e.stateReducers.push(Wt),e.useInstance.push(Tt),e.useInstanceBeforeDimensions.push(zt);},Ht=function(e,t){var n=t.instance,o=t.header,r=n.dispatch,i=function(e,t){var n=!1;if("touchstart"===e.type){if(e.touches&&e.touches.length>1)return;n=!0;}var o,i,u=function(e){var t=[];return function e(n){n.columns&&n.columns.length&&n.columns.map(e);t.push(n);}(e),t}(t).map((function(e){return [e.id,e.totalWidth]})),s=n?Math.round(e.touches[0].clientX):e.clientX,a=function(){window.cancelAnimationFrame(o),o=null,r({type:l.columnDoneResizing});},c=function(){window.cancelAnimationFrame(o),o=null,r({type:l.columnResizing,clientX:i});},d=function(e){i=e,o||(o=window.requestAnimationFrame(c));},f={mouse:{moveEvent:"mousemove",moveHandler:function(e){return d(e.clientX)},upEvent:"mouseup",upHandler:function(e){document.removeEventListener("mousemove",f.mouse.moveHandler),document.removeEventListener("mouseup",f.mouse.upHandler),a();}},touch:{moveEvent:"touchmove",moveHandler:function(e){return e.cancelable&&(e.preventDefault(),e.stopPropagation()),d(e.touches[0].clientX),!1},upEvent:"touchend",upHandler:function(e){document.removeEventListener(f.touch.moveEvent,f.touch.moveHandler),document.removeEventListener(f.touch.upEvent,f.touch.moveHandler),a();}}},p=n?f.touch:f.mouse,g=!!function(){if("boolean"==typeof z)return z;var e=!1;try{var t={get passive(){return e=!0,!1}};window.addEventListener("test",null,t),window.removeEventListener("test",null,t);}catch(t){e=!1;}return z=e}()&&{passive:!1};document.addEventListener(p.moveEvent,p.moveHandler,g),document.addEventListener(p.upEvent,p.upHandler,g),r({type:l.columnStartResizing,columnId:t.id,columnWidth:t.totalWidth,headerIdWidths:u,clientX:s});};return [e,{onMouseDown:function(e){return e.persist()||i(e,o)},onTouchStart:function(e){return e.persist()||i(e,o)},style:{cursor:"col-resize"},draggable:!1,role:"separator"}]};function Wt(e,t){if(t.type===l.init)return r({columnResizing:{columnWidths:{}}},e);if(t.type===l.resetResize)return r({},e,{columnResizing:{columnWidths:{}}});if(t.type===l.columnStartResizing){var n=t.clientX,o=t.columnId,i=t.columnWidth,u=t.headerIdWidths;return r({},e,{columnResizing:r({},e.columnResizing,{startX:n,headerIdWidths:u,columnWidth:i,isResizingColumn:o})})}if(t.type===l.columnResizing){var s=t.clientX,a=e.columnResizing,c=a.startX,d=a.columnWidth,f=a.headerIdWidths,p=(s-c)/d,g={};return (void 0===f?[]:f).forEach((function(e){var t=e[0],n=e[1];g[t]=Math.max(n+n*p,0);})),r({},e,{columnResizing:r({},e.columnResizing,{columnWidths:r({},e.columnResizing.columnWidths,{},g)})})}return t.type===l.columnDoneResizing?r({},e,{columnResizing:r({},e.columnResizing,{startX:null,isResizingColumn:null})}):void 0}kt.pluginName="useResizeColumns";var zt=function(e){var t=e.flatHeaders,n=e.disableResizing,o=e.getHooks,r=e.state.columnResizing,i=h(e);t.forEach((function(e){var t=I(!0!==e.disableResizing&&void 0,!0!==n&&void 0,!0);e.canResize=t,e.width=r.columnWidths[e.id]||e.originalWidth||e.width,e.isResizing=r.isResizingColumn===e.id,t&&(e.getResizerProps=f(o().getResizerProps,{instance:i(),header:e}));}));};function Tt(e){var n=e.plugins,o=e.dispatch,r=e.autoResetResize,i=void 0===r||r,u=e.columns;v(n,["useAbsoluteLayout"],"useResizeColumns");var s=h(i);w((function(){s()&&o({type:l.resetResize});}),[u]);var a=t.useCallback((function(){return o({type:l.resetResize})}),[o]);Object.assign(e,{resetResizing:a});}var Ot={position:"absolute",top:0},Mt=function(e){e.getTableBodyProps.push(jt),e.getRowProps.push(jt),e.getHeaderGroupProps.push(jt),e.getFooterGroupProps.push(jt),e.getHeaderProps.push((function(e,t){var n=t.column;return [e,{style:r({},Ot,{left:n.totalLeft+"px",width:n.totalWidth+"px"})}]})),e.getCellProps.push((function(e,t){var n=t.cell;return [e,{style:r({},Ot,{left:n.column.totalLeft+"px",width:n.column.totalWidth+"px"})}]})),e.getFooterProps.push((function(e,t){var n=t.column;return [e,{style:r({},Ot,{left:n.totalLeft+"px",width:n.totalWidth+"px"})}]}));};Mt.pluginName="useAbsoluteLayout";var jt=function(e,t){return [e,{style:{position:"relative",width:t.instance.totalColumnsWidth+"px"}}]},Lt={display:"inline-block",boxSizing:"border-box"},Nt=function(e,t){return [e,{style:{display:"flex",width:t.instance.totalColumnsWidth+"px"}}]},Dt=function(e){e.getRowProps.push(Nt),e.getHeaderGroupProps.push(Nt),e.getFooterGroupProps.push(Nt),e.getHeaderProps.push((function(e,t){var n=t.column;return [e,{style:r({},Lt,{width:n.totalWidth+"px"})}]})),e.getCellProps.push((function(e,t){var n=t.cell;return [e,{style:r({},Lt,{width:n.column.totalWidth+"px"})}]})),e.getFooterProps.push((function(e,t){var n=t.column;return [e,{style:r({},Lt,{width:n.totalWidth+"px"})}]}));};function Vt(e){e.getTableProps.push(_t),e.getRowProps.push(Xt),e.getHeaderGroupProps.push(Xt),e.getFooterGroupProps.push(Xt),e.getHeaderProps.push(qt),e.getCellProps.push(Kt),e.getFooterProps.push(Ut);}Dt.pluginName="useBlockLayout",Vt.pluginName="useFlexLayout";var _t=function(e,t){return [e,{style:{minWidth:t.instance.totalColumnsMinWidth+"px"}}]},Xt=function(e,t){return [e,{style:{display:"flex",flex:"1 0 auto",minWidth:t.instance.totalColumnsMinWidth+"px"}}]},qt=function(e,t){var n=t.column;return [e,{style:{boxSizing:"border-box",flex:n.totalFlexWidth?n.totalFlexWidth+" 0 auto":void 0,minWidth:n.totalMinWidth+"px",width:n.totalWidth+"px"}}]},Kt=function(e,t){var n=t.cell;return [e,{style:{boxSizing:"border-box",flex:n.column.totalFlexWidth+" 0 auto",minWidth:n.column.totalMinWidth+"px",width:n.column.totalWidth+"px"}}]},Ut=function(e,t){var n=t.column;return [e,{style:{boxSizing:"border-box",flex:n.totalFlexWidth?n.totalFlexWidth+" 0 auto":void 0,minWidth:n.totalMinWidth+"px",width:n.totalWidth+"px"}}]};function $t(e){e.stateReducers.push(Zt),e.getTableProps.push(Jt),e.getHeaderProps.push(Yt),e.getRowProps.push(Qt);}l.columnStartResizing="columnStartResizing",l.columnResizing="columnResizing",l.columnDoneResizing="columnDoneResizing",l.resetResize="resetResize",$t.pluginName="useGridLayout";var Jt=function(e,t){var n=t.instance;return [e,{style:{display:"grid",gridTemplateColumns:n.visibleColumns.map((function(e){var t;return n.state.gridLayout.columnWidths[e.id]?n.state.gridLayout.columnWidths[e.id]+"px":(null==(t=n.state.columnResizing)?void 0:t.isResizingColumn)?n.state.gridLayout.startWidths[e.id]+"px":"number"==typeof e.width?e.width+"px":e.width})).join(" ")}}]},Yt=function(e,t){var n=t.column;return [e,{id:"header-cell-"+n.id,style:{position:"sticky",gridColumn:"span "+n.totalVisibleHeaderCount}}]},Qt=function(e,t){var n=t.row;return n.isExpanded?[e,{style:{gridColumn:"1 / "+(n.cells.length+1)}}]:[e,{}]};function Zt(e,t,n,o){if(t.type===l.init)return r({gridLayout:{columnWidths:{}}},e);if(t.type===l.resetResize)return r({},e,{gridLayout:{columnWidths:{}}});if(t.type===l.columnStartResizing){var i=t.columnId,u=t.headerIdWidths,s=en(i);if(void 0!==s){var a=o.visibleColumns.reduce((function(e,t){var n;return r({},e,((n={})[t.id]=en(t.id),n))}),{}),c=o.visibleColumns.reduce((function(e,t){var n;return r({},e,((n={})[t.id]=t.minWidth,n))}),{}),d=o.visibleColumns.reduce((function(e,t){var n;return r({},e,((n={})[t.id]=t.maxWidth,n))}),{}),f=u.map((function(e){var t=e[0];return [t,en(t)]}));return r({},e,{gridLayout:r({},e.gridLayout,{startWidths:a,minWidths:c,maxWidths:d,headerIdGridWidths:f,columnWidth:s})})}return e}if(t.type===l.columnResizing){var p=t.clientX,g=e.columnResizing.startX,v=e.gridLayout,m=v.columnWidth,h=v.minWidths,y=v.maxWidths,w=v.headerIdGridWidths,R=(p-g)/m,b={};return (void 0===w?[]:w).forEach((function(e){var t=e[0],n=e[1];b[t]=Math.min(Math.max(h[t],n+n*R),y[t]);})),r({},e,{gridLayout:r({},e.gridLayout,{columnWidths:r({},e.gridLayout.columnWidths,{},b)})})}return t.type===l.columnDoneResizing?r({},e,{gridLayout:r({},e.gridLayout,{startWidths:{},minWidths:{},maxWidths:{}})}):void 0}function en(e){var t,n=null==(t=document.getElementById("header-cell-"+e))?void 0:t.offsetWidth;if(void 0!==n)return n}e._UNSTABLE_usePivotColumns=nt,e.actions=l,e.defaultColumn=c,e.defaultGroupByFn=De,e.defaultOrderByFn=Qe,e.defaultRenderer=s,e.emptyRenderer=a,e.ensurePluginOrder=v,e.flexRender=b,e.functionalUpdate=m,e.loopHooks=g,e.makePropGetter=f,e.makeRenderer=R,e.reduceHooks=p,e.safeUseLayoutEffect=y,e.useAbsoluteLayout=Mt,e.useAsyncDebounce=function(e,n){void 0===n&&(n=0);var r=t.useRef({}),i=h(e),u=h(n);return t.useCallback(function(){var e=o(regeneratorRuntime.mark((function e(){var t,n,l,s=arguments;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:for(t=s.length,n=new Array(t),l=0;l1?n-1:0),i=1;i value === null || value === undefined; + +// eslint-disable-next-line unicorn/prefer-code-point +const strictUriEncode = string => encodeURIComponent(string).replace(/[!'()*]/g, x => `%${x.charCodeAt(0).toString(16).toUpperCase()}`); + +const encodeFragmentIdentifier = Symbol('encodeFragmentIdentifier'); + +function encoderForArrayFormat(options) { + switch (options.arrayFormat) { + case 'index': { + return key => (result, value) => { + const index = result.length; + + if ( + value === undefined + || (options.skipNull && value === null) + || (options.skipEmptyString && value === '') + ) { + return result; + } + + if (value === null) { + return [ + ...result, [encode(key, options), '[', index, ']'].join(''), + ]; + } + + return [ + ...result, + [encode(key, options), '[', encode(index, options), ']=', encode(value, options)].join(''), + ]; + }; + } + + case 'bracket': { + return key => (result, value) => { + if ( + value === undefined + || (options.skipNull && value === null) + || (options.skipEmptyString && value === '') + ) { + return result; + } + + if (value === null) { + return [ + ...result, + [encode(key, options), '[]'].join(''), + ]; + } + + return [ + ...result, + [encode(key, options), '[]=', encode(value, options)].join(''), + ]; + }; + } + + case 'colon-list-separator': { + return key => (result, value) => { + if ( + value === undefined + || (options.skipNull && value === null) + || (options.skipEmptyString && value === '') + ) { + return result; + } + + if (value === null) { + return [ + ...result, + [encode(key, options), ':list='].join(''), + ]; + } + + return [ + ...result, + [encode(key, options), ':list=', encode(value, options)].join(''), + ]; + }; + } + + case 'comma': + case 'separator': + case 'bracket-separator': { + const keyValueSep = options.arrayFormat === 'bracket-separator' + ? '[]=' + : '='; + + return key => (result, value) => { + if ( + value === undefined + || (options.skipNull && value === null) + || (options.skipEmptyString && value === '') + ) { + return result; + } + + // Translate null to an empty string so that it doesn't serialize as 'null' + value = value === null ? '' : value; + + if (result.length === 0) { + return [[encode(key, options), keyValueSep, encode(value, options)].join('')]; + } + + return [[result, encode(value, options)].join(options.arrayFormatSeparator)]; + }; + } + + default: { + return key => (result, value) => { + if ( + value === undefined + || (options.skipNull && value === null) + || (options.skipEmptyString && value === '') + ) { + return result; + } + + if (value === null) { + return [ + ...result, + encode(key, options), + ]; + } + + return [ + ...result, + [encode(key, options), '=', encode(value, options)].join(''), + ]; + }; + } + } +} + +function parserForArrayFormat(options) { + let result; + + switch (options.arrayFormat) { + case 'index': { + return (key, value, accumulator) => { + result = /\[(\d*)]$/.exec(key); + + key = key.replace(/\[\d*]$/, ''); + + if (!result) { + accumulator[key] = value; + return; + } + + if (accumulator[key] === undefined) { + accumulator[key] = {}; + } + + accumulator[key][result[1]] = value; + }; + } + + case 'bracket': { + return (key, value, accumulator) => { + result = /(\[])$/.exec(key); + key = key.replace(/\[]$/, ''); + + if (!result) { + accumulator[key] = value; + return; + } + + if (accumulator[key] === undefined) { + accumulator[key] = [value]; + return; + } + + accumulator[key] = [...accumulator[key], value]; + }; + } + + case 'colon-list-separator': { + return (key, value, accumulator) => { + result = /(:list)$/.exec(key); + key = key.replace(/:list$/, ''); + + if (!result) { + accumulator[key] = value; + return; + } + + if (accumulator[key] === undefined) { + accumulator[key] = [value]; + return; + } + + accumulator[key] = [...accumulator[key], value]; + }; + } + + case 'comma': + case 'separator': { + return (key, value, accumulator) => { + const isArray = typeof value === 'string' && value.includes(options.arrayFormatSeparator); + const isEncodedArray = (typeof value === 'string' && !isArray && decode(value, options).includes(options.arrayFormatSeparator)); + value = isEncodedArray ? decode(value, options) : value; + const newValue = isArray || isEncodedArray ? value.split(options.arrayFormatSeparator).map(item => decode(item, options)) : (value === null ? value : decode(value, options)); + accumulator[key] = newValue; + }; + } + + case 'bracket-separator': { + return (key, value, accumulator) => { + const isArray = /(\[])$/.test(key); + key = key.replace(/\[]$/, ''); + + if (!isArray) { + accumulator[key] = value ? decode(value, options) : value; + return; + } + + const arrayValue = value === null + ? [] + : value.split(options.arrayFormatSeparator).map(item => decode(item, options)); + + if (accumulator[key] === undefined) { + accumulator[key] = arrayValue; + return; + } + + accumulator[key] = [...accumulator[key], ...arrayValue]; + }; + } + + default: { + return (key, value, accumulator) => { + if (accumulator[key] === undefined) { + accumulator[key] = value; + return; + } + + accumulator[key] = [...[accumulator[key]].flat(), value]; + }; + } + } +} + +function validateArrayFormatSeparator(value) { + if (typeof value !== 'string' || value.length !== 1) { + throw new TypeError('arrayFormatSeparator must be single character string'); + } +} + +function encode(value, options) { + if (options.encode) { + return options.strict ? strictUriEncode(value) : encodeURIComponent(value); + } + + return value; +} + +function decode(value, options) { + if (options.decode) { + return decodeUriComponent(value); + } + + return value; +} + +function keysSorter(input) { + if (Array.isArray(input)) { + return input.sort(); + } + + if (typeof input === 'object') { + return keysSorter(Object.keys(input)) + .sort((a, b) => Number(a) - Number(b)) + .map(key => input[key]); + } + + return input; +} + +function removeHash(input) { + const hashStart = input.indexOf('#'); + if (hashStart !== -1) { + input = input.slice(0, hashStart); + } + + return input; +} + +function getHash(url) { + let hash = ''; + const hashStart = url.indexOf('#'); + if (hashStart !== -1) { + hash = url.slice(hashStart); + } + + return hash; +} + +function parseValue(value, options) { + if (options.parseNumbers && !Number.isNaN(Number(value)) && (typeof value === 'string' && value.trim() !== '')) { + value = Number(value); + } else if (options.parseBooleans && value !== null && (value.toLowerCase() === 'true' || value.toLowerCase() === 'false')) { + value = value.toLowerCase() === 'true'; + } + + return value; +} + +function extract(input) { + input = removeHash(input); + const queryStart = input.indexOf('?'); + if (queryStart === -1) { + return ''; + } + + return input.slice(queryStart + 1); +} + +function parse$4(query, options) { + options = { + decode: true, + sort: true, + arrayFormat: 'none', + arrayFormatSeparator: ',', + parseNumbers: false, + parseBooleans: false, + ...options, + }; + + validateArrayFormatSeparator(options.arrayFormatSeparator); + + const formatter = parserForArrayFormat(options); + + // Create an object with no prototype + const returnValue = Object.create(null); + + if (typeof query !== 'string') { + return returnValue; + } + + query = query.trim().replace(/^[?#&]/, ''); + + if (!query) { + return returnValue; + } + + for (const parameter of query.split('&')) { + if (parameter === '') { + continue; + } + + const parameter_ = options.decode ? parameter.replace(/\+/g, ' ') : parameter; + + let [key, value] = splitOnFirst(parameter_, '='); + + if (key === undefined) { + key = parameter_; + } + + // Missing `=` should be `null`: + // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters + value = value === undefined ? null : (['comma', 'separator', 'bracket-separator'].includes(options.arrayFormat) ? value : decode(value, options)); + formatter(decode(key, options), value, returnValue); + } + + for (const [key, value] of Object.entries(returnValue)) { + if (typeof value === 'object' && value !== null) { + for (const [key2, value2] of Object.entries(value)) { + value[key2] = parseValue(value2, options); + } + } else { + returnValue[key] = parseValue(value, options); + } + } + + if (options.sort === false) { + return returnValue; + } + + // TODO: Remove the use of `reduce`. + // eslint-disable-next-line unicorn/no-array-reduce + return (options.sort === true ? Object.keys(returnValue).sort() : Object.keys(returnValue).sort(options.sort)).reduce((result, key) => { + const value = returnValue[key]; + if (Boolean(value) && typeof value === 'object' && !Array.isArray(value)) { + // Sort object keys, not values + result[key] = keysSorter(value); + } else { + result[key] = value; + } + + return result; + }, Object.create(null)); +} + +function stringify(object, options) { + if (!object) { + return ''; + } + + options = {encode: true, + strict: true, + arrayFormat: 'none', + arrayFormatSeparator: ',', ...options}; + + validateArrayFormatSeparator(options.arrayFormatSeparator); + + const shouldFilter = key => ( + (options.skipNull && isNullOrUndefined(object[key])) + || (options.skipEmptyString && object[key] === '') + ); + + const formatter = encoderForArrayFormat(options); + + const objectCopy = {}; + + for (const [key, value] of Object.entries(object)) { + if (!shouldFilter(key)) { + objectCopy[key] = value; + } + } + + const keys = Object.keys(objectCopy); + + if (options.sort !== false) { + keys.sort(options.sort); + } + + return keys.map(key => { + const value = object[key]; + + if (value === undefined) { + return ''; + } + + if (value === null) { + return encode(key, options); + } + + if (Array.isArray(value)) { + if (value.length === 0 && options.arrayFormat === 'bracket-separator') { + return encode(key, options) + '[]'; + } + + return value + .reduce(formatter(key), []) + .join('&'); + } + + return encode(key, options) + '=' + encode(value, options); + }).filter(x => x.length > 0).join('&'); +} + +function parseUrl(url, options) { + options = { + decode: true, + ...options, + }; + + let [url_, hash] = splitOnFirst(url, '#'); + + if (url_ === undefined) { + url_ = url; + } + + return { + url: url_?.split('?')?.[0] ?? '', + query: parse$4(extract(url), options), + ...(options && options.parseFragmentIdentifier && hash ? {fragmentIdentifier: decode(hash, options)} : {}), + }; +} + +function stringifyUrl(object, options) { + options = { + encode: true, + strict: true, + [encodeFragmentIdentifier]: true, + ...options, + }; + + const url = removeHash(object.url).split('?')[0] || ''; + const queryFromUrl = extract(object.url); + + const query = { + ...parse$4(queryFromUrl, {sort: false}), + ...object.query, + }; + + let queryString = stringify(query, options); + if (queryString) { + queryString = `?${queryString}`; + } + + let hash = getHash(object.url); + if (object.fragmentIdentifier) { + const urlObjectForFragmentEncode = new URL(url); + urlObjectForFragmentEncode.hash = object.fragmentIdentifier; + hash = options[encodeFragmentIdentifier] ? urlObjectForFragmentEncode.hash : `#${object.fragmentIdentifier}`; + } + + return `${url}${queryString}${hash}`; +} + +function pick$1(input, filter, options) { + options = { + parseFragmentIdentifier: true, + [encodeFragmentIdentifier]: false, + ...options, + }; + + const {url, query, fragmentIdentifier} = parseUrl(input, options); + + return stringifyUrl({ + url, + query: includeKeys(query, filter), + fragmentIdentifier, + }, options); +} + +function exclude(input, filter, options) { + const exclusionFilter = Array.isArray(filter) ? key => !filter.includes(key) : (key, value) => !filter(key, value); + + return pick$1(input, exclusionFilter, options); +} + +var queryString = /*#__PURE__*/Object.freeze({ + __proto__: null, + exclude: exclude, + extract: extract, + parse: parse$4, + parseUrl: parseUrl, + pick: pick$1, + stringify: stringify, + stringifyUrl: stringifyUrl +}); + +var asctime = function (duration) { + var milliseconds = parseInt("".concat((duration % 1000) / 100), 10), seconds = Math.floor((duration / 1000) % 60), minutes = Math.floor((duration / (1000 * 60)) % 60), hours = Math.floor((duration / (1000 * 60 * 60)) % 24); + var hours_ = hours < 10 ? '0' + hours : hours; + var minutes_ = minutes < 10 ? '0' + minutes : minutes; + var seconds_ = seconds < 10 ? '0' + seconds : seconds; + return hours_ + ':' + minutes_ + ':' + seconds_ + '.' + milliseconds; +}; +var SETTINGS_KEY = 'minimal-history-plugin'; +var loadSettings = function () { + var parsed = queryString.parse(location.hash.substring(location.hash.split('?', 1)[0].length + 1)); + try { + var raw = JSON.parse(localStorage.getItem(SETTINGS_KEY) || '{}'); + return { + showHistoricBadges: !!(raw === null || raw === void 0 ? void 0 : raw.showHistoricBadges) || !!parsed.showHistoricBadges, + showSequenceFlow: !!(raw === null || raw === void 0 ? void 0 : raw.showSequenceFlow) || !!parsed.showSequenceFlow, + leftPaneSize: !!(raw === null || raw === void 0 ? void 0 : raw.leftPaneSize) ? raw.leftPaneSize : null, + topPaneSize: !!(raw === null || raw === void 0 ? void 0 : raw.topPaneSize) ? raw.topPaneSize : null, + }; + } + catch (e) { + return { + showHistoricBadges: false, + showSequenceFlow: false, + leftPaneSize: null, + topPaneSize: null, + }; + } +}; +var saveSettings = function (settings) { + localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings)); +}; + +var Component = {}; + +var toggleSelection = function () { + var selection = document.getSelection(); + if (!selection.rangeCount) { + return function () {}; + } + var active = document.activeElement; + + var ranges = []; + for (var i = 0; i < selection.rangeCount; i++) { + ranges.push(selection.getRangeAt(i)); + } + + switch (active.tagName.toUpperCase()) { // .toUpperCase handles XHTML + case 'INPUT': + case 'TEXTAREA': + active.blur(); + break; + + default: + active = null; + break; + } + + selection.removeAllRanges(); + return function () { + selection.type === 'Caret' && + selection.removeAllRanges(); + + if (!selection.rangeCount) { + ranges.forEach(function(range) { + selection.addRange(range); + }); + } + + active && + active.focus(); + }; +}; + +var deselectCurrent = toggleSelection; + +var clipboardToIE11Formatting = { + "text/plain": "Text", + "text/html": "Url", + "default": "Text" +}; + +var defaultMessage = "Copy to clipboard: #{key}, Enter"; + +function format$2(message) { + var copyKey = (/mac os x/i.test(navigator.userAgent) ? "⌘" : "Ctrl") + "+C"; + return message.replace(/#{\s*key\s*}/g, copyKey); +} + +function copy$1(text, options) { + var debug, + message, + reselectPrevious, + range, + selection, + mark, + success = false; + if (!options) { + options = {}; + } + debug = options.debug || false; + try { + reselectPrevious = deselectCurrent(); + + range = document.createRange(); + selection = document.getSelection(); + + mark = document.createElement("span"); + mark.textContent = text; + // avoid screen readers from reading out loud the text + mark.ariaHidden = "true"; + // reset user styles for span element + mark.style.all = "unset"; + // prevents scrolling to the end of the page + mark.style.position = "fixed"; + mark.style.top = 0; + mark.style.clip = "rect(0, 0, 0, 0)"; + // used to preserve spaces and line breaks + mark.style.whiteSpace = "pre"; + // do not inherit user-select (it may be `none`) + mark.style.webkitUserSelect = "text"; + mark.style.MozUserSelect = "text"; + mark.style.msUserSelect = "text"; + mark.style.userSelect = "text"; + mark.addEventListener("copy", function(e) { + e.stopPropagation(); + if (options.format) { + e.preventDefault(); + if (typeof e.clipboardData === "undefined") { // IE 11 + debug && console.warn("unable to use e.clipboardData"); + debug && console.warn("trying IE specific stuff"); + window.clipboardData.clearData(); + var format = clipboardToIE11Formatting[options.format] || clipboardToIE11Formatting["default"]; + window.clipboardData.setData(format, text); + } else { // all other browsers + e.clipboardData.clearData(); + e.clipboardData.setData(options.format, text); + } + } + if (options.onCopy) { + e.preventDefault(); + options.onCopy(e.clipboardData); + } + }); + + document.body.appendChild(mark); + + range.selectNodeContents(mark); + selection.addRange(range); + + var successful = document.execCommand("copy"); + if (!successful) { + throw new Error("copy command was unsuccessful"); + } + success = true; + } catch (err) { + debug && console.error("unable to copy using execCommand: ", err); + debug && console.warn("trying IE specific stuff"); + try { + window.clipboardData.setData(options.format || "text", text); + options.onCopy && options.onCopy(window.clipboardData); + success = true; + } catch (err) { + debug && console.error("unable to copy using clipboardData: ", err); + debug && console.error("falling back to prompt"); + message = format$2("message" in options ? options.message : defaultMessage); + window.prompt(message, text); + } + } finally { + if (selection) { + if (typeof selection.removeRange == "function") { + selection.removeRange(range); + } else { + selection.removeAllRanges(); + } + } + + if (mark) { + document.body.removeChild(mark); + } + reselectPrevious(); + } + + return success; +} + +var copyToClipboard = copy$1; + +function _typeof$1(obj) { "@babel/helpers - typeof"; return _typeof$1 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof$1(obj); } + +Object.defineProperty(Component, "__esModule", { + value: true +}); +Component.CopyToClipboard = void 0; + +var _react$1 = _interopRequireDefault$5(reactExports); + +var _copyToClipboard = _interopRequireDefault$5(copyToClipboard); + +var _excluded = ["text", "onCopy", "options", "children"]; + +function _interopRequireDefault$5(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty$1(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } + +function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose$1(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } + +function _objectWithoutPropertiesLoose$1(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } + +function _classCallCheck$3(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties$1(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass$2(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$1(Constructor.prototype, protoProps); if (staticProps) _defineProperties$1(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } + +function _inherits$2(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf$2(subClass, superClass); } + +function _setPrototypeOf$2(o, p) { _setPrototypeOf$2 = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf$2(o, p); } + +function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf$1(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf$1(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn$2(this, result); }; } + +function _possibleConstructorReturn$2(self, call) { if (call && (_typeof$1(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized$2(self); } + +function _assertThisInitialized$2(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } + +function _getPrototypeOf$1(o) { _getPrototypeOf$1 = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf$1(o); } + +function _defineProperty$1(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +var CopyToClipboard$2 = /*#__PURE__*/function (_React$PureComponent) { + _inherits$2(CopyToClipboard, _React$PureComponent); + + var _super = _createSuper$1(CopyToClipboard); + + function CopyToClipboard() { + var _this; + + _classCallCheck$3(this, CopyToClipboard); + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + _this = _super.call.apply(_super, [this].concat(args)); + + _defineProperty$1(_assertThisInitialized$2(_this), "onClick", function (event) { + var _this$props = _this.props, + text = _this$props.text, + onCopy = _this$props.onCopy, + children = _this$props.children, + options = _this$props.options; + + var elem = _react$1["default"].Children.only(children); + + var result = (0, _copyToClipboard["default"])(text, options); + + if (onCopy) { + onCopy(text, result); + } // Bypass onClick if it was present + + + if (elem && elem.props && typeof elem.props.onClick === 'function') { + elem.props.onClick(event); + } + }); + + return _this; + } + + _createClass$2(CopyToClipboard, [{ + key: "render", + value: function render() { + var _this$props2 = this.props; + _this$props2.text; + _this$props2.onCopy; + _this$props2.options; + var children = _this$props2.children, + props = _objectWithoutProperties(_this$props2, _excluded); + + var elem = _react$1["default"].Children.only(children); + + return /*#__PURE__*/_react$1["default"].cloneElement(elem, _objectSpread(_objectSpread({}, props), {}, { + onClick: this.onClick + })); + } + }]); + + return CopyToClipboard; +}(_react$1["default"].PureComponent); + +Component.CopyToClipboard = CopyToClipboard$2; + +_defineProperty$1(CopyToClipboard$2, "defaultProps", { + onCopy: undefined, + options: undefined +}); + +var _require = Component, + CopyToClipboard = _require.CopyToClipboard; + +CopyToClipboard.CopyToClipboard = CopyToClipboard; +var lib$1 = CopyToClipboard; + +var CopyToClipboard$1 = /*@__PURE__*/getDefaultExportFromCjs(lib$1); + +// THIS FILE IS AUTO GENERATED +function HiCheck (props) { + return GenIcon({"tag":"svg","attr":{"viewBox":"0 0 20 20","fill":"currentColor","aria-hidden":"true"},"child":[{"tag":"path","attr":{"fillRule":"evenodd","d":"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z","clipRule":"evenodd"}}]})(props); +}function HiClipboardCopy (props) { + return GenIcon({"tag":"svg","attr":{"viewBox":"0 0 20 20","fill":"currentColor","aria-hidden":"true"},"child":[{"tag":"path","attr":{"d":"M8 2a1 1 0 000 2h2a1 1 0 100-2H8z"}},{"tag":"path","attr":{"d":"M3 5a2 2 0 012-2 3 3 0 003 3h2a3 3 0 003-3 2 2 0 012 2v6h-4.586l1.293-1.293a1 1 0 00-1.414-1.414l-3 3a1 1 0 000 1.414l3 3a1 1 0 001.414-1.414L10.414 13H15v3a2 2 0 01-2 2H5a2 2 0 01-2-2V5zM15 11h2a1 1 0 110 2h-2v-2z"}}]})(props); +} + +var Clippy = function (_a) { + var value = _a.value, children = _a.children; + var _b = reactExports.useState(false), mouseOver = _b[0], setMouseOver = _b[1]; + var _c = reactExports.useState(false), copied = _c[0], setCopied = _c[1]; + return (React.createElement("span", { onMouseOver: function () { + if (!mouseOver) { + setMouseOver(true); + } + }, onMouseLeave: function () { + setMouseOver(false); + setCopied(false); + }, style: { display: 'flex', alignItems: 'center' } }, + children, + mouseOver ? (React.createElement(CopyToClipboard$1, { text: value, onCopy: function () { return setCopied(true); } }, + React.createElement("a", { href: "#", onClick: function (e) { + e.preventDefault(); + }, style: { fontSize: '120%', paddingLeft: '0.2em' } }, copied ? (React.createElement(HiCheck, { style: { color: 'green', display: 'flex' } })) : (React.createElement(HiClipboardCopy, { style: { display: 'flex' } }))))) : (React.createElement("span", { style: { fontSize: '120%', width: '1.2em' } })))); +}; + +var AuditLogTable = function (_a) { + var activities = _a.activities, decisions = _a.decisions; + var columns = React.useMemo(function () { return [ + { + Header: 'Activity Name', + accessor: 'activityName', + Cell: function (_a) { + var value = _a.value; + var baseUrl = "".concat(window.location.href.split('#')[0], "/") + .replace(/\/+$/, '/') + .replace(/\/app\/tasklist\//, '/app/cockpit/'); + if (value.activityType === 'businessRuleTask' && decisions.has(value.id)) { + return React.createElement("a", { href: "".concat(baseUrl, "#/decision-instance/").concat(decisions.get(value.id)) }, value.activityName); + } + else if (value.activityType === 'callActivity' && value.calledProcessInstanceId && value.endTime) { + return (React.createElement("a", { href: "".concat(baseUrl, "#/history/process-instance/").concat(value.calledProcessInstanceId) }, value.activityName)); + } + else if (value.activityType === 'callActivity' && value.calledProcessInstanceId) { + return (React.createElement("a", { href: "".concat(baseUrl, "#/process-instance/").concat(value.calledProcessInstanceId, "/runtime") }, value.activityName)); + } + return React.createElement(Clippy, { value: value.activityName }, value.activityName); + }, + }, + { + Header: 'Start Time', + accessor: 'startDate', + Cell: function (_a) { + var value = _a.value; + return (React.createElement(Clippy, { value: value ? value.format('YYYY-MM-DDTHH:mm:ss') : value }, value ? value.format('YYYY-MM-DDTHH:mm:ss') : value)); + }, + }, + { + Header: 'End Time', + accessor: 'endDate', + Cell: function (_a) { + var value = _a.value; + return (React.createElement(Clippy, { value: value ? value.format('YYYY-MM-DDTHH:mm:ss') : value }, value ? value.format('YYYY-MM-DDTHH:mm:ss') : value)); + }, + }, + { + Header: 'Duration', + accessor: 'duration', + Cell: function (_a) { + var value = _a.value; + return React.createElement(Clippy, { value: value }, value); + }, + }, + { + Header: 'Type', + accessor: 'type', + Cell: function (_a) { + var value = _a.value; + return React.createElement(Clippy, { value: value }, value); + }, + }, + { + Header: 'User', + accessor: 'assignee', + Cell: function (_a) { + var value = _a.value; + return React.createElement(Clippy, { value: value }, value); + }, + }, + { + Header: 'Canceled', + accessor: 'canceled', + Cell: function (_a) { + var value = _a.value; + return React.createElement(Clippy, { value: value }, value); + }, + }, + ]; }, [activities, decisions]); + var data = React.useMemo(function () { + return activities.map(function (activity) { + return { + activityName: activity, + startDate: moment(activity.startTime), + endDate: activity.endTime ? moment(activity.endTime) : '', + duration: activity.endTime + ? asctime(new Date(activity.endTime).getTime() - new Date(activity.startTime).getTime()) + : '', + type: activity.activityType, + assignee: activity.assignee, + canceled: activity.canceled ? 'true' : 'false', + }; + }); + }, [activities, decisions]); + var tableInstance = reactTableExports.useTable({ columns: columns, data: data }, reactTableExports.useSortBy); + var getTableProps = tableInstance.getTableProps, getTableBodyProps = tableInstance.getTableBodyProps, headerGroups = tableInstance.headerGroups, rows = tableInstance.rows, prepareRow = tableInstance.prepareRow; + return (React.createElement("table", __assign$1({ className: "cam-table" }, getTableProps()), + React.createElement("thead", null, headerGroups.map(function (headerGroup) { return (React.createElement("tr", __assign$1({}, headerGroup.getHeaderGroupProps()), headerGroup.headers.map(function (column) { return ( + /* @ts-ignore */ + React.createElement("th", __assign$1({}, column.getHeaderProps(column.getSortByToggleProps())), + column.render('Header'), + React.createElement("span", { style: { position: 'absolute', fontSize: '125%' } }, + /* @ts-ignore */ + column.isSorted ? ( + /* @ts-ignore */ + column.isSortedDesc ? (React.createElement(GoChevronDown, { style: { color: '#155cb5' } })) : (React.createElement(GoChevronUp, { style: { color: '#155cb5' } }))) : (React.createElement(TiMinus, { style: { color: '#155cb5' } }))))); }))); })), + React.createElement("tbody", __assign$1({}, getTableBodyProps()), rows.map(function (row) { + prepareRow(row); + return (React.createElement("tr", __assign$1({}, row.getRowProps()), row.cells.map(function (cell) { + return React.createElement("td", __assign$1({}, cell.getCellProps()), cell.render('Cell')); + }))); + })))); +}; + +function e(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}));} + +/** + * Flatten array, one level deep. + * + * @template T + * + * @param {T[][]} arr + * + * @return {T[]} + */ +function flatten(arr) { + return Array.prototype.concat.apply([], arr); +} + +const nativeToString$2 = Object.prototype.toString; +const nativeHasOwnProperty$2 = Object.prototype.hasOwnProperty; + +function isUndefined$3(obj) { + return obj === undefined; +} + +function isDefined(obj) { + return obj !== undefined; +} + +function isNil(obj) { + return obj == null; +} + +function isArray$4(obj) { + return nativeToString$2.call(obj) === '[object Array]'; +} + +function isObject(obj) { + return nativeToString$2.call(obj) === '[object Object]'; +} + +function isNumber(obj) { + return nativeToString$2.call(obj) === '[object Number]'; +} + +/** + * @param {any} obj + * + * @return {boolean} + */ +function isFunction(obj) { + const tag = nativeToString$2.call(obj); + + return ( + tag === '[object Function]' || + tag === '[object AsyncFunction]' || + tag === '[object GeneratorFunction]' || + tag === '[object AsyncGeneratorFunction]' || + tag === '[object Proxy]' + ); +} + +function isString(obj) { + return nativeToString$2.call(obj) === '[object String]'; +} + + +/** + * Ensure collection is an array. + * + * @param {Object} obj + */ +function ensureArray(obj) { + + if (isArray$4(obj)) { + return; + } + + throw new Error('must supply array'); +} + +/** + * Return true, if target owns a property with the given key. + * + * @param {Object} target + * @param {String} key + * + * @return {Boolean} + */ +function has$2(target, key) { + return nativeHasOwnProperty$2.call(target, key); +} + +/** + * @template T + * @typedef { ( + * ((e: T) => boolean) | + * ((e: T, idx: number) => boolean) | + * ((e: T, key: string) => boolean) | + * string | + * number + * ) } Matcher + */ + +/** + * @template T + * @template U + * + * @typedef { ( + * ((e: T) => U) | string | number + * ) } Extractor + */ + + +/** + * @template T + * @typedef { (val: T, key: any) => boolean } MatchFn + */ + +/** + * @template T + * @typedef { T[] } ArrayCollection + */ + +/** + * @template T + * @typedef { { [key: string]: T } } StringKeyValueCollection + */ + +/** + * @template T + * @typedef { { [key: number]: T } } NumberKeyValueCollection + */ + +/** + * @template T + * @typedef { StringKeyValueCollection | NumberKeyValueCollection } KeyValueCollection + */ + +/** + * @template T + * @typedef { KeyValueCollection | ArrayCollection } Collection + */ + +/** + * Find element in collection. + * + * @template T + * @param {Collection} collection + * @param {Matcher} matcher + * + * @return {Object} + */ +function find(collection, matcher) { + + const matchFn = toMatcher(matcher); + + let match; + + forEach$2(collection, function(val, key) { + if (matchFn(val, key)) { + match = val; + + return false; + } + }); + + return match; + +} + + +/** + * Find element index in collection. + * + * @template T + * @param {Collection} collection + * @param {Matcher} matcher + * + * @return {number} + */ +function findIndex$1(collection, matcher) { + + const matchFn = toMatcher(matcher); + + let idx = isArray$4(collection) ? -1 : undefined; + + forEach$2(collection, function(val, key) { + if (matchFn(val, key)) { + idx = key; + + return false; + } + }); + + return idx; +} + + +/** + * Filter elements in collection. + * + * @template T + * @param {Collection} collection + * @param {Matcher} matcher + * + * @return {T[]} result + */ +function filter(collection, matcher) { + + const matchFn = toMatcher(matcher); + + let result = []; + + forEach$2(collection, function(val, key) { + if (matchFn(val, key)) { + result.push(val); + } + }); + + return result; +} + + +/** + * Iterate over collection; returning something + * (non-undefined) will stop iteration. + * + * @template T + * @param {Collection} collection + * @param { ((item: T, idx: number) => (boolean|void)) | ((item: T, key: string) => (boolean|void)) } iterator + * + * @return {T} return result that stopped the iteration + */ +function forEach$2(collection, iterator) { + + let val, + result; + + if (isUndefined$3(collection)) { + return; + } + + const convertKey = isArray$4(collection) ? toNum$2 : identity$2; + + for (let key in collection) { + + if (has$2(collection, key)) { + val = collection[key]; + + result = iterator(val, convertKey(key)); + + if (result === false) { + return val; + } + } + } +} + +/** + * Return collection without element. + * + * @template T + * @param {ArrayCollection} arr + * @param {Matcher} matcher + * + * @return {T[]} + */ +function without(arr, matcher) { + + if (isUndefined$3(arr)) { + return []; + } + + ensureArray(arr); + + const matchFn = toMatcher(matcher); + + return arr.filter(function(el, idx) { + return !matchFn(el, idx); + }); + +} + + +/** + * Reduce collection, returning a single result. + * + * @template T + * @template V + * + * @param {Collection} collection + * @param {(result: V, entry: T, index: any) => V} iterator + * @param {V} result + * + * @return {V} result returned from last iterator + */ +function reduce(collection, iterator, result) { + + forEach$2(collection, function(value, idx) { + result = iterator(result, value, idx); + }); + + return result; +} + + +/** + * Return true if every element in the collection + * matches the criteria. + * + * @param {Object|Array} collection + * @param {Function} matcher + * + * @return {Boolean} + */ +function every(collection, matcher) { + + return !!reduce(collection, function(matches, val, key) { + return matches && matcher(val, key); + }, true); +} + + +/** + * Return true if some elements in the collection + * match the criteria. + * + * @param {Object|Array} collection + * @param {Function} matcher + * + * @return {Boolean} + */ +function some(collection, matcher) { + + return !!find(collection, matcher); +} + + +/** + * Transform a collection into another collection + * by piping each member through the given fn. + * + * @param {Object|Array} collection + * @param {Function} fn + * + * @return {Array} transformed collection + */ +function map$2(collection, fn) { + + let result = []; + + forEach$2(collection, function(val, key) { + result.push(fn(val, key)); + }); + + return result; +} + + +/** + * Get the collections keys. + * + * @param {Object|Array} collection + * + * @return {Array} + */ +function keys(collection) { + return collection && Object.keys(collection) || []; +} + + +/** + * Get the values in the collection. + * + * @param {Object|Array} collection + * + * @return {Array} + */ +function values(collection) { + return map$2(collection, (val) => val); +} + + +/** + * Group collection members by attribute. + * + * @param {Object|Array} collection + * @param {Extractor} extractor + * + * @return {Object} map with { attrValue => [ a, b, c ] } + */ +function groupBy(collection, extractor, grouped = {}) { + + extractor = toExtractor(extractor); + + forEach$2(collection, function(val) { + let discriminator = extractor(val) || '_'; + + let group = grouped[discriminator]; + + if (!group) { + group = grouped[discriminator] = []; + } + + group.push(val); + }); + + return grouped; +} + + +function uniqueBy(extractor, ...collections) { + + extractor = toExtractor(extractor); + + let grouped = {}; + + forEach$2(collections, (c) => groupBy(c, extractor, grouped)); + + let result = map$2(grouped, function(val, key) { + return val[0]; + }); + + return result; +} + + +const unionBy = uniqueBy; + + + +/** + * Sort collection by criteria. + * + * @template T + * + * @param {Collection} collection + * @param {Extractor} extractor + * + * @return {Array} + */ +function sortBy(collection, extractor) { + + extractor = toExtractor(extractor); + + let sorted = []; + + forEach$2(collection, function(value, key) { + let disc = extractor(value, key); + + let entry = { + d: disc, + v: value + }; + + for (var idx = 0; idx < sorted.length; idx++) { + let { d } = sorted[idx]; + + if (disc < d) { + sorted.splice(idx, 0, entry); + return; + } + } + + // not inserted, append (!) + sorted.push(entry); + }); + + return map$2(sorted, (e) => e.v); +} + + +/** + * Create an object pattern matcher. + * + * @example + * + * ```javascript + * const matcher = matchPattern({ id: 1 }); + * + * let element = find(elements, matcher); + * ``` + * + * @template T + * + * @param {T} pattern + * + * @return { (el: any) => boolean } matcherFn + */ +function matchPattern(pattern) { + + return function(el) { + + return every(pattern, function(val, key) { + return el[key] === val; + }); + + }; +} + + +/** + * @param {string | ((e: any) => any) } extractor + * + * @return { (e: any) => any } + */ +function toExtractor(extractor) { + + /** + * @satisfies { (e: any) => any } + */ + return isFunction(extractor) ? extractor : (e) => { + + // @ts-ignore: just works + return e[extractor]; + }; +} + + +/** + * @template T + * @param {Matcher} matcher + * + * @return {MatchFn} + */ +function toMatcher(matcher) { + return isFunction(matcher) ? matcher : (e) => { + return e === matcher; + }; +} + + +function identity$2(arg) { + return arg; +} + +function toNum$2(arg) { + return Number(arg); +} + +/* global setTimeout clearTimeout */ + +/** + * @typedef { { + * (...args: any[]): any; + * flush: () => void; + * cancel: () => void; + * } } DebouncedFunction + */ + +/** + * Debounce fn, calling it only once if the given time + * elapsed between calls. + * + * Lodash-style the function exposes methods to `#clear` + * and `#flush` to control internal behavior. + * + * @param {Function} fn + * @param {Number} timeout + * + * @return {DebouncedFunction} debounced function + */ +function debounce$1(fn, timeout) { + + let timer; + + let lastArgs; + let lastThis; + + let lastNow; + + function fire(force) { + + let now = Date.now(); + + let scheduledDiff = force ? 0 : (lastNow + timeout) - now; + + if (scheduledDiff > 0) { + return schedule(scheduledDiff); + } + + fn.apply(lastThis, lastArgs); + + clear(); + } + + function schedule(timeout) { + timer = setTimeout(fire, timeout); + } + + function clear() { + if (timer) { + clearTimeout(timer); + } + + timer = lastNow = lastArgs = lastThis = undefined; + } + + function flush() { + if (timer) { + fire(true); + } + + clear(); + } + + /** + * @type { DebouncedFunction } + */ + function callback(...args) { + lastNow = Date.now(); + + lastArgs = args; + lastThis = this; + + // ensure an execution is scheduled + if (!timer) { + schedule(timeout); + } + } + + callback.flush = flush; + callback.cancel = clear; + + return callback; +} + +/** + * Bind function against target . + * + * @param {Function} fn + * @param {Object} target + * + * @return {Function} bound function + */ +function bind$2(fn, target) { + return fn.bind(target); +} + +/** + * Convenience wrapper for `Object.assign`. + * + * @param {Object} target + * @param {...Object} others + * + * @return {Object} the target + */ +function assign$3(target, ...others) { + return Object.assign(target, ...others); +} + +/** + * Sets a nested property of a given object to the specified value. + * + * This mutates the object and returns it. + * + * @template T + * + * @param {T} target The target of the set operation. + * @param {(string|number)[]} path The path to the nested value. + * @param {any} value The value to set. + * + * @return {T} + */ +function set$3(target, path, value) { + + let currentTarget = target; + + forEach$2(path, function(key, idx) { + + if (typeof key !== 'number' && typeof key !== 'string') { + throw new Error('illegal key type: ' + typeof key + '. Key should be of type number or string.'); + } + + if (key === 'constructor') { + throw new Error('illegal key: constructor'); + } + + if (key === '__proto__') { + throw new Error('illegal key: __proto__'); + } + + let nextKey = path[idx + 1]; + let nextTarget = currentTarget[key]; + + if (isDefined(nextKey) && isNil(nextTarget)) { + nextTarget = currentTarget[key] = isNaN(+nextKey) ? {} : []; + } + + if (isUndefined$3(nextKey)) { + if (isUndefined$3(value)) { + delete currentTarget[key]; + } else { + currentTarget[key] = value; + } + } else { + currentTarget = nextTarget; + } + }); + + return target; +} + +/** + * Pick properties from the given target. + * + * @template T + * @template {any[]} V + * + * @param {T} target + * @param {V} properties + * + * @return Pick + */ +function pick(target, properties) { + + let result = {}; + + let obj = Object(target); + + forEach$2(properties, function(prop) { + + if (prop in obj) { + result[prop] = target[prop]; + } + }); + + return result; +} + +/** + * Pick all target properties, excluding the given ones. + * + * @template T + * @template {any[]} V + * + * @param {T} target + * @param {V} properties + * + * @return {Omit} target + */ +function omit(target, properties) { + + let result = {}; + + let obj = Object(target); + + forEach$2(obj, function(prop, key) { + + if (properties.indexOf(key) === -1) { + result[key] = prop; + } + }); + + return result; +} + +/** + * @typedef {import('../util/Types').Axis} Axis + * @typedef {import('../util/Types').Point} Point + * @typedef {import('../util/Types').Rect} Rect + */ + +/** + * Computes the distance between two points. + * + * @param {Point} a + * @param {Point} b + * + * @return {number} The distance between the two points. + */ +function pointDistance(a, b) { + if (!a || !b) { + return -1; + } + + return Math.sqrt( + Math.pow(a.x - b.x, 2) + + Math.pow(a.y - b.y, 2) + ); +} + + +/** + * Returns true if the point r is on the line between p and q. + * + * @param {Point} p + * @param {Point} q + * @param {Point} r + * @param {number} [accuracy=5] The accuracy with which to check (lower is better). + * + * @return {boolean} + */ +function pointsOnLine(p, q, r, accuracy) { + + if (typeof accuracy === 'undefined') { + accuracy = 5; + } + + if (!p || !q || !r) { + return false; + } + + var val = (q.x - p.x) * (r.y - p.y) - (q.y - p.y) * (r.x - p.x), + dist = pointDistance(p, q); + + // @see http://stackoverflow.com/a/907491/412190 + return Math.abs(val / dist) <= accuracy; +} + + +var ALIGNED_THRESHOLD = 2; + +/** + * Check whether two points are horizontally or vertically aligned. + * + * @param {Point[]|Point} a + * @param {Point} [b] + * + * @return {string|boolean} If and how the two points are aligned ('h', 'v' or `false`). + */ +function pointsAligned(a, b) { + var points = Array.from(arguments).flat(); + + const axisMap = { + 'x': 'v', + 'y': 'h' + }; + + for (const [ axis, orientation ] of Object.entries(axisMap)) { + if (pointsAlignedOnAxis(axis, points)) { + return orientation; + } + } + + return false; +} + +/** + * @param {Axis} axis + * @param {Point[]} points + * + * @return {boolean} + */ +function pointsAlignedOnAxis(axis, points) { + const referencePoint = points[0]; + + return every(points, function(point) { + return Math.abs(referencePoint[axis] - point[axis]) <= ALIGNED_THRESHOLD; + }); +} + +/** + * Returns true if the point p is inside the rectangle rect + * + * @param {Point} p + * @param {Rect} rect + * @param {number} tolerance + * + * @return {boolean} + */ +function pointInRect(p, rect, tolerance) { + tolerance = tolerance || 0; + + return p.x > rect.x - tolerance && + p.y > rect.y - tolerance && + p.x < rect.x + rect.width + tolerance && + p.y < rect.y + rect.height + tolerance; +} + +/** + * This file contains source code adapted from Snap.svg (licensed Apache-2.0). + * + * @see https://github.com/adobe-webplatform/Snap.svg/blob/master/src/path.js + */ + +/* eslint no-fallthrough: "off" */ + +var p2s = /,?([a-z]),?/gi, + toFloat = parseFloat, + math = Math, + PI = math.PI, + mmin = math.min, + mmax = math.max, + pow = math.pow, + abs$4 = math.abs, + pathCommand = /([a-z])[\s,]*((-?\d*\.?\d*(?:e[-+]?\d+)?[\s]*,?[\s]*)+)/ig, + pathValues = /(-?\d*\.?\d*(?:e[-+]?\d+)?)[\s]*,?[\s]*/ig; + +var isArray$3 = Array.isArray || function(o) { return o instanceof Array; }; + +function hasProperty(obj, property) { + return Object.prototype.hasOwnProperty.call(obj, property); +} + +function clone$1(obj) { + + if (typeof obj == 'function' || Object(obj) !== obj) { + return obj; + } + + var res = new obj.constructor; + + for (var key in obj) { + if (hasProperty(obj, key)) { + res[key] = clone$1(obj[key]); + } + } + + return res; +} + +function repush(array, item) { + for (var i = 0, ii = array.length; i < ii; i++) if (array[i] === item) { + return array.push(array.splice(i, 1)[0]); + } +} + +function cacher(f) { + + function newf() { + + var arg = Array.prototype.slice.call(arguments, 0), + args = arg.join('\u2400'), + cache = newf.cache = newf.cache || {}, + count = newf.count = newf.count || []; + + if (hasProperty(cache, args)) { + repush(count, args); + return cache[args]; + } + + count.length >= 1e3 && delete cache[count.shift()]; + count.push(args); + cache[args] = f.apply(0, arg); + + return cache[args]; + } + return newf; +} + +function parsePathString(pathString) { + + if (!pathString) { + return null; + } + + var pth = paths(pathString); + + if (pth.arr) { + return clone$1(pth.arr); + } + + var paramCounts = { a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0 }, + data = []; + + if (isArray$3(pathString) && isArray$3(pathString[0])) { // rough assumption + data = clone$1(pathString); + } + + if (!data.length) { + + String(pathString).replace(pathCommand, function(a, b, c) { + var params = [], + name = b.toLowerCase(); + + c.replace(pathValues, function(a, b) { + b && params.push(+b); + }); + + if (name == 'm' && params.length > 2) { + data.push([b].concat(params.splice(0, 2))); + name = 'l'; + b = b == 'm' ? 'l' : 'L'; + } + + while (params.length >= paramCounts[name]) { + data.push([b].concat(params.splice(0, paramCounts[name]))); + if (!paramCounts[name]) { + break; + } + } + }); + } + + data.toString = paths.toString; + pth.arr = clone$1(data); + + return data; +} + +function paths(ps) { + var p = paths.ps = paths.ps || {}; + + if (p[ps]) { + p[ps].sleep = 100; + } else { + p[ps] = { + sleep: 100 + }; + } + + setTimeout(function() { + for (var key in p) { + if (hasProperty(p, key) && key != ps) { + p[key].sleep--; + !p[key].sleep && delete p[key]; + } + } + }); + + return p[ps]; +} + +function rectBBox(x, y, width, height) { + + if (arguments.length === 1) { + y = x.y; + width = x.width; + height = x.height; + x = x.x; + } + + return { + x: x, + y: y, + width: width, + height: height, + x2: x + width, + y2: y + height + }; +} + +function pathToString() { + return this.join(',').replace(p2s, '$1'); +} + +function pathClone(pathArray) { + var res = clone$1(pathArray); + res.toString = pathToString; + return res; +} + +function findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) { + var t1 = 1 - t, + t13 = pow(t1, 3), + t12 = pow(t1, 2), + t2 = t * t, + t3 = t2 * t, + x = t13 * p1x + t12 * 3 * t * c1x + t1 * 3 * t * t * c2x + t3 * p2x, + y = t13 * p1y + t12 * 3 * t * c1y + t1 * 3 * t * t * c2y + t3 * p2y; + + return { + x: fixError(x), + y: fixError(y) + }; +} + +function bezierBBox(points) { + + var bbox = curveBBox.apply(null, points); + + return rectBBox( + bbox.x0, + bbox.y0, + bbox.x1 - bbox.x0, + bbox.y1 - bbox.y0 + ); +} + +function isPointInsideBBox$2(bbox, x, y) { + return x >= bbox.x && + x <= bbox.x + bbox.width && + y >= bbox.y && + y <= bbox.y + bbox.height; +} + +function isBBoxIntersect(bbox1, bbox2) { + bbox1 = rectBBox(bbox1); + bbox2 = rectBBox(bbox2); + return isPointInsideBBox$2(bbox2, bbox1.x, bbox1.y) + || isPointInsideBBox$2(bbox2, bbox1.x2, bbox1.y) + || isPointInsideBBox$2(bbox2, bbox1.x, bbox1.y2) + || isPointInsideBBox$2(bbox2, bbox1.x2, bbox1.y2) + || isPointInsideBBox$2(bbox1, bbox2.x, bbox2.y) + || isPointInsideBBox$2(bbox1, bbox2.x2, bbox2.y) + || isPointInsideBBox$2(bbox1, bbox2.x, bbox2.y2) + || isPointInsideBBox$2(bbox1, bbox2.x2, bbox2.y2) + || (bbox1.x < bbox2.x2 && bbox1.x > bbox2.x + || bbox2.x < bbox1.x2 && bbox2.x > bbox1.x) + && (bbox1.y < bbox2.y2 && bbox1.y > bbox2.y + || bbox2.y < bbox1.y2 && bbox2.y > bbox1.y); +} + +function base3(t, p1, p2, p3, p4) { + var t1 = -3 * p1 + 9 * p2 - 9 * p3 + 3 * p4, + t2 = t * t1 + 6 * p1 - 12 * p2 + 6 * p3; + return t * t2 - 3 * p1 + 3 * p2; +} + +function bezlen(x1, y1, x2, y2, x3, y3, x4, y4, z) { + + if (z == null) { + z = 1; + } + + z = z > 1 ? 1 : z < 0 ? 0 : z; + + var z2 = z / 2, + n = 12, + Tvalues = [-.1252,.1252,-.3678,.3678,-.5873,.5873,-.7699,.7699,-.9041,.9041,-.9816,.9816], + Cvalues = [0.2491,0.2491,0.2335,0.2335,0.2032,0.2032,0.1601,0.1601,0.1069,0.1069,0.0472,0.0472], + sum = 0; + + for (var i = 0; i < n; i++) { + var ct = z2 * Tvalues[i] + z2, + xbase = base3(ct, x1, x2, x3, x4), + ybase = base3(ct, y1, y2, y3, y4), + comb = xbase * xbase + ybase * ybase; + + sum += Cvalues[i] * math.sqrt(comb); + } + + return z2 * sum; +} + + +function intersectLines(x1, y1, x2, y2, x3, y3, x4, y4) { + + if ( + mmax(x1, x2) < mmin(x3, x4) || + mmin(x1, x2) > mmax(x3, x4) || + mmax(y1, y2) < mmin(y3, y4) || + mmin(y1, y2) > mmax(y3, y4) + ) { + return; + } + + var nx = (x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4), + ny = (x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4), + denominator = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); + + if (!denominator) { + return; + } + + var px = fixError(nx / denominator), + py = fixError(ny / denominator), + px2 = +px.toFixed(2), + py2 = +py.toFixed(2); + + if ( + px2 < +mmin(x1, x2).toFixed(2) || + px2 > +mmax(x1, x2).toFixed(2) || + px2 < +mmin(x3, x4).toFixed(2) || + px2 > +mmax(x3, x4).toFixed(2) || + py2 < +mmin(y1, y2).toFixed(2) || + py2 > +mmax(y1, y2).toFixed(2) || + py2 < +mmin(y3, y4).toFixed(2) || + py2 > +mmax(y3, y4).toFixed(2) + ) { + return; + } + + return { x: px, y: py }; +} + +function fixError(number) { + return Math.round(number * 100000000000) / 100000000000; +} + +function findBezierIntersections(bez1, bez2, justCount) { + var bbox1 = bezierBBox(bez1), + bbox2 = bezierBBox(bez2); + + if (!isBBoxIntersect(bbox1, bbox2)) { + return justCount ? 0 : []; + } + + // As an optimization, lines will have only 1 segment + + var l1 = bezlen.apply(0, bez1), + l2 = bezlen.apply(0, bez2), + n1 = isLine(bez1) ? 1 : ~~(l1 / 5) || 1, + n2 = isLine(bez2) ? 1 : ~~(l2 / 5) || 1, + dots1 = [], + dots2 = [], + xy = {}, + res = justCount ? 0 : []; + + for (var i = 0; i < n1 + 1; i++) { + var p = findDotsAtSegment.apply(0, bez1.concat(i / n1)); + dots1.push({ x: p.x, y: p.y, t: i / n1 }); + } + + for (i = 0; i < n2 + 1; i++) { + p = findDotsAtSegment.apply(0, bez2.concat(i / n2)); + dots2.push({ x: p.x, y: p.y, t: i / n2 }); + } + + for (i = 0; i < n1; i++) { + + for (var j = 0; j < n2; j++) { + var di = dots1[i], + di1 = dots1[i + 1], + dj = dots2[j], + dj1 = dots2[j + 1], + ci = abs$4(di1.x - di.x) < .01 ? 'y' : 'x', + cj = abs$4(dj1.x - dj.x) < .01 ? 'y' : 'x', + is = intersectLines(di.x, di.y, di1.x, di1.y, dj.x, dj.y, dj1.x, dj1.y), + key; + + if (is) { + key = is.x.toFixed(9) + '#' + is.y.toFixed(9); + + if (xy[key]) { + continue; + } + + xy[key] = true; + + var t1 = di.t + abs$4((is[ci] - di[ci]) / (di1[ci] - di[ci])) * (di1.t - di.t), + t2 = dj.t + abs$4((is[cj] - dj[cj]) / (dj1[cj] - dj[cj])) * (dj1.t - dj.t); + + if (t1 >= 0 && t1 <= 1 && t2 >= 0 && t2 <= 1) { + + if (justCount) { + res++; + } else { + res.push({ + x: is.x, + y: is.y, + t1: t1, + t2: t2 + }); + } + } + } + } + } + + return res; +} + + +/** + * Find or counts the intersections between two SVG paths. + * + * Returns a number in counting mode and a list of intersections otherwise. + * + * A single intersection entry contains the intersection coordinates (x, y) + * as well as additional information regarding the intersecting segments + * on each path (segment1, segment2) and the relative location of the + * intersection on these segments (t1, t2). + * + * The path may be an SVG path string or a list of path components + * such as `[ [ 'M', 0, 10 ], [ 'L', 20, 0 ] ]`. + * + * @example + * + * var intersections = findPathIntersections( + * 'M0,0L100,100', + * [ [ 'M', 0, 100 ], [ 'L', 100, 0 ] ] + * ); + * + * // intersections = [ + * // { x: 50, y: 50, segment1: 1, segment2: 1, t1: 0.5, t2: 0.5 } + * // ] + * + * @param {String|Array} path1 + * @param {String|Array} path2 + * @param {Boolean} [justCount=false] + * + * @return {Array|Number} + */ +function findPathIntersections(path1, path2, justCount) { + path1 = pathToCurve(path1); + path2 = pathToCurve(path2); + + var x1, y1, x2, y2, x1m, y1m, x2m, y2m, bez1, bez2, + res = justCount ? 0 : []; + + for (var i = 0, ii = path1.length; i < ii; i++) { + var pi = path1[i]; + + if (pi[0] == 'M') { + x1 = x1m = pi[1]; + y1 = y1m = pi[2]; + } else { + + if (pi[0] == 'C') { + bez1 = [x1, y1].concat(pi.slice(1)); + x1 = bez1[6]; + y1 = bez1[7]; + } else { + bez1 = [x1, y1, x1, y1, x1m, y1m, x1m, y1m]; + x1 = x1m; + y1 = y1m; + } + + for (var j = 0, jj = path2.length; j < jj; j++) { + var pj = path2[j]; + + if (pj[0] == 'M') { + x2 = x2m = pj[1]; + y2 = y2m = pj[2]; + } else { + + if (pj[0] == 'C') { + bez2 = [x2, y2].concat(pj.slice(1)); + x2 = bez2[6]; + y2 = bez2[7]; + } else { + bez2 = [x2, y2, x2, y2, x2m, y2m, x2m, y2m]; + x2 = x2m; + y2 = y2m; + } + + var intr = findBezierIntersections(bez1, bez2, justCount); + + if (justCount) { + res += intr; + } else { + + for (var k = 0, kk = intr.length; k < kk; k++) { + intr[k].segment1 = i; + intr[k].segment2 = j; + intr[k].bez1 = bez1; + intr[k].bez2 = bez2; + } + + res = res.concat(intr); + } + } + } + } + } + + return res; +} + + +function pathToAbsolute(pathArray) { + var pth = paths(pathArray); + + if (pth.abs) { + return pathClone(pth.abs); + } + + if (!isArray$3(pathArray) || !isArray$3(pathArray && pathArray[0])) { // rough assumption + pathArray = parsePathString(pathArray); + } + + if (!pathArray || !pathArray.length) { + return [['M', 0, 0]]; + } + + var res = [], + x = 0, + y = 0, + mx = 0, + my = 0, + start = 0, + pa0; + + if (pathArray[0][0] == 'M') { + x = +pathArray[0][1]; + y = +pathArray[0][2]; + mx = x; + my = y; + start++; + res[0] = ['M', x, y]; + } + + for (var r, pa, i = start, ii = pathArray.length; i < ii; i++) { + res.push(r = []); + pa = pathArray[i]; + pa0 = pa[0]; + + if (pa0 != pa0.toUpperCase()) { + r[0] = pa0.toUpperCase(); + + switch (r[0]) { + case 'A': + r[1] = pa[1]; + r[2] = pa[2]; + r[3] = pa[3]; + r[4] = pa[4]; + r[5] = pa[5]; + r[6] = +pa[6] + x; + r[7] = +pa[7] + y; + break; + case 'V': + r[1] = +pa[1] + y; + break; + case 'H': + r[1] = +pa[1] + x; + break; + case 'M': + mx = +pa[1] + x; + my = +pa[2] + y; + default: + for (var j = 1, jj = pa.length; j < jj; j++) { + r[j] = +pa[j] + ((j % 2) ? x : y); + } + } + } else { + for (var k = 0, kk = pa.length; k < kk; k++) { + r[k] = pa[k]; + } + } + pa0 = pa0.toUpperCase(); + + switch (r[0]) { + case 'Z': + x = +mx; + y = +my; + break; + case 'H': + x = r[1]; + break; + case 'V': + y = r[1]; + break; + case 'M': + mx = r[r.length - 2]; + my = r[r.length - 1]; + default: + x = r[r.length - 2]; + y = r[r.length - 1]; + } + } + + res.toString = pathToString; + pth.abs = pathClone(res); + + return res; +} + +function isLine(bez) { + return ( + bez[0] === bez[2] && + bez[1] === bez[3] && + bez[4] === bez[6] && + bez[5] === bez[7] + ); +} + +function lineToCurve(x1, y1, x2, y2) { + return [ + x1, y1, x2, + y2, x2, y2 + ]; +} + +function qubicToCurve(x1, y1, ax, ay, x2, y2) { + var _13 = 1 / 3, + _23 = 2 / 3; + + return [ + _13 * x1 + _23 * ax, + _13 * y1 + _23 * ay, + _13 * x2 + _23 * ax, + _13 * y2 + _23 * ay, + x2, + y2 + ]; +} + +function arcToCurve(x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) { + + // for more information of where this math came from visit: + // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes + var _120 = PI * 120 / 180, + rad = PI / 180 * (+angle || 0), + res = [], + xy, + rotate = cacher(function(x, y, rad) { + var X = x * math.cos(rad) - y * math.sin(rad), + Y = x * math.sin(rad) + y * math.cos(rad); + + return { x: X, y: Y }; + }); + + if (!recursive) { + xy = rotate(x1, y1, -rad); + x1 = xy.x; + y1 = xy.y; + xy = rotate(x2, y2, -rad); + x2 = xy.x; + y2 = xy.y; + + var x = (x1 - x2) / 2, + y = (y1 - y2) / 2; + + var h = (x * x) / (rx * rx) + (y * y) / (ry * ry); + + if (h > 1) { + h = math.sqrt(h); + rx = h * rx; + ry = h * ry; + } + + var rx2 = rx * rx, + ry2 = ry * ry, + k = (large_arc_flag == sweep_flag ? -1 : 1) * + math.sqrt(abs$4((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))), + cx = k * rx * y / ry + (x1 + x2) / 2, + cy = k * -ry * x / rx + (y1 + y2) / 2, + f1 = math.asin(((y1 - cy) / ry).toFixed(9)), + f2 = math.asin(((y2 - cy) / ry).toFixed(9)); + + f1 = x1 < cx ? PI - f1 : f1; + f2 = x2 < cx ? PI - f2 : f2; + f1 < 0 && (f1 = PI * 2 + f1); + f2 < 0 && (f2 = PI * 2 + f2); + + if (sweep_flag && f1 > f2) { + f1 = f1 - PI * 2; + } + if (!sweep_flag && f2 > f1) { + f2 = f2 - PI * 2; + } + } else { + f1 = recursive[0]; + f2 = recursive[1]; + cx = recursive[2]; + cy = recursive[3]; + } + + var df = f2 - f1; + + if (abs$4(df) > _120) { + var f2old = f2, + x2old = x2, + y2old = y2; + + f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1); + x2 = cx + rx * math.cos(f2); + y2 = cy + ry * math.sin(f2); + res = arcToCurve(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]); + } + + df = f2 - f1; + + var c1 = math.cos(f1), + s1 = math.sin(f1), + c2 = math.cos(f2), + s2 = math.sin(f2), + t = math.tan(df / 4), + hx = 4 / 3 * rx * t, + hy = 4 / 3 * ry * t, + m1 = [x1, y1], + m2 = [x1 + hx * s1, y1 - hy * c1], + m3 = [x2 + hx * s2, y2 - hy * c2], + m4 = [x2, y2]; + + m2[0] = 2 * m1[0] - m2[0]; + m2[1] = 2 * m1[1] - m2[1]; + + if (recursive) { + return [m2, m3, m4].concat(res); + } else { + res = [m2, m3, m4].concat(res).join().split(','); + var newres = []; + + for (var i = 0, ii = res.length; i < ii; i++) { + newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x; + } + + return newres; + } +} + +// Returns bounding box of cubic bezier curve. +// Source: http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html +// Original version: NISHIO Hirokazu +// Modifications: https://github.com/timo22345 +function curveBBox(x0, y0, x1, y1, x2, y2, x3, y3) { + var tvalues = [], + bounds = [[], []], + a, b, c, t, t1, t2, b2ac, sqrtb2ac; + + for (var i = 0; i < 2; ++i) { + + if (i == 0) { + b = 6 * x0 - 12 * x1 + 6 * x2; + a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3; + c = 3 * x1 - 3 * x0; + } else { + b = 6 * y0 - 12 * y1 + 6 * y2; + a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3; + c = 3 * y1 - 3 * y0; + } + + if (abs$4(a) < 1e-12) { + + if (abs$4(b) < 1e-12) { + continue; + } + + t = -c / b; + + if (0 < t && t < 1) { + tvalues.push(t); + } + + continue; + } + + b2ac = b * b - 4 * c * a; + sqrtb2ac = math.sqrt(b2ac); + + if (b2ac < 0) { + continue; + } + + t1 = (-b + sqrtb2ac) / (2 * a); + + if (0 < t1 && t1 < 1) { + tvalues.push(t1); + } + + t2 = (-b - sqrtb2ac) / (2 * a); + + if (0 < t2 && t2 < 1) { + tvalues.push(t2); + } + } + + var j = tvalues.length, + jlen = j, + mt; + + while (j--) { + t = tvalues[j]; + mt = 1 - t; + bounds[0][j] = (mt * mt * mt * x0) + (3 * mt * mt * t * x1) + (3 * mt * t * t * x2) + (t * t * t * x3); + bounds[1][j] = (mt * mt * mt * y0) + (3 * mt * mt * t * y1) + (3 * mt * t * t * y2) + (t * t * t * y3); + } + + bounds[0][jlen] = x0; + bounds[1][jlen] = y0; + bounds[0][jlen + 1] = x3; + bounds[1][jlen + 1] = y3; + bounds[0].length = bounds[1].length = jlen + 2; + + return { + x0: mmin.apply(0, bounds[0]), + y0: mmin.apply(0, bounds[1]), + x1: mmax.apply(0, bounds[0]), + y1: mmax.apply(0, bounds[1]) + }; +} + +function pathToCurve(path) { + + var pth = paths(path); + + // return cached curve, if existing + if (pth.curve) { + return pathClone(pth.curve); + } + + var curvedPath = pathToAbsolute(path), + attrs = { x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null }, + processPath = function(path, d, pathCommand) { + var nx, ny; + + if (!path) { + return ['C', d.x, d.y, d.x, d.y, d.x, d.y]; + } + + !(path[0] in { T: 1, Q: 1 }) && (d.qx = d.qy = null); + + switch (path[0]) { + case 'M': + d.X = path[1]; + d.Y = path[2]; + break; + case 'A': + path = ['C'].concat(arcToCurve.apply(0, [d.x, d.y].concat(path.slice(1)))); + break; + case 'S': + if (pathCommand == 'C' || pathCommand == 'S') { + + // In 'S' case we have to take into account, if the previous command is C/S. + nx = d.x * 2 - d.bx; + + // And reflect the previous + ny = d.y * 2 - d.by; + + // command's control point relative to the current point. + } + else { + + // or some else or nothing + nx = d.x; + ny = d.y; + } + path = ['C', nx, ny].concat(path.slice(1)); + break; + case 'T': + if (pathCommand == 'Q' || pathCommand == 'T') { + + // In 'T' case we have to take into account, if the previous command is Q/T. + d.qx = d.x * 2 - d.qx; + + // And make a reflection similar + d.qy = d.y * 2 - d.qy; + + // to case 'S'. + } + else { + + // or something else or nothing + d.qx = d.x; + d.qy = d.y; + } + path = ['C'].concat(qubicToCurve(d.x, d.y, d.qx, d.qy, path[1], path[2])); + break; + case 'Q': + d.qx = path[1]; + d.qy = path[2]; + path = ['C'].concat(qubicToCurve(d.x, d.y, path[1], path[2], path[3], path[4])); + break; + case 'L': + path = ['C'].concat(lineToCurve(d.x, d.y, path[1], path[2])); + break; + case 'H': + path = ['C'].concat(lineToCurve(d.x, d.y, path[1], d.y)); + break; + case 'V': + path = ['C'].concat(lineToCurve(d.x, d.y, d.x, path[1])); + break; + case 'Z': + path = ['C'].concat(lineToCurve(d.x, d.y, d.X, d.Y)); + break; + } + + return path; + }, + + fixArc = function(pp, i) { + + if (pp[i].length > 7) { + pp[i].shift(); + var pi = pp[i]; + + while (pi.length) { + pathCommands[i] = 'A'; // if created multiple C:s, their original seg is saved + pp.splice(i++, 0, ['C'].concat(pi.splice(0, 6))); + } + + pp.splice(i, 1); + ii = curvedPath.length; + } + }, + + pathCommands = [], // path commands of original path p + pfirst = '', // temporary holder for original path command + pathCommand = ''; // holder for previous path command of original path + + for (var i = 0, ii = curvedPath.length; i < ii; i++) { + curvedPath[i] && (pfirst = curvedPath[i][0]); // save current path command + + if (pfirst != 'C') // C is not saved yet, because it may be result of conversion + { + pathCommands[i] = pfirst; // Save current path command + i && (pathCommand = pathCommands[i - 1]); // Get previous path command pathCommand + } + curvedPath[i] = processPath(curvedPath[i], attrs, pathCommand); // Previous path command is inputted to processPath + + if (pathCommands[i] != 'A' && pfirst == 'C') pathCommands[i] = 'C'; // A is the only command + // which may produce multiple C:s + // so we have to make sure that C is also C in original path + + fixArc(curvedPath, i); // fixArc adds also the right amount of A:s to pathCommands + + var seg = curvedPath[i], + seglen = seg.length; + + attrs.x = seg[seglen - 2]; + attrs.y = seg[seglen - 1]; + attrs.bx = toFloat(seg[seglen - 4]) || attrs.x; + attrs.by = toFloat(seg[seglen - 3]) || attrs.y; + } + + // cache curve + pth.curve = pathClone(curvedPath); + + return curvedPath; +} + +var intersect = findPathIntersections; + +var intersectPaths = /*@__PURE__*/getDefaultExportFromCjs(intersect); + +/** + * Checks whether a value is an instance of Connection. + * + * @param {any} value + * + * @return {boolean} + */ +function isConnection(value) { + return isObject(value) && has$2(value, 'waypoints'); +} + +/** + * Checks whether a value is an instance of Label. + * + * @param {any} value + * + * @return {boolean} + */ +function isLabel(value) { + return isObject(value) && has$2(value, 'labelTarget'); +} + +/** + * @typedef {import('../core/Types').ElementLike} Element + * @typedef {import('../core/Types').ConnectionLike} Connection + * + * @typedef {import('../util/Types').DirectionTRBL} DirectionTRBL + * @typedef {import('../util/Types').Point} Point + * @typedef {import('../util/Types').Rect} Rect + * @typedef {import('../util/Types').RectTRBL} RectTRBL + */ + +/** + * @param {Rect} bounds + * + * @returns {Rect} + */ +function roundBounds(bounds) { + return { + x: Math.round(bounds.x), + y: Math.round(bounds.y), + width: Math.round(bounds.width), + height: Math.round(bounds.height) + }; +} + +/** + * @param {Point} point + * + * @returns {Point} + */ +function roundPoint(point) { + + return { + x: Math.round(point.x), + y: Math.round(point.y) + }; +} + + +/** + * Convert the given bounds to a { top, left, bottom, right } descriptor. + * + * @param {Point|Rect} bounds + * + * @return {RectTRBL} + */ +function asTRBL(bounds) { + return { + top: bounds.y, + right: bounds.x + (bounds.width || 0), + bottom: bounds.y + (bounds.height || 0), + left: bounds.x + }; +} + + +/** + * Convert a { top, left, bottom, right } to an objects bounds. + * + * @param {RectTRBL} trbl + * + * @return {Rect} + */ +function asBounds(trbl) { + return { + x: trbl.left, + y: trbl.top, + width: trbl.right - trbl.left, + height: trbl.bottom - trbl.top + }; +} + + +/** + * Get the mid of the given bounds or point. + * + * @param {Point|Rect} bounds + * + * @return {Point} + */ +function getBoundsMid(bounds) { + return roundPoint({ + x: bounds.x + (bounds.width || 0) / 2, + y: bounds.y + (bounds.height || 0) / 2 + }); +} + + +/** + * Get the mid of the given Connection. + * + * @param {Connection} connection + * + * @return {Point} + */ +function getConnectionMid(connection) { + var waypoints = connection.waypoints; + + // calculate total length and length of each segment + var parts = waypoints.reduce(function(parts, point, index) { + + var lastPoint = waypoints[index - 1]; + + if (lastPoint) { + var lastPart = parts[parts.length - 1]; + + var startLength = lastPart && lastPart.endLength || 0; + var length = distance(lastPoint, point); + + parts.push({ + start: lastPoint, + end: point, + startLength: startLength, + endLength: startLength + length, + length: length + }); + } + + return parts; + }, []); + + var totalLength = parts.reduce(function(length, part) { + return length + part.length; + }, 0); + + // find which segement contains middle point + var midLength = totalLength / 2; + + var i = 0; + var midSegment = parts[i]; + + while (midSegment.endLength < midLength) { + midSegment = parts[++i]; + } + + // calculate relative position on mid segment + var segmentProgress = (midLength - midSegment.startLength) / midSegment.length; + + var midPoint = { + x: midSegment.start.x + (midSegment.end.x - midSegment.start.x) * segmentProgress, + y: midSegment.start.y + (midSegment.end.y - midSegment.start.y) * segmentProgress + }; + + return midPoint; +} + + +/** + * Get the mid of the given Element. + * + * @param {Element} element + * + * @return {Point} + */ +function getMid$2(element) { + if (isConnection(element)) { + return getConnectionMid(element); + } + + return getBoundsMid(element); +} + +// orientation utils ////////////////////// + +/** + * Get orientation of the given rectangle with respect to + * the reference rectangle. + * + * A padding (positive or negative) may be passed to influence + * horizontal / vertical orientation and intersection. + * + * @param {Rect} rect + * @param {Rect} reference + * @param {Point|number} padding + * + * @return {DirectionTRBL} the orientation; one of top, top-left, left, ..., bottom, right or intersect. + */ +function getOrientation(rect, reference, padding) { + + padding = padding || 0; + + // make sure we can use an object, too + // for individual { x, y } padding + if (!isObject(padding)) { + padding = { x: padding, y: padding }; + } + + + var rectOrientation = asTRBL(rect), + referenceOrientation = asTRBL(reference); + + var top = rectOrientation.bottom + padding.y <= referenceOrientation.top, + right = rectOrientation.left - padding.x >= referenceOrientation.right, + bottom = rectOrientation.top - padding.y >= referenceOrientation.bottom, + left = rectOrientation.right + padding.x <= referenceOrientation.left; + + var vertical = top ? 'top' : (bottom ? 'bottom' : null), + horizontal = left ? 'left' : (right ? 'right' : null); + + if (horizontal && vertical) { + return vertical + '-' + horizontal; + } else { + return horizontal || vertical || 'intersect'; + } +} + + +// intersection utils ////////////////////// + +/** + * Get intersection between an element and a line path. + * + * @param {string} elementPath + * @param {string} linePath + * @param {boolean} cropStart Whether to crop start or end. + * + * @return {Point} + */ +function getElementLineIntersection(elementPath, linePath, cropStart) { + + var intersections = getIntersections(elementPath, linePath); + + // recognize intersections + // only one -> choose + // two close together -> choose first + // two or more distinct -> pull out appropriate one + // none -> ok (fallback to point itself) + if (intersections.length === 1) { + return roundPoint(intersections[0]); + } else if (intersections.length === 2 && pointDistance(intersections[0], intersections[1]) < 1) { + return roundPoint(intersections[0]); + } else if (intersections.length > 1) { + + // sort by intersections based on connection segment + + // distance from start + intersections = sortBy(intersections, function(i) { + var distance = Math.floor(i.t2 * 100) || 1; + + distance = 100 - distance; + + distance = (distance < 10 ? '0' : '') + distance; + + // create a sort string that makes sure we sort + // line segment ASC + line segment position DESC (for cropStart) + // line segment ASC + line segment position ASC (for cropEnd) + return i.segment2 + '#' + distance; + }); + + return roundPoint(intersections[cropStart ? 0 : intersections.length - 1]); + } + + return null; +} + + +function getIntersections(a, b) { + return intersectPaths(a, b); +} + +// helpers ////////////////////// + +function distance(a, b) { + return Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2)); +} + +/** + * @typedef {import('../util/Types').Point} Point + * @typedef {import('../util/Types').Rect} Rect + */ + +/** + * @param {Rect} bounds + * @return {Point} + */ +function center(bounds) { + return { + x: bounds.x + (bounds.width / 2), + y: bounds.y + (bounds.height / 2) + }; +} + + +/** + * @param {Point} a + * @param {Point} b + * @return {Point} + */ +function delta(a, b) { + return { + x: a.x - b.x, + y: a.y - b.y + }; +} + +/** + * Get the logarithm of x with base 10. + * + * @param {number} x + */ +function log10(x) { + return Math.log(x) / Math.log(10); +} + +/** + * @typedef { import('../model/Types').Element } Element + * @typedef { import('../model/Types').ModdleElement } ModdleElement + */ + +/** + * Is an element of the given BPMN type? + * + * @param {Element|ModdleElement} element + * @param {string} type + * + * @return {boolean} + */ +function is$2(element, type) { + var bo = getBusinessObject(element); + + return bo && (typeof bo.$instanceOf === 'function') && bo.$instanceOf(type); +} + + +/** + * Return true if element has any of the given types. + * + * @param {Element|ModdleElement} element + * @param {string[]} types + * + * @return {boolean} + */ +function isAny(element, types) { + return some(types, function(t) { + return is$2(element, t); + }); +} + +/** + * Return the business object for a given element. + * + * @param {Element|ModdleElement} element + * + * @return {ModdleElement} + */ +function getBusinessObject(element) { + return (element && element.businessObject) || element; +} + +/** + * Return the di object for a given element. + * + * @param {Element} element + * + * @return {ModdleElement} + */ +function getDi(element) { + return element && element.di; +} + +/** + * @typedef {import('diagram-js/lib/util/Types').Point} Point + * @typedef {import('diagram-js/lib/util/Types').Rect} Rect + * + * @typedef {import('../model/Types').Element} Element + * @typedef {import('../model/Types').ModdleElement} ModdleElement + */ + +var DEFAULT_LABEL_SIZE$1 = { + width: 90, + height: 20 +}; + +var FLOW_LABEL_INDENT = 15; + + +/** + * Return true if the given semantic has an external label. + * + * @param {Element} semantic + * + * @return {boolean} + */ +function isLabelExternal(semantic) { + return is$2(semantic, 'bpmn:Event') || + is$2(semantic, 'bpmn:Gateway') || + is$2(semantic, 'bpmn:DataStoreReference') || + is$2(semantic, 'bpmn:DataObjectReference') || + is$2(semantic, 'bpmn:DataInput') || + is$2(semantic, 'bpmn:DataOutput') || + is$2(semantic, 'bpmn:SequenceFlow') || + is$2(semantic, 'bpmn:MessageFlow') || + is$2(semantic, 'bpmn:Group'); +} + +/** + * Return true if the given element has an external label. + * + * @param {Element} element + * + * @return {boolean} + */ +function hasExternalLabel(element) { + return isLabel(element.label); +} + +/** + * Get the position of a sequence flow label. + * + * @param {Point[]} waypoints + * + * @return {Point} + */ +function getFlowLabelPosition(waypoints) { + + // get the waypoints mid + var mid = waypoints.length / 2 - 1; + + var first = waypoints[Math.floor(mid)]; + var second = waypoints[Math.ceil(mid + 0.01)]; + + // get position + var position = getWaypointsMid(waypoints); + + // calculate angle + var angle = Math.atan((second.y - first.y) / (second.x - first.x)); + + var x = position.x, + y = position.y; + + if (Math.abs(angle) < Math.PI / 2) { + y -= FLOW_LABEL_INDENT; + } else { + x += FLOW_LABEL_INDENT; + } + + return { x: x, y: y }; +} + + +/** + * Get the middle of a number of waypoints. + * + * @param {Point[]} waypoints + * + * @return {Point} + */ +function getWaypointsMid(waypoints) { + + var mid = waypoints.length / 2 - 1; + + var first = waypoints[Math.floor(mid)]; + var second = waypoints[Math.ceil(mid + 0.01)]; + + return { + x: first.x + (second.x - first.x) / 2, + y: first.y + (second.y - first.y) / 2 + }; +} + +/** + * Get the middle of the external label of an element. + * + * @param {Element} element + * + * @return {Point} + */ +function getExternalLabelMid(element) { + + if (element.waypoints) { + return getFlowLabelPosition(element.waypoints); + } else if (is$2(element, 'bpmn:Group')) { + return { + x: element.x + element.width / 2, + y: element.y + DEFAULT_LABEL_SIZE$1.height / 2 + }; + } else { + return { + x: element.x + element.width / 2, + y: element.y + element.height + DEFAULT_LABEL_SIZE$1.height / 2 + }; + } +} + + +/** + * Return the bounds of an elements label, parsed from the elements DI or + * generated from its bounds. + * + * @param {ModdleElement} di + * @param {Element} element + * + * @return {Rect} + */ +function getExternalLabelBounds(di, element) { + + var mid, + size, + bounds, + label = di.label; + + if (label && label.bounds) { + bounds = label.bounds; + + size = { + width: Math.max(DEFAULT_LABEL_SIZE$1.width, bounds.width), + height: bounds.height + }; + + mid = { + x: bounds.x + bounds.width / 2, + y: bounds.y + bounds.height / 2 + }; + } else { + + mid = getExternalLabelMid(element); + + size = DEFAULT_LABEL_SIZE$1; + } + + return assign$3({ + x: mid.x - size.width / 2, + y: mid.y - size.height / 2 + }, size); +} + +/** + * @param {ModdleElement} semantic + * + * @returns {string} + */ +function getLabelAttr(semantic) { + if ( + is$2(semantic, 'bpmn:FlowElement') || + is$2(semantic, 'bpmn:Participant') || + is$2(semantic, 'bpmn:Lane') || + is$2(semantic, 'bpmn:SequenceFlow') || + is$2(semantic, 'bpmn:MessageFlow') || + is$2(semantic, 'bpmn:DataInput') || + is$2(semantic, 'bpmn:DataOutput') + ) { + return 'name'; + } + + if (is$2(semantic, 'bpmn:TextAnnotation')) { + return 'text'; + } + + if (is$2(semantic, 'bpmn:Group')) { + return 'categoryValueRef'; + } +} + +/** + * @param {ModdleElement} semantic + * + * @returns {string} + */ +function getCategoryValue(semantic) { + var categoryValueRef = semantic['categoryValueRef']; + + if (!categoryValueRef) { + return ''; + } + + + return categoryValueRef.value || ''; +} + +/** + * @param {Element} element + * + * @return {string} + */ +function getLabel(element) { + var semantic = element.businessObject, + attr = getLabelAttr(semantic); + + if (attr) { + + if (attr === 'categoryValueRef') { + + return getCategoryValue(semantic); + } + + return semantic[attr] || ''; + } +} + + +/** + * @param {Element} element + * @param {string} text + * + * @return {Element} + */ +function setLabel(element, text) { + var semantic = element.businessObject, + attr = getLabelAttr(semantic); + + if (attr) { + + if (attr === 'categoryValueRef') { + semantic['categoryValueRef'].value = text; + } else { + semantic[attr] = text; + } + + } + + return element; +} + +/** + * @typedef {import('../core/Types').ElementLike} ElementLike + * @typedef {import('../core/EventBus').default} EventBus + * @typedef {import('./CommandStack').CommandContext} CommandContext + * + * @typedef {string|string[]} Events + * @typedef { (context: CommandContext) => ElementLike[] | void } HandlerFunction + * @typedef { (context: CommandContext) => void } ComposeHandlerFunction + */ + +var DEFAULT_PRIORITY$2 = 1000; + +/** + * A utility that can be used to plug into the command execution for + * extension and/or validation. + * + * @class + * @constructor + * + * @example + * + * ```javascript + * import CommandInterceptor from 'diagram-js/lib/command/CommandInterceptor'; + * + * class CommandLogger extends CommandInterceptor { + * constructor(eventBus) { + * super(eventBus); + * + * this.preExecute('shape.create', (event) => { + * console.log('commandStack.shape-create.preExecute', event); + * }); + * } + * ``` + * + * @param {EventBus} eventBus + */ +function CommandInterceptor(eventBus) { + + /** + * @type {EventBus} + */ + this._eventBus = eventBus; +} + +CommandInterceptor.$inject = [ 'eventBus' ]; + +function unwrapEvent(fn, that) { + return function(event) { + return fn.call(that || null, event.context, event.command, event); + }; +} + + +/** + * Intercept a command during one of the phases. + * + * @param {Events} [events] command(s) to intercept + * @param {string} [hook] phase to intercept + * @param {number} [priority] + * @param {ComposeHandlerFunction|HandlerFunction} handlerFn + * @param {boolean} [unwrap] whether the event should be unwrapped + * @param {any} [that] + */ +CommandInterceptor.prototype.on = function(events, hook, priority, handlerFn, unwrap, that) { + + if (isFunction(hook) || isNumber(hook)) { + that = unwrap; + unwrap = handlerFn; + handlerFn = priority; + priority = hook; + hook = null; + } + + if (isFunction(priority)) { + that = unwrap; + unwrap = handlerFn; + handlerFn = priority; + priority = DEFAULT_PRIORITY$2; + } + + if (isObject(unwrap)) { + that = unwrap; + unwrap = false; + } + + if (!isFunction(handlerFn)) { + throw new Error('handlerFn must be a function'); + } + + if (!isArray$4(events)) { + events = [ events ]; + } + + var eventBus = this._eventBus; + + forEach$2(events, function(event) { + + // concat commandStack(.event)?(.hook)? + var fullEvent = [ 'commandStack', event, hook ].filter(function(e) { return e; }).join('.'); + + eventBus.on(fullEvent, priority, unwrap ? unwrapEvent(handlerFn, that) : handlerFn, that); + }); +}; + +/** + * Add a phase of command interceptor. + * + * @param {Events} [events] command(s) to intercept + * @param {number} [priority] + * @param {ComposeHandlerFunction|HandlerFunction} handlerFn + * @param {boolean} [unwrap] whether the event should be unwrapped + * @param {any} [that] + */ +CommandInterceptor.prototype.canExecute = createHook('canExecute'); + +/** + * Add a phase of command interceptor. + * + * @param {Events} [events] command(s) to intercept + * @param {number} [priority] + * @param {ComposeHandlerFunction|HandlerFunction} handlerFn + * @param {boolean} [unwrap] whether the event should be unwrapped + * @param {any} [that] + */ +CommandInterceptor.prototype.preExecute = createHook('preExecute'); + +/** + * Add a phase of command interceptor. + * + * @param {Events} [events] command(s) to intercept + * @param {number} [priority] + * @param {ComposeHandlerFunction|HandlerFunction} handlerFn + * @param {boolean} [unwrap] whether the event should be unwrapped + * @param {any} [that] + */ +CommandInterceptor.prototype.preExecuted = createHook('preExecuted'); + +/** + * Add a phase of command interceptor. + * + * @param {Events} [events] command(s) to intercept + * @param {number} [priority] + * @param {ComposeHandlerFunction|HandlerFunction} handlerFn + * @param {boolean} [unwrap] whether the event should be unwrapped + * @param {any} [that] + */ +CommandInterceptor.prototype.execute = createHook('execute'); + +/** + * Add a phase of command interceptor. + * + * @param {Events} [events] command(s) to intercept + * @param {number} [priority] + * @param {ComposeHandlerFunction|HandlerFunction} handlerFn + * @param {boolean} [unwrap] whether the event should be unwrapped + * @param {any} [that] + */ +CommandInterceptor.prototype.executed = createHook('executed'); + +/** + * Add a phase of command interceptor. + * + * @param {Events} [events] command(s) to intercept + * @param {number} [priority] + * @param {ComposeHandlerFunction|HandlerFunction} handlerFn + * @param {boolean} [unwrap] whether the event should be unwrapped + * @param {any} [that] + */ +CommandInterceptor.prototype.postExecute = createHook('postExecute'); + +/** + * Add a phase of command interceptor. + * + * @param {Events} [events] command(s) to intercept + * @param {number} [priority] + * @param {ComposeHandlerFunction|HandlerFunction} handlerFn + * @param {boolean} [unwrap] whether the event should be unwrapped + * @param {any} [that] + */ +CommandInterceptor.prototype.postExecuted = createHook('postExecuted'); + +/** + * Add a phase of command interceptor. + * + * @param {Events} [events] command(s) to intercept + * @param {number} [priority] + * @param {ComposeHandlerFunction|HandlerFunction} handlerFn + * @param {boolean} [unwrap] whether the event should be unwrapped + * @param {any} [that] + */ +CommandInterceptor.prototype.revert = createHook('revert'); + +/** + * Add a phase of command interceptor. + * + * @param {Events} [events] command(s) to intercept + * @param {number} [priority] + * @param {ComposeHandlerFunction|HandlerFunction} handlerFn + * @param {boolean} [unwrap] whether the event should be unwrapped + * @param {any} [that] + */ +CommandInterceptor.prototype.reverted = createHook('reverted'); + +/* + * Add prototype methods for each phase of command execution (e.g. execute, + * revert). + * + * @param {string} hook + * + * @return { ( + * events?: Events, + * priority?: number, + * handlerFn: ComposeHandlerFunction|HandlerFunction, + * unwrap?: boolean + * ) => any } + */ +function createHook(hook) { + + /** + * @this {CommandInterceptor} + * + * @param {Events} [events] + * @param {number} [priority] + * @param {ComposeHandlerFunction|HandlerFunction} handlerFn + * @param {boolean} [unwrap] + * @param {any} [that] + */ + const hookFn = function(events, priority, handlerFn, unwrap, that) { + + if (isFunction(events) || isNumber(events)) { + that = unwrap; + unwrap = handlerFn; + handlerFn = priority; + priority = events; + events = null; + } + + this.on(events, hook, priority, handlerFn, unwrap, that); + }; + + return hookFn; +} + +/** + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * @typedef {import('../Modeling').default} Modeling + * + * @typedef {import('../../../model/Types').Element} Element + * @typedef {import('../../../model/Types').Shape} Shape + * + * @typedef {import('diagram-js/lib/util/Types').DirectionTRBL} DirectionTRBL + */ + +var ALIGNMENTS = [ + 'top', + 'bottom', + 'left', + 'right' +]; + +var ELEMENT_LABEL_DISTANCE$1 = 10; + +/** + * A component that makes sure that external labels are added + * together with respective elements and properly updated (DI wise) + * during move. + * + * @param {EventBus} eventBus + * @param {Modeling} modeling + */ +function AdaptiveLabelPositioningBehavior(eventBus, modeling) { + + CommandInterceptor.call(this, eventBus); + + this.postExecuted([ + 'connection.create', + 'connection.layout', + 'connection.updateWaypoints' + ], function(event) { + var context = event.context, + connection = context.connection, + source = connection.source, + target = connection.target, + hints = context.hints || {}; + + if (hints.createElementsBehavior !== false) { + checkLabelAdjustment(source); + checkLabelAdjustment(target); + } + }); + + + this.postExecuted([ + 'label.create' + ], function(event) { + var context = event.context, + shape = context.shape, + hints = context.hints || {}; + + if (hints.createElementsBehavior !== false) { + checkLabelAdjustment(shape.labelTarget); + } + }); + + + this.postExecuted([ + 'elements.create' + ], function(event) { + var context = event.context, + elements = context.elements, + hints = context.hints || {}; + + if (hints.createElementsBehavior !== false) { + elements.forEach(function(element) { + checkLabelAdjustment(element); + }); + } + }); + + function checkLabelAdjustment(element) { + + // skip non-existing labels + if (!hasExternalLabel(element)) { + return; + } + + var optimalPosition = getOptimalPosition(element); + + // no optimal position found + if (!optimalPosition) { + return; + } + + adjustLabelPosition(element, optimalPosition); + } + + function adjustLabelPosition(element, orientation) { + + var elementMid = getMid$2(element), + label = element.label, + labelMid = getMid$2(label); + + // ignore labels that are being created + if (!label.parent) { + return; + } + + var elementTrbl = asTRBL(element); + + var newLabelMid; + + switch (orientation) { + case 'top': + newLabelMid = { + x: elementMid.x, + y: elementTrbl.top - ELEMENT_LABEL_DISTANCE$1 - label.height / 2 + }; + + break; + + case 'left': + + newLabelMid = { + x: elementTrbl.left - ELEMENT_LABEL_DISTANCE$1 - label.width / 2, + y: elementMid.y + }; + + break; + + case 'bottom': + + newLabelMid = { + x: elementMid.x, + y: elementTrbl.bottom + ELEMENT_LABEL_DISTANCE$1 + label.height / 2 + }; + + break; + + case 'right': + + newLabelMid = { + x: elementTrbl.right + ELEMENT_LABEL_DISTANCE$1 + label.width / 2, + y: elementMid.y + }; + + break; + } + + var delta$1 = delta(newLabelMid, labelMid); + + modeling.moveShape(label, delta$1); + } + +} + +e(AdaptiveLabelPositioningBehavior, CommandInterceptor); + +AdaptiveLabelPositioningBehavior.$inject = [ + 'eventBus', + 'modeling' +]; + + +// helpers ////////////////////// + +/** + * Return alignments which are taken by a boundary's host element + * + * @param {Shape} element + * + * @return {DirectionTRBL[]} + */ +function getTakenHostAlignments(element) { + + var hostElement = element.host, + elementMid = getMid$2(element), + hostOrientation = getOrientation(elementMid, hostElement); + + var freeAlignments; + + // check whether there is a multi-orientation, e.g. 'top-left' + if (hostOrientation.indexOf('-') >= 0) { + freeAlignments = hostOrientation.split('-'); + } else { + freeAlignments = [ hostOrientation ]; + } + + var takenAlignments = ALIGNMENTS.filter(function(alignment) { + + return freeAlignments.indexOf(alignment) === -1; + }); + + return takenAlignments; + +} + +/** + * Return alignments which are taken by related connections + * + * @param {Element} element + * + * @return {DirectionTRBL[]} + */ +function getTakenConnectionAlignments(element) { + + var elementMid = getMid$2(element); + + var takenAlignments = [].concat( + element.incoming.map(function(c) { + return c.waypoints[c.waypoints.length - 2 ]; + }), + element.outgoing.map(function(c) { + return c.waypoints[1]; + }) + ).map(function(point) { + return getApproximateOrientation(elementMid, point); + }); + + return takenAlignments; +} + +/** + * Return the optimal label position around an element + * or `undefined`, if none was found. + * + * @param {Element} element + * + * @return {DirectionTRBL|undefined} + */ +function getOptimalPosition(element) { + + var labelMid = getMid$2(element.label); + + var elementMid = getMid$2(element); + + var labelOrientation = getApproximateOrientation(elementMid, labelMid); + + if (!isAligned(labelOrientation)) { + return; + } + + var takenAlignments = getTakenConnectionAlignments(element); + + if (element.host) { + var takenHostAlignments = getTakenHostAlignments(element); + + takenAlignments = takenAlignments.concat(takenHostAlignments); + } + + var freeAlignments = ALIGNMENTS.filter(function(alignment) { + + return takenAlignments.indexOf(alignment) === -1; + }); + + // NOTHING TO DO; label already aligned a.O.K. + if (freeAlignments.indexOf(labelOrientation) !== -1) { + return; + } + + return freeAlignments[0]; +} + +function getApproximateOrientation(p0, p1) { + return getOrientation(p1, p0, 5); +} + +function isAligned(orientation) { + return ALIGNMENTS.indexOf(orientation) !== -1; +} + +/** + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + */ + +function AppendBehavior(eventBus) { + + CommandInterceptor.call(this, eventBus); + + // assign correct shape position unless already set + + this.preExecute('shape.append', function(context) { + + var source = context.source, + shape = context.shape; + + if (!context.position) { + + if (is$2(shape, 'bpmn:TextAnnotation')) { + context.position = { + x: source.x + source.width / 2 + 75, + y: source.y - 50 - shape.height / 2 + }; + } else { + context.position = { + x: source.x + source.width + 80 + shape.width / 2, + y: source.y + source.height / 2 + }; + } + } + }, true); +} + +e(AppendBehavior, CommandInterceptor); + +AppendBehavior.$inject = [ + 'eventBus' +]; + +/** + * @typedef {import('didi').Injector} Injector + * @typedef {import('../Modeling').default} Modeling + */ + +/** + * @param {Injector} injector + * @param {Modeling} modeling + */ +function AssociationBehavior(injector, modeling) { + injector.invoke(CommandInterceptor, this); + + this.postExecute('shape.move', function(context) { + var newParent = context.newParent, + shape = context.shape; + + var associations = filter(shape.incoming.concat(shape.outgoing), function(connection) { + return is$2(connection, 'bpmn:Association'); + }); + + forEach$2(associations, function(association) { + modeling.moveConnection(association, { x: 0, y: 0 }, newParent); + }); + }, true); +} + +e(AssociationBehavior, CommandInterceptor); + +AssociationBehavior.$inject = [ + 'injector', + 'modeling' +]; + +/** + * @typedef {import('../../../model/Types').Element} Element + */ + +/** + * Return the parent of the element with any of the given types. + * + * @param {Element} element + * @param {string|string[]} anyType + * + * @return {Element|null} + */ +function getParent$2(element, anyType) { + + if (isString(anyType)) { + anyType = [ anyType ]; + } + + while ((element = element.parent)) { + if (isAny(element, anyType)) { + return element; + } + } + + return null; +} + +/** + * @typedef {import('../../replace/BpmnReplace').default} BpmnReplace + * @typedef {import('didi').Injector} Injector + */ + +var LOW_PRIORITY$k = 500; + + +/** + * Replace intermediate event with boundary event when creating or moving results in attached event. + * + * @param {BpmnReplace} bpmnReplace + * @param {Injector} injector + */ +function AttachEventBehavior(bpmnReplace, injector) { + injector.invoke(CommandInterceptor, this); + + this._bpmnReplace = bpmnReplace; + + var self = this; + + this.postExecuted('elements.create', LOW_PRIORITY$k, function(context) { + var elements = context.elements; + + elements = elements.filter(function(shape) { + var host = shape.host; + + return shouldReplace$1(shape, host); + }); + + if (elements.length !== 1) { + return; + } + + elements.map(function(element) { + return elements.indexOf(element); + }).forEach(function(index) { + var host = elements[ index ]; + + context.elements[ index ] = self._replaceShape(elements[ index ], host); + }); + }, true); + + + this.preExecute('elements.move', LOW_PRIORITY$k, function(context) { + var shapes = context.shapes, + host = context.newHost; + + if (shapes.length !== 1) { + return; + } + + var shape = shapes[0]; + + if (shouldReplace$1(shape, host)) { + context.shapes = [ self._replaceShape(shape, host) ]; + } + }, true); +} + +AttachEventBehavior.$inject = [ + 'bpmnReplace', + 'injector' +]; + +e(AttachEventBehavior, CommandInterceptor); + +AttachEventBehavior.prototype._replaceShape = function(shape, host) { + var eventDefinition = getEventDefinition$2(shape); + + var boundaryEvent = { + type: 'bpmn:BoundaryEvent', + host: host + }; + + if (eventDefinition) { + boundaryEvent.eventDefinitionType = eventDefinition.$type; + } + + return this._bpmnReplace.replaceElement(shape, boundaryEvent, { layoutConnection: false }); +}; + + +// helpers ////////// + +function getEventDefinition$2(element) { + var businessObject = getBusinessObject(element), + eventDefinitions = businessObject.eventDefinitions; + + return eventDefinitions && eventDefinitions[0]; +} + +function shouldReplace$1(shape, host) { + return !isLabel(shape) && + isAny(shape, [ 'bpmn:IntermediateThrowEvent', 'bpmn:IntermediateCatchEvent' ]) && !!host; +} + +/** + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * @typedef {import('../Modeling').default} Modeling + */ + +/** + * BPMN specific boundary event behavior. + * + * @param {EventBus} eventBus + * @param {Modeling} modeling + */ +function BoundaryEventBehavior(eventBus, modeling) { + + CommandInterceptor.call(this, eventBus); + + function getBoundaryEvents(element) { + return filter(element.attachers, function(attacher) { + return is$2(attacher, 'bpmn:BoundaryEvent'); + }); + } + + // remove after connecting to event-based gateway + this.postExecute('connection.create', function(event) { + var source = event.context.source, + target = event.context.target, + boundaryEvents = getBoundaryEvents(target); + + if ( + is$2(source, 'bpmn:EventBasedGateway') && + is$2(target, 'bpmn:ReceiveTask') && + boundaryEvents.length > 0 + ) { + modeling.removeElements(boundaryEvents); + } + + }); + + // remove after replacing connected gateway with event-based gateway + this.postExecute('connection.reconnect', function(event) { + var oldSource = event.context.oldSource, + newSource = event.context.newSource; + + if (is$2(oldSource, 'bpmn:Gateway') && + is$2(newSource, 'bpmn:EventBasedGateway')) { + forEach$2(newSource.outgoing, function(connection) { + var target = connection.target, + attachedboundaryEvents = getBoundaryEvents(target); + + if (is$2(target, 'bpmn:ReceiveTask') && + attachedboundaryEvents.length > 0) { + modeling.removeElements(attachedboundaryEvents); + } + }); + } + }); + +} + +BoundaryEventBehavior.$inject = [ + 'eventBus', + 'modeling' +]; + +e(BoundaryEventBehavior, CommandInterceptor); + +/** + * @typedef {import('didi').Injector} Injector + */ + +/** + * @param {Injector} injector + */ +function CreateBehavior(injector) { + injector.invoke(CommandInterceptor, this); + + this.preExecute('shape.create', 1500, function(event) { + var context = event.context, + parent = context.parent, + shape = context.shape; + + if (is$2(parent, 'bpmn:Lane') && !is$2(shape, 'bpmn:Lane')) { + context.parent = getParent$2(parent, 'bpmn:Participant'); + } + }); + +} + + +CreateBehavior.$inject = [ 'injector' ]; + +e(CreateBehavior, CommandInterceptor); + +/** + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * @typedef {import('../BpmnFactory').default} BpmnFactory + */ + +/** + * BPMN specific create data object behavior. + * + * @param {EventBus} eventBus + * @param {BpmnFactory} bpmnFactory + */ +function CreateDataObjectBehavior(eventBus, bpmnFactory) { + + CommandInterceptor.call(this, eventBus); + + this.preExecute('shape.create', function(event) { + + var context = event.context, + shape = context.shape; + + if (is$2(shape, 'bpmn:DataObjectReference') && shape.type !== 'label') { + + // create a DataObject every time a DataObjectReference is created + var dataObject = bpmnFactory.create('bpmn:DataObject'); + + // set the reference to the DataObject + shape.businessObject.dataObjectRef = dataObject; + } + }); + +} + +CreateDataObjectBehavior.$inject = [ + 'eventBus', + 'bpmnFactory' +]; + +e(CreateDataObjectBehavior, CommandInterceptor); + +/** + * @typedef {import('../model/Types').Connection} Connection + * @typedef {import('../model/Types').Element} Element + * @typedef {import('../model/Types').Shape} Shape + * + * @typedef {import('../../type/Types').Rect} Rect + * + * @typedef { { + * allShapes: Record, + * allConnections: Record, + * topLevel: Record, + * enclosedConnections: Record, + * enclosedElements: Record + * } } Closure + */ + +/** + * Get parent elements. + * + * @param {Element[]} elements + * + * @return {Element[]} + */ +function getParents$1(elements) { + + // find elements that are not children of any other elements + return filter(elements, function(element) { + return !find(elements, function(e) { + return e !== element && getParent$1(element, e); + }); + }); +} + + +function getParent$1(element, parent) { + if (!parent) { + return; + } + + if (element === parent) { + return parent; + } + + if (!element.parent) { + return; + } + + return getParent$1(element.parent, parent); +} + + +/** + * Adds an element to a collection and returns true if the + * element was added. + * + * @param {Object[]} elements + * @param {Object} element + * @param {boolean} [unique] + */ +function add$1(elements, element, unique) { + var canAdd = !unique || elements.indexOf(element) === -1; + + if (canAdd) { + elements.push(element); + } + + return canAdd; +} + + +/** + * Iterate over each element in a collection, calling the iterator function `fn` + * with (element, index, recursionDepth). + * + * Recurse into all elements that are returned by `fn`. + * + * @param {Element|Element[]} elements + * @param {(element: Element, index: number, depth: number) => Element[] | boolean | undefined} fn + * @param {number} [depth] maximum recursion depth + */ +function eachElement(elements, fn, depth) { + + depth = depth || 0; + + if (!isArray$4(elements)) { + elements = [ elements ]; + } + + forEach$2(elements, function(s, i) { + var filter = fn(s, i, depth); + + if (isArray$4(filter) && filter.length) { + eachElement(filter, fn, depth + 1); + } + }); +} + + +/** + * Collects self + child elements up to a given depth from a list of elements. + * + * @param {Element|Element[]} elements the elements to select the children from + * @param {boolean} unique whether to return a unique result set (no duplicates) + * @param {number} maxDepth the depth to search through or -1 for infinite + * + * @return {Element[]} found elements + */ +function selfAndChildren(elements, unique, maxDepth) { + var result = [], + processedChildren = []; + + eachElement(elements, function(element, i, depth) { + add$1(result, element, unique); + + var children = element.children; + + // max traversal depth not reached yet + if (maxDepth === -1 || depth < maxDepth) { + + // children exist && children not yet processed + if (children && add$1(processedChildren, children, unique)) { + return children; + } + } + }); + + return result; +} + + +/** + * Return self + ALL children for a number of elements + * + * @param {Element[]} elements to query + * @param {boolean} [allowDuplicates] to allow duplicates in the result set + * + * @return {Element[]} the collected elements + */ +function selfAndAllChildren(elements, allowDuplicates) { + return selfAndChildren(elements, !allowDuplicates, -1); +} + + +/** + * Gets the the closure for all selected elements, + * their enclosed children and connections. + * + * @param {Element[]} elements + * @param {boolean} [isTopLevel=true] + * @param {Closure} [closure] + * + * @return {Closure} newClosure + */ +function getClosure(elements, isTopLevel, closure) { + + if (isUndefined$3(isTopLevel)) { + isTopLevel = true; + } + + if (isObject(isTopLevel)) { + closure = isTopLevel; + isTopLevel = true; + } + + + closure = closure || {}; + + var allShapes = copyObject(closure.allShapes), + allConnections = copyObject(closure.allConnections), + enclosedElements = copyObject(closure.enclosedElements), + enclosedConnections = copyObject(closure.enclosedConnections); + + var topLevel = copyObject( + closure.topLevel, + isTopLevel && groupBy(elements, function(e) { return e.id; }) + ); + + + function handleConnection(c) { + if (topLevel[c.source.id] && topLevel[c.target.id]) { + topLevel[c.id] = [ c ]; + } + + // not enclosed as a child, but maybe logically + // (connecting two moved elements?) + if (allShapes[c.source.id] && allShapes[c.target.id]) { + enclosedConnections[c.id] = enclosedElements[c.id] = c; + } + + allConnections[c.id] = c; + } + + function handleElement(element) { + + enclosedElements[element.id] = element; + + if (element.waypoints) { + + // remember connection + enclosedConnections[element.id] = allConnections[element.id] = element; + } else { + + // remember shape + allShapes[element.id] = element; + + // remember all connections + forEach$2(element.incoming, handleConnection); + + forEach$2(element.outgoing, handleConnection); + + // recurse into children + return element.children; + } + } + + eachElement(elements, handleElement); + + return { + allShapes: allShapes, + allConnections: allConnections, + topLevel: topLevel, + enclosedConnections: enclosedConnections, + enclosedElements: enclosedElements + }; +} + +/** + * Returns the surrounding bbox for all elements in + * the array or the element primitive. + * + * @param {Element|Element[]} elements + * @param {boolean} [stopRecursion=false] + * + * @return {Rect} + */ +function getBBox(elements, stopRecursion) { + + stopRecursion = !!stopRecursion; + if (!isArray$4(elements)) { + elements = [ elements ]; + } + + var minX, + minY, + maxX, + maxY; + + forEach$2(elements, function(element) { + + // If element is a connection the bbox must be computed first + var bbox = element; + if (element.waypoints && !stopRecursion) { + bbox = getBBox(element.waypoints, true); + } + + var x = bbox.x, + y = bbox.y, + height = bbox.height || 0, + width = bbox.width || 0; + + if (x < minX || minX === undefined) { + minX = x; + } + if (y < minY || minY === undefined) { + minY = y; + } + + if ((x + width) > maxX || maxX === undefined) { + maxX = x + width; + } + if ((y + height) > maxY || maxY === undefined) { + maxY = y + height; + } + }); + + return { + x: minX, + y: minY, + height: maxY - minY, + width: maxX - minX + }; +} + +/** + * Get the element's type + * + * @param {Element} element + * + * @return {'connection' | 'shape' | 'root'} + */ +function getType(element) { + + if ('waypoints' in element) { + return 'connection'; + } + + if ('x' in element) { + return 'shape'; + } + + return 'root'; +} + +/** + * @param {Element} element + * + * @return {boolean} + */ +function isFrameElement$1(element) { + return !!(element && element.isFrame); +} + +// helpers /////////////////////////////// + +function copyObject(src1, src2) { + return assign$3({}, src1 || {}, src2 || {}); +} + +/** + * @typedef {import('diagram-js/lib/core/Canvas').default} Canvas + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * @typedef {import('../Modeling').default} Modeling + */ + +var HORIZONTAL_PARTICIPANT_PADDING = 20, + VERTICAL_PARTICIPANT_PADDING = 20; + +var PARTICIPANT_BORDER_WIDTH = 30; + +var HIGH_PRIORITY$e = 2000; + + +/** + * BPMN-specific behavior for creating participants. + * + * @param {Canvas} canvas + * @param {EventBus} eventBus + * @param {Modeling} modeling + */ +function CreateParticipantBehavior(canvas, eventBus, modeling) { + CommandInterceptor.call(this, eventBus); + + // fit participant + eventBus.on([ + 'create.start', + 'shape.move.start' + ], HIGH_PRIORITY$e, function(event) { + var context = event.context, + shape = context.shape, + rootElement = canvas.getRootElement(); + + if (!is$2(shape, 'bpmn:Participant') || + !is$2(rootElement, 'bpmn:Process') || + !rootElement.children.length) { + return; + } + + // ignore connections, groups and labels + var children = rootElement.children.filter(function(element) { + return !is$2(element, 'bpmn:Group') && + !isLabel(element) && + !isConnection(element); + }); + + // ensure for available children to calculate bounds + if (!children.length) { + return; + } + + var childrenBBox = getBBox(children); + + var participantBounds = getParticipantBounds(shape, childrenBBox); + + // assign width and height + assign$3(shape, participantBounds); + + // assign create constraints + context.createConstraints = getParticipantCreateConstraints(shape, childrenBBox); + }); + + // force hovering process when creating first participant + eventBus.on('create.start', HIGH_PRIORITY$e, function(event) { + var context = event.context, + shape = context.shape, + rootElement = canvas.getRootElement(), + rootElementGfx = canvas.getGraphics(rootElement); + + function ensureHoveringProcess(event) { + event.element = rootElement; + event.gfx = rootElementGfx; + } + + if (is$2(shape, 'bpmn:Participant') && is$2(rootElement, 'bpmn:Process')) { + eventBus.on('element.hover', HIGH_PRIORITY$e, ensureHoveringProcess); + + eventBus.once('create.cleanup', function() { + eventBus.off('element.hover', ensureHoveringProcess); + }); + } + }); + + // turn process into collaboration when creating first participant + function getOrCreateCollaboration() { + var rootElement = canvas.getRootElement(); + + if (is$2(rootElement, 'bpmn:Collaboration')) { + return rootElement; + } + + return modeling.makeCollaboration(); + } + + // when creating mutliple elements through `elements.create` parent must be set to collaboration + // and passed to `shape.create` as hint + this.preExecute('elements.create', HIGH_PRIORITY$e, function(context) { + var elements = context.elements, + parent = context.parent, + participant = findParticipant(elements), + hints; + + if (participant && is$2(parent, 'bpmn:Process')) { + context.parent = getOrCreateCollaboration(); + + hints = context.hints = context.hints || {}; + + hints.participant = participant; + hints.process = parent; + hints.processRef = getBusinessObject(participant).get('processRef'); + } + }, true); + + // when creating single shape through `shape.create` parent must be set to collaboration + // unless it was already set through `elements.create` + this.preExecute('shape.create', function(context) { + var parent = context.parent, + shape = context.shape; + + if (is$2(shape, 'bpmn:Participant') && is$2(parent, 'bpmn:Process')) { + context.parent = getOrCreateCollaboration(); + + context.process = parent; + context.processRef = getBusinessObject(shape).get('processRef'); + } + }, true); + + // #execute necessary because #preExecute not called on CommandStack#redo + this.execute('shape.create', function(context) { + var hints = context.hints || {}, + process = context.process || hints.process, + shape = context.shape, + participant = hints.participant; + + // both shape.create and elements.create must be handled + if (process && (!participant || shape === participant)) { + + // monkey-patch process ref + getBusinessObject(shape).set('processRef', getBusinessObject(process)); + } + }, true); + + this.revert('shape.create', function(context) { + var hints = context.hints || {}, + process = context.process || hints.process, + processRef = context.processRef || hints.processRef, + shape = context.shape, + participant = hints.participant; + + // both shape.create and elements.create must be handled + if (process && (!participant || shape === participant)) { + + // monkey-patch process ref + getBusinessObject(shape).set('processRef', processRef); + } + }, true); + + this.postExecute('shape.create', function(context) { + var hints = context.hints || {}, + process = context.process || context.hints.process, + shape = context.shape, + participant = hints.participant; + + if (process) { + var children = process.children.slice(); + + // both shape.create and elements.create must be handled + if (!participant) { + modeling.moveElements(children, { x: 0, y: 0 }, shape); + } else if (shape === participant) { + modeling.moveElements(children, { x: 0, y: 0 }, participant); + } + } + }, true); +} + +CreateParticipantBehavior.$inject = [ + 'canvas', + 'eventBus', + 'modeling' +]; + +e(CreateParticipantBehavior, CommandInterceptor); + +// helpers ////////// + +function getParticipantBounds(shape, childrenBBox) { + childrenBBox = { + width: childrenBBox.width + HORIZONTAL_PARTICIPANT_PADDING * 2 + PARTICIPANT_BORDER_WIDTH, + height: childrenBBox.height + VERTICAL_PARTICIPANT_PADDING * 2 + }; + + var width = Math.max(shape.width, childrenBBox.width), + height = Math.max(shape.height, childrenBBox.height); + + return { + x: -width / 2, + y: -height / 2, + width: width, + height: height + }; +} + +function getParticipantCreateConstraints(shape, childrenBBox) { + childrenBBox = asTRBL(childrenBBox); + + return { + bottom: childrenBBox.top + shape.height / 2 - VERTICAL_PARTICIPANT_PADDING, + left: childrenBBox.right - shape.width / 2 + HORIZONTAL_PARTICIPANT_PADDING, + top: childrenBBox.bottom - shape.height / 2 + VERTICAL_PARTICIPANT_PADDING, + right: childrenBBox.left + shape.width / 2 - HORIZONTAL_PARTICIPANT_PADDING - PARTICIPANT_BORDER_WIDTH + }; +} + +function findParticipant(elements) { + return find(elements, function(element) { + return is$2(element, 'bpmn:Participant'); + }); +} + +/** + * Failsafe remove an element from a collection + * + * @param {Array} [collection] + * @param {Object} [element] + * + * @return {number} the previous index of the element + */ +function remove$2(collection, element) { + + if (!collection || !element) { + return -1; + } + + var idx = collection.indexOf(element); + + if (idx !== -1) { + collection.splice(idx, 1); + } + + return idx; +} + +/** + * Fail save add an element to the given connection, ensuring + * it does not yet exist. + * + * @param {Array} collection + * @param {Object} element + * @param {number} [idx] + */ +function add(collection, element, idx) { + + if (!collection || !element) { + return; + } + + if (typeof idx !== 'number') { + idx = -1; + } + + var currentIdx = collection.indexOf(element); + + if (currentIdx !== -1) { + + if (currentIdx === idx) { + + // nothing to do, position has not changed + return; + } else { + + if (idx !== -1) { + + // remove from current position + collection.splice(currentIdx, 1); + } else { + + // already exists in collection + return; + } + } + } + + if (idx !== -1) { + + // insert at specified position + collection.splice(idx, 0, element); + } else { + + // push to end + collection.push(element); + } +} + + +/** + * Fail save get the index of an element in a collection. + * + * @param {Array} collection + * @param {Object} element + * + * @return {number} the index or -1 if collection or element do + * not exist or the element is not contained. + */ +function indexOf(collection, element) { + + if (!collection || !element) { + return -1; + } + + return collection.indexOf(element); +} + +/** + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * @typedef {import('../BpmnFactory').default} BpmnFactory + */ + +var TARGET_REF_PLACEHOLDER_NAME = '__targetRef_placeholder'; + + +/** + * This behavior makes sure we always set a fake + * DataInputAssociation#targetRef as demanded by the BPMN 2.0 + * XSD schema. + * + * The reference is set to a bpmn:Property{ name: '__targetRef_placeholder' } + * which is created on the fly and cleaned up afterwards if not needed + * anymore. + * + * @param {EventBus} eventBus + * @param {BpmnFactory} bpmnFactory + */ +function DataInputAssociationBehavior(eventBus, bpmnFactory) { + + CommandInterceptor.call(this, eventBus); + + + this.executed([ + 'connection.create', + 'connection.delete', + 'connection.move', + 'connection.reconnect' + ], ifDataInputAssociation(fixTargetRef)); + + this.reverted([ + 'connection.create', + 'connection.delete', + 'connection.move', + 'connection.reconnect' + ], ifDataInputAssociation(fixTargetRef)); + + + function usesTargetRef(element, targetRef, removedConnection) { + + var inputAssociations = element.get('dataInputAssociations'); + + return find(inputAssociations, function(association) { + return association !== removedConnection && + association.targetRef === targetRef; + }); + } + + function getTargetRef(element, create) { + + var properties = element.get('properties'); + + var targetRefProp = find(properties, function(p) { + return p.name === TARGET_REF_PLACEHOLDER_NAME; + }); + + if (!targetRefProp && create) { + targetRefProp = bpmnFactory.create('bpmn:Property', { + name: TARGET_REF_PLACEHOLDER_NAME + }); + + add(properties, targetRefProp); + } + + return targetRefProp; + } + + function cleanupTargetRef(element, connection) { + + var targetRefProp = getTargetRef(element); + + if (!targetRefProp) { + return; + } + + if (!usesTargetRef(element, targetRefProp, connection)) { + remove$2(element.get('properties'), targetRefProp); + } + } + + /** + * Make sure targetRef is set to a valid property or + * `null` if the connection is detached. + * + * @param {Event} event + */ + function fixTargetRef(event) { + + var context = event.context, + connection = context.connection, + connectionBo = connection.businessObject, + target = connection.target, + targetBo = target && target.businessObject, + newTarget = context.newTarget, + newTargetBo = newTarget && newTarget.businessObject, + oldTarget = context.oldTarget || context.target, + oldTargetBo = oldTarget && oldTarget.businessObject; + + var dataAssociation = connection.businessObject, + targetRefProp; + + if (oldTargetBo && oldTargetBo !== targetBo) { + cleanupTargetRef(oldTargetBo, connectionBo); + } + + if (newTargetBo && newTargetBo !== targetBo) { + cleanupTargetRef(newTargetBo, connectionBo); + } + + if (targetBo) { + targetRefProp = getTargetRef(targetBo, true); + dataAssociation.targetRef = targetRefProp; + } else { + dataAssociation.targetRef = null; + } + } +} + +DataInputAssociationBehavior.$inject = [ + 'eventBus', + 'bpmnFactory' +]; + +e(DataInputAssociationBehavior, CommandInterceptor); + + +/** + * Only call the given function when the event + * touches a bpmn:DataInputAssociation. + * + * @param {Function} fn + * @return {Function} + */ +function ifDataInputAssociation(fn) { + + return function(event) { + var context = event.context, + connection = context.connection; + + if (is$2(connection, 'bpmn:DataInputAssociation')) { + return fn(event); + } + }; +} + +/** + * @typedef {import('diagram-js/lib/command/CommandHandler').default} CommandHandler + * + * @typedef {import('../BpmnUpdater').default} BpmnUpdater + */ + +/** + * @implements {CommandHandler} + * + * @param {BpmnUpdater} bpmnUpdater + */ +function UpdateSemanticParentHandler(bpmnUpdater) { + this._bpmnUpdater = bpmnUpdater; +} + +UpdateSemanticParentHandler.$inject = [ 'bpmnUpdater' ]; + + +UpdateSemanticParentHandler.prototype.execute = function(context) { + var dataStoreBo = context.dataStoreBo, + dataStoreDi = context.dataStoreDi, + newSemanticParent = context.newSemanticParent, + newDiParent = context.newDiParent; + + context.oldSemanticParent = dataStoreBo.$parent; + context.oldDiParent = dataStoreDi.$parent; + + // update semantic parent + this._bpmnUpdater.updateSemanticParent(dataStoreBo, newSemanticParent); + + // update DI parent + this._bpmnUpdater.updateDiParent(dataStoreDi, newDiParent); + + return []; +}; + +UpdateSemanticParentHandler.prototype.revert = function(context) { + var dataStoreBo = context.dataStoreBo, + dataStoreDi = context.dataStoreDi, + oldSemanticParent = context.oldSemanticParent, + oldDiParent = context.oldDiParent; + + // update semantic parent + this._bpmnUpdater.updateSemanticParent(dataStoreBo, oldSemanticParent); + + // update DI parent + this._bpmnUpdater.updateDiParent(dataStoreDi, oldDiParent); + + return []; +}; + +/** + * @typedef {import('diagram-js/lib/core/Canvas').default} Canvas + * @typedef {import('diagram-js/lib/command/CommandStack').default} CommandStack + * @typedef {import('diagram-js/lib/core/ElementRegistry').default} ElementRegistry + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + */ + +/** + * BPMN specific data store behavior. + * + * @param {Canvas} canvas + * @param {CommandStack} commandStack + * @param {ElementRegistry} elementRegistry + * @param {EventBus} eventBus + */ +function DataStoreBehavior( + canvas, commandStack, elementRegistry, + eventBus) { + + CommandInterceptor.call(this, eventBus); + + commandStack.registerHandler('dataStore.updateContainment', UpdateSemanticParentHandler); + + function getFirstParticipantWithProcessRef() { + return elementRegistry.filter(function(element) { + return is$2(element, 'bpmn:Participant') && getBusinessObject(element).processRef; + })[0]; + } + + function getDataStores(element) { + return element.children.filter(function(child) { + return is$2(child, 'bpmn:DataStoreReference') && !child.labelTarget; + }); + } + + function updateDataStoreParent(dataStore, newDataStoreParent) { + var dataStoreBo = dataStore.businessObject || dataStore; + + newDataStoreParent = newDataStoreParent || getFirstParticipantWithProcessRef(); + + if (newDataStoreParent) { + var newDataStoreParentBo = newDataStoreParent.businessObject || newDataStoreParent; + + commandStack.execute('dataStore.updateContainment', { + dataStoreBo: dataStoreBo, + dataStoreDi: getDi(dataStore), + newSemanticParent: newDataStoreParentBo.processRef || newDataStoreParentBo, + newDiParent: getDi(newDataStoreParent) + }); + } + } + + + // disable auto-resize for data stores + this.preExecute('shape.create', function(event) { + + var context = event.context, + shape = context.shape; + + if (is$2(shape, 'bpmn:DataStoreReference') && + shape.type !== 'label') { + + if (!context.hints) { + context.hints = {}; + } + + // prevent auto resizing + context.hints.autoResize = false; + } + }); + + + // disable auto-resize for data stores + this.preExecute('elements.move', function(event) { + var context = event.context, + shapes = context.shapes; + + var dataStoreReferences = shapes.filter(function(shape) { + return is$2(shape, 'bpmn:DataStoreReference'); + }); + + if (dataStoreReferences.length) { + if (!context.hints) { + context.hints = {}; + } + + // prevent auto resizing for data store references + context.hints.autoResize = shapes.filter(function(shape) { + return !is$2(shape, 'bpmn:DataStoreReference'); + }); + } + }); + + + // update parent on data store created + this.postExecute('shape.create', function(event) { + var context = event.context, + shape = context.shape, + parent = shape.parent; + + + if (is$2(shape, 'bpmn:DataStoreReference') && + shape.type !== 'label' && + is$2(parent, 'bpmn:Collaboration')) { + + updateDataStoreParent(shape); + } + }); + + + // update parent on data store moved + this.postExecute('shape.move', function(event) { + var context = event.context, + shape = context.shape, + oldParent = context.oldParent, + parent = shape.parent; + + if (is$2(oldParent, 'bpmn:Collaboration')) { + + // do nothing if not necessary + return; + } + + if (is$2(shape, 'bpmn:DataStoreReference') && + shape.type !== 'label' && + is$2(parent, 'bpmn:Collaboration')) { + + var participant = is$2(oldParent, 'bpmn:Participant') ? + oldParent : + getAncestor(oldParent, 'bpmn:Participant'); + + updateDataStoreParent(shape, participant); + } + }); + + + // update data store parents on participant or subprocess deleted + this.postExecute('shape.delete', function(event) { + var context = event.context, + shape = context.shape, + rootElement = canvas.getRootElement(); + + if (isAny(shape, [ 'bpmn:Participant', 'bpmn:SubProcess' ]) + && is$2(rootElement, 'bpmn:Collaboration')) { + getDataStores(rootElement) + .filter(function(dataStore) { + return isDescendant(dataStore, shape); + }) + .forEach(function(dataStore) { + updateDataStoreParent(dataStore); + }); + } + }); + + // update data store parents on collaboration -> process + this.postExecute('canvas.updateRoot', function(event) { + var context = event.context, + oldRoot = context.oldRoot, + newRoot = context.newRoot; + + var dataStores = getDataStores(oldRoot); + + dataStores.forEach(function(dataStore) { + + if (is$2(newRoot, 'bpmn:Process')) { + updateDataStoreParent(dataStore, newRoot); + } + + }); + }); +} + +DataStoreBehavior.$inject = [ + 'canvas', + 'commandStack', + 'elementRegistry', + 'eventBus', +]; + +e(DataStoreBehavior, CommandInterceptor); + + +// helpers ////////// + +function isDescendant(descendant, ancestor) { + var descendantBo = descendant.businessObject || descendant, + ancestorBo = ancestor.businessObject || ancestor; + + while (descendantBo.$parent) { + if (descendantBo.$parent === ancestorBo.processRef || ancestorBo) { + return true; + } + + descendantBo = descendantBo.$parent; + } + + return false; +} + +function getAncestor(element, type) { + + while (element.parent) { + if (is$2(element.parent, type)) { + return element.parent; + } + + element = element.parent; + } +} + +var DEFAULT_CHILD_BOX_PADDING = 20; + +/** + * @typedef {import('../../core/Types').ElementLike} Element + * @typedef {import('../../core/Types').ShapeLike} Shape + * + * @typedef {import('../../util/Types').Direction} Direction + * @typedef {import('../../util/Types').Point} Point + * @typedef {import('../../util/Types').Rect} Rect + * @typedef {import('../../util/Types').RectTRBL} RectTRBL + */ + +/** + * Substract a TRBL from another + * + * @param {RectTRBL} trblA + * @param {RectTRBL} trblB + * + * @return {RectTRBL} + */ +function substractTRBL(trblA, trblB) { + return { + top: trblA.top - trblB.top, + right: trblA.right - trblB.right, + bottom: trblA.bottom - trblB.bottom, + left: trblA.left - trblB.left + }; +} + + +/** + * Resize the given bounds by applying the passed + * { top, right, bottom, left } delta. + * + * @param {Rect} bounds + * @param {RectTRBL} resize + * + * @return {Rect} + */ +function resizeTRBL(bounds, resize) { + return { + x: bounds.x + (resize.left || 0), + y: bounds.y + (resize.top || 0), + width: bounds.width - (resize.left || 0) + (resize.right || 0), + height: bounds.height - (resize.top || 0) + (resize.bottom || 0) + }; +} + +function asPadding(mayBePadding, defaultValue) { + if (typeof mayBePadding !== 'undefined') { + return mayBePadding; + } else { + return DEFAULT_CHILD_BOX_PADDING; + } +} + +function addPadding$1(bbox, padding) { + var left, right, top, bottom; + + if (typeof padding === 'object') { + left = asPadding(padding.left); + right = asPadding(padding.right); + top = asPadding(padding.top); + bottom = asPadding(padding.bottom); + } else { + left = right = top = bottom = asPadding(padding); + } + + return { + x: bbox.x - left, + y: bbox.y - top, + width: bbox.width + left + right, + height: bbox.height + top + bottom + }; +} + + +/** + * Is the given element part of the resize + * targets min boundary box? + * + * This is the default implementation which excludes + * connections and labels. + * + * @param {Element} element + */ +function isBBoxChild(element) { + + // exclude connections + if (element.waypoints) { + return false; + } + + // exclude labels + if (element.type === 'label') { + return false; + } + + return true; +} + +/** + * Return children bounding computed from a shapes children + * or a list of prefiltered children. + * + * @param {Shape|Shape[]} shapeOrChildren + * @param {RectTRBL|number} padding + * + * @return {Rect} + */ +function computeChildrenBBox(shapeOrChildren, padding) { + + var elements; + + // compute based on shape + if (shapeOrChildren.length === undefined) { + + // grab all the children that are part of the + // parents children box + elements = filter(shapeOrChildren.children, isBBoxChild); + + } else { + elements = shapeOrChildren; + } + + if (elements.length) { + return addPadding$1(getBBox(elements), padding); + } +} + +/** + * @typedef {import('../../../model/Types').Shape} Shape + * + * @typedef {import('diagram-js/lib/util/Types').Rect} Rect + */ + +var abs$3 = Math.abs; + + +function getTRBLResize(oldBounds, newBounds) { + return substractTRBL(asTRBL(newBounds), asTRBL(oldBounds)); +} + + +var LANE_PARENTS = [ + 'bpmn:Participant', + 'bpmn:Process', + 'bpmn:SubProcess' +]; + +var LANE_INDENTATION = 30; + + +/** + * Return all lanes that are children of the given shape. + * + * @param {Shape} shape + * @param {Shape[]} [collectedShapes] + * + * @return {Shape[]} + */ +function collectLanes(shape, collectedShapes) { + + collectedShapes = collectedShapes || []; + + shape.children.filter(function(s) { + if (is$2(s, 'bpmn:Lane')) { + collectLanes(s, collectedShapes); + + collectedShapes.push(s); + } + }); + + return collectedShapes; +} + + +/** + * Return all lanes that are direct children of the given shape. + * + * @param {Shape} shape + * + * @return {Shape[]} + */ +function getChildLanes(shape) { + return shape.children.filter(function(c) { + return is$2(c, 'bpmn:Lane'); + }); +} + + +/** + * Return the parent shape of the given lane. + * + * @param {Shape} shape + * + * @return {Shape} + */ +function getLanesRoot(shape) { + return getParent$2(shape, LANE_PARENTS) || shape; +} + + +/** + * Compute the required resize operations for lanes + * adjacent to the given shape, assuming it will be + * resized to the given new bounds. + * + * @param {Shape} shape + * @param {Rect} newBounds + * + * @return { { + * shape: Shape; + * newBounds: Rect; + * }[] } + */ +function computeLanesResize(shape, newBounds) { + + var rootElement = getLanesRoot(shape); + + var initialShapes = is$2(rootElement, 'bpmn:Process') ? [] : [ rootElement ]; + + var allLanes = collectLanes(rootElement, initialShapes), + shapeTrbl = asTRBL(shape), + shapeNewTrbl = asTRBL(newBounds), + trblResize = getTRBLResize(shape, newBounds), + resizeNeeded = []; + + allLanes.forEach(function(other) { + + if (other === shape) { + return; + } + + var topResize = 0, + rightResize = trblResize.right, + bottomResize = 0, + leftResize = trblResize.left; + + var otherTrbl = asTRBL(other); + + if (trblResize.top) { + if (abs$3(otherTrbl.bottom - shapeTrbl.top) < 10) { + bottomResize = shapeNewTrbl.top - otherTrbl.bottom; + } + + if (abs$3(otherTrbl.top - shapeTrbl.top) < 5) { + topResize = shapeNewTrbl.top - otherTrbl.top; + } + } + + if (trblResize.bottom) { + if (abs$3(otherTrbl.top - shapeTrbl.bottom) < 10) { + topResize = shapeNewTrbl.bottom - otherTrbl.top; + } + + if (abs$3(otherTrbl.bottom - shapeTrbl.bottom) < 5) { + bottomResize = shapeNewTrbl.bottom - otherTrbl.bottom; + } + } + + if (topResize || rightResize || bottomResize || leftResize) { + + resizeNeeded.push({ + shape: other, + newBounds: resizeTRBL(other, { + top: topResize, + right: rightResize, + bottom: bottomResize, + left: leftResize + }) + }); + } + + }); + + return resizeNeeded; +} + +/** + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * @typedef {import('../../space-tool/BpmnSpaceTool').default} SpaceTool + */ + +var LOW_PRIORITY$j = 500; + + +/** + * BPMN specific delete lane behavior. + * + * @param {EventBus} eventBus + * @param {SpaceTool} spaceTool + */ +function DeleteLaneBehavior(eventBus, spaceTool) { + + CommandInterceptor.call(this, eventBus); + + + function compensateLaneDelete(shape, oldParent) { + + var siblings = getChildLanes(oldParent); + + var topAffected = []; + var bottomAffected = []; + + eachElement(siblings, function(element) { + + if (element.y > shape.y) { + bottomAffected.push(element); + } else { + topAffected.push(element); + } + + return element.children; + }); + + if (!siblings.length) { + return; + } + + var offset; + + if (bottomAffected.length && topAffected.length) { + offset = shape.height / 2; + } else { + offset = shape.height; + } + + var topAdjustments, + bottomAdjustments; + + if (topAffected.length) { + topAdjustments = spaceTool.calculateAdjustments( + topAffected, 'y', offset, shape.y - 10); + + spaceTool.makeSpace( + topAdjustments.movingShapes, + topAdjustments.resizingShapes, + { x: 0, y: offset }, 's'); + } + + if (bottomAffected.length) { + bottomAdjustments = spaceTool.calculateAdjustments( + bottomAffected, 'y', -offset, shape.y + shape.height + 10); + + spaceTool.makeSpace( + bottomAdjustments.movingShapes, + bottomAdjustments.resizingShapes, + { x: 0, y: -offset }, 'n'); + } + } + + + /** + * Adjust sizes of other lanes after lane deletion + */ + this.postExecuted('shape.delete', LOW_PRIORITY$j, function(event) { + + var context = event.context, + hints = context.hints, + shape = context.shape, + oldParent = context.oldParent; + + // only compensate lane deletes + if (!is$2(shape, 'bpmn:Lane')) { + return; + } + + // compensate root deletes only + if (hints && hints.nested) { + return; + } + + compensateLaneDelete(shape, oldParent); + }); +} + +DeleteLaneBehavior.$inject = [ + 'eventBus', + 'spaceTool' +]; + +e(DeleteLaneBehavior, CommandInterceptor); + +/** + * @typedef {import('../../replace/BpmnReplace').default} BpmnReplace + * @typedef {import('didi').Injector} Injector + */ + +var LOW_PRIORITY$i = 500; + + +/** + * Replace boundary event with intermediate event when creating or moving results in detached event. + * + * @param {BpmnReplace} bpmnReplace + * @param {Injector} injector + */ +function DetachEventBehavior(bpmnReplace, injector) { + injector.invoke(CommandInterceptor, this); + + this._bpmnReplace = bpmnReplace; + + var self = this; + + this.postExecuted('elements.create', LOW_PRIORITY$i, function(context) { + var elements = context.elements; + + elements.filter(function(shape) { + var host = shape.host; + + return shouldReplace(shape, host); + }).map(function(shape) { + return elements.indexOf(shape); + }).forEach(function(index) { + context.elements[ index ] = self._replaceShape(elements[ index ]); + }); + }, true); + + this.preExecute('elements.move', LOW_PRIORITY$i, function(context) { + var shapes = context.shapes, + newHost = context.newHost; + + shapes.forEach(function(shape, index) { + var host = shape.host; + + if (shouldReplace(shape, includes$5(shapes, host) ? host : newHost)) { + shapes[ index ] = self._replaceShape(shape); + } + }); + }, true); +} + +DetachEventBehavior.$inject = [ + 'bpmnReplace', + 'injector' +]; + +e(DetachEventBehavior, CommandInterceptor); + +DetachEventBehavior.prototype._replaceShape = function(shape) { + var eventDefinition = getEventDefinition$1(shape), + intermediateEvent; + + if (eventDefinition) { + intermediateEvent = { + type: 'bpmn:IntermediateCatchEvent', + eventDefinitionType: eventDefinition.$type + }; + } else { + intermediateEvent = { + type: 'bpmn:IntermediateThrowEvent' + }; + } + + return this._bpmnReplace.replaceElement(shape, intermediateEvent, { layoutConnection: false }); +}; + + +// helpers ////////// + +function getEventDefinition$1(element) { + var businessObject = getBusinessObject(element), + eventDefinitions = businessObject.eventDefinitions; + + return eventDefinitions && eventDefinitions[0]; +} + +function shouldReplace(shape, host) { + return !isLabel(shape) && is$2(shape, 'bpmn:BoundaryEvent') && !host; +} + +function includes$5(array, item) { + return array.indexOf(item) !== -1; +} + +/** + * @typedef {import('../util/Types').Point} Point + * + * @typedef { { + * bendpoint?: boolean; + * index: number; + * point: Point; + * } } Intersection + */ + +var round$8 = Math.round, + max$6 = Math.max; + + +function circlePath(center, r) { + var x = center.x, + y = center.y; + + return [ + [ 'M', x, y ], + [ 'm', 0, -r ], + [ 'a', r, r, 0, 1, 1, 0, 2 * r ], + [ 'a', r, r, 0, 1, 1, 0, -2 * r ], + [ 'z' ] + ]; +} + +function linePath(points) { + var segments = []; + + points.forEach(function(p, idx) { + segments.push([ idx === 0 ? 'M' : 'L', p.x, p.y ]); + }); + + return segments; +} + + +var INTERSECTION_THRESHOLD$1 = 10; + +/** + * @param {Point[]} waypoints + * @param {Point} reference + * + * @return {Intersection|null} + */ +function getBendpointIntersection(waypoints, reference) { + + var i, w; + + for (i = 0; (w = waypoints[i]); i++) { + + if (pointDistance(w, reference) <= INTERSECTION_THRESHOLD$1) { + return { + point: waypoints[i], + bendpoint: true, + index: i + }; + } + } + + return null; +} + +/** + * @param {Point[]} waypoints + * @param {Point} reference + * + * @return {Intersection|null} + */ +function getPathIntersection(waypoints, reference) { + + var intersections = intersectPaths(circlePath(reference, INTERSECTION_THRESHOLD$1), linePath(waypoints)); + + var a = intersections[0], + b = intersections[intersections.length - 1], + idx; + + if (!a) { + + // no intersection + return null; + } + + if (a !== b) { + + if (a.segment2 !== b.segment2) { + + // we use the bendpoint in between both segments + // as the intersection point + + idx = max$6(a.segment2, b.segment2) - 1; + + return { + point: waypoints[idx], + bendpoint: true, + index: idx + }; + } + + return { + point: { + x: (round$8(a.x + b.x) / 2), + y: (round$8(a.y + b.y) / 2) + }, + index: a.segment2 + }; + } + + return { + point: { + x: round$8(a.x), + y: round$8(a.y) + }, + index: a.segment2 + }; +} + +/** + * Returns the closest point on the connection towards a given reference point. + * + * @param {Point[]} waypoints + * @param {Point} reference + * + * @return {Intersection|null} + */ +function getApproxIntersection(waypoints, reference) { + return getBendpointIntersection(waypoints, reference) || getPathIntersection(waypoints, reference); +} + +/** + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * @typedef {import('../../rules/BpmnRules').default} BpmnRules + * @typedef {import('../../modeling/Modeling').default} Modeling + */ + +/** + * @param {EventBus} eventBus + * @param {BpmnRules} bpmnRules + * @param {Modeling} modeling + */ +function DropOnFlowBehavior(eventBus, bpmnRules, modeling) { + + CommandInterceptor.call(this, eventBus); + + /** + * Reconnect start / end of a connection after + * dropping an element on a flow. + */ + + function insertShape(shape, targetFlow, positionOrBounds) { + var waypoints = targetFlow.waypoints, + waypointsBefore, + waypointsAfter, + dockingPoint, + source, + target, + incomingConnection, + outgoingConnection, + oldOutgoing = shape.outgoing.slice(), + oldIncoming = shape.incoming.slice(); + + var mid; + + if (isNumber(positionOrBounds.width)) { + mid = getMid$2(positionOrBounds); + } else { + mid = positionOrBounds; + } + + var intersection = getApproxIntersection(waypoints, mid); + + if (intersection) { + waypointsBefore = waypoints.slice(0, intersection.index); + waypointsAfter = waypoints.slice(intersection.index + (intersection.bendpoint ? 1 : 0)); + + // due to inaccuracy intersection might have been found + if (!waypointsBefore.length || !waypointsAfter.length) { + return; + } + + dockingPoint = intersection.bendpoint ? waypoints[intersection.index] : mid; + + // if last waypointBefore is inside shape's bounds, ignore docking point + if (waypointsBefore.length === 1 || !isPointInsideBBox$1(shape, waypointsBefore[waypointsBefore.length - 1])) { + waypointsBefore.push(copy(dockingPoint)); + } + + // if first waypointAfter is inside shape's bounds, ignore docking point + if (waypointsAfter.length === 1 || !isPointInsideBBox$1(shape, waypointsAfter[0])) { + waypointsAfter.unshift(copy(dockingPoint)); + } + } + + source = targetFlow.source; + target = targetFlow.target; + + if (bpmnRules.canConnect(source, shape, targetFlow)) { + + // reconnect source -> inserted shape + modeling.reconnectEnd(targetFlow, shape, waypointsBefore || mid); + + incomingConnection = targetFlow; + } + + if (bpmnRules.canConnect(shape, target, targetFlow)) { + + if (!incomingConnection) { + + // reconnect inserted shape -> end + modeling.reconnectStart(targetFlow, shape, waypointsAfter || mid); + + outgoingConnection = targetFlow; + } else { + outgoingConnection = modeling.connect( + shape, target, { type: targetFlow.type, waypoints: waypointsAfter } + ); + } + } + + var duplicateConnections = [].concat( + + incomingConnection && filter(oldIncoming, function(connection) { + return connection.source === incomingConnection.source; + }) || [], + + outgoingConnection && filter(oldOutgoing, function(connection) { + return connection.target === outgoingConnection.target; + }) || [] + ); + + if (duplicateConnections.length) { + modeling.removeElements(duplicateConnections); + } + } + + this.preExecute('elements.move', function(context) { + + var newParent = context.newParent, + shapes = context.shapes, + delta = context.delta, + shape = shapes[0]; + + if (!shape || !newParent) { + return; + } + + // if the new parent is a connection, + // change it to the new parent's parent + if (newParent && newParent.waypoints) { + context.newParent = newParent = newParent.parent; + } + + var shapeMid = getMid$2(shape); + var newShapeMid = { + x: shapeMid.x + delta.x, + y: shapeMid.y + delta.y + }; + + // find a connection which intersects with the + // element's mid point + var connection = find(newParent.children, function(element) { + var canInsert = bpmnRules.canInsert(shapes, element); + + return canInsert && getApproxIntersection(element.waypoints, newShapeMid); + }); + + if (connection) { + context.targetFlow = connection; + context.position = newShapeMid; + } + + }, true); + + this.postExecuted('elements.move', function(context) { + + var shapes = context.shapes, + targetFlow = context.targetFlow, + position = context.position; + + if (targetFlow) { + insertShape(shapes[0], targetFlow, position); + } + + }, true); + + this.preExecute('shape.create', function(context) { + + var parent = context.parent, + shape = context.shape; + + if (bpmnRules.canInsert(shape, parent)) { + context.targetFlow = parent; + context.parent = parent.parent; + } + }, true); + + this.postExecuted('shape.create', function(context) { + + var shape = context.shape, + targetFlow = context.targetFlow, + positionOrBounds = context.position; + + if (targetFlow) { + insertShape(shape, targetFlow, positionOrBounds); + } + }, true); +} + +e(DropOnFlowBehavior, CommandInterceptor); + +DropOnFlowBehavior.$inject = [ + 'eventBus', + 'bpmnRules', + 'modeling' +]; + + +// helpers ///////////////////// + +function isPointInsideBBox$1(bbox, point) { + var x = point.x, + y = point.y; + + return x >= bbox.x && + x <= bbox.x + bbox.width && + y >= bbox.y && + y <= bbox.y + bbox.height; +} + +function copy(obj) { + return assign$3({}, obj); +} + +/** + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * @typedef {import('../Modeling').default} Modeling + */ + +/** + * @param {EventBus} eventBus + * @param {Modeling} modeling + */ +function EventBasedGatewayBehavior(eventBus, modeling) { + + CommandInterceptor.call(this, eventBus); + + /** + * Remove incoming sequence flows of event-based target when creating + * sequence flow. + * + * 1. If source is event-based gateway remove all incoming sequence flows + * 2. If source is not event-based gateway remove all incoming sequence flows + * whose source is event-based gateway + */ + this.preExecuted('connection.create', function(event) { + var context = event.context, + connection = context.connection, + source = context.source, + target = context.target, + hints = context.hints; + + if (hints && hints.createElementsBehavior === false) { + return; + } + + if (!isSequenceFlow(connection)) { + return; + } + + var sequenceFlows = []; + + if (is$2(source, 'bpmn:EventBasedGateway')) { + sequenceFlows = target.incoming.filter(isSequenceFlow); + } else { + sequenceFlows = target.incoming.filter(function(connection) { + return isSequenceFlow(connection) + && is$2(connection.source, 'bpmn:EventBasedGateway'); + }); + } + + sequenceFlows.forEach(function(sequenceFlow) { + modeling.removeConnection(sequenceFlow); + }); + }); + + /** + * Remove incoming sequence flows of event-based targets when replacing source + * with event-based gateway. + */ + this.preExecuted('shape.replace', function(event) { + var context = event.context, + newShape = context.newShape; + + if (!is$2(newShape, 'bpmn:EventBasedGateway')) { + return; + } + + var targets = newShape.outgoing.filter(isSequenceFlow) + .reduce(function(targets, sequenceFlow) { + if (!targets.includes(sequenceFlow.target)) { + return targets.concat(sequenceFlow.target); + } + + return targets; + }, []); + + targets.forEach(function(target) { + target.incoming.filter(isSequenceFlow).forEach(function(sequenceFlow) { + const sequenceFlowsFromNewShape = target.incoming.filter(isSequenceFlow).filter(function(sequenceFlow) { + return sequenceFlow.source === newShape; + }); + + if (sequenceFlow.source !== newShape || sequenceFlowsFromNewShape.length > 1) { + modeling.removeConnection(sequenceFlow); + } + }); + }); + }); +} + +EventBasedGatewayBehavior.$inject = [ + 'eventBus', + 'modeling' +]; + +e(EventBasedGatewayBehavior, CommandInterceptor); + +// helpers ////////// + +function isSequenceFlow(connection) { + return is$2(connection, 'bpmn:SequenceFlow'); +} + +/** + * @typedef {import('diagram-js/lib/core/ElementRegistry').default} ElementRegistry + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * @typedef {import('diagram-js/lib/core/Canvas').default} Canvas + */ + +var HIGH_PRIORITY$d = 1500; +var HIGHEST_PRIORITY = 2000; + + +/** + * Correct hover targets in certain situations to improve diagram interaction. + * + * @param {ElementRegistry} elementRegistry + * @param {EventBus} eventBus + * @param {Canvas} canvas + */ +function FixHoverBehavior(elementRegistry, eventBus, canvas) { + + eventBus.on([ + 'create.hover', + 'create.move', + 'create.out', + 'create.end', + 'shape.move.hover', + 'shape.move.move', + 'shape.move.out', + 'shape.move.end' + ], HIGH_PRIORITY$d, function(event) { + var context = event.context, + shape = context.shape || event.shape, + hover = event.hover; + + // ensure elements are not dropped onto a bpmn:Lane but onto + // the underlying bpmn:Participant + if (is$2(hover, 'bpmn:Lane') && !isAny(shape, [ 'bpmn:Lane', 'bpmn:Participant' ])) { + event.hover = getLanesRoot(hover); + event.hoverGfx = elementRegistry.getGraphics(event.hover); + } + + var rootElement = canvas.getRootElement(); + + // ensure bpmn:Group and label elements are dropped + // always onto the root + if (hover !== rootElement && (shape.labelTarget || is$2(shape, 'bpmn:Group'))) { + event.hover = rootElement; + event.hoverGfx = elementRegistry.getGraphics(event.hover); + } + }); + + eventBus.on([ + 'connect.hover', + 'connect.out', + 'connect.end', + 'connect.cleanup', + 'global-connect.hover', + 'global-connect.out', + 'global-connect.end', + 'global-connect.cleanup' + ], HIGH_PRIORITY$d, function(event) { + var hover = event.hover; + + // ensure connections start/end on bpmn:Participant, + // not the underlying bpmn:Lane + if (is$2(hover, 'bpmn:Lane')) { + event.hover = getLanesRoot(hover) || hover; + event.hoverGfx = elementRegistry.getGraphics(event.hover); + } + }); + + + eventBus.on([ + 'bendpoint.move.hover' + ], HIGH_PRIORITY$d, function(event) { + var context = event.context, + hover = event.hover, + type = context.type; + + // ensure reconnect start/end on bpmn:Participant, + // not the underlying bpmn:Lane + if (is$2(hover, 'bpmn:Lane') && /reconnect/.test(type)) { + event.hover = getLanesRoot(hover) || hover; + event.hoverGfx = elementRegistry.getGraphics(event.hover); + } + }); + + + eventBus.on([ + 'connect.start' + ], HIGH_PRIORITY$d, function(event) { + var context = event.context, + start = context.start; + + // ensure connect start on bpmn:Participant, + // not the underlying bpmn:Lane + if (is$2(start, 'bpmn:Lane')) { + context.start = getLanesRoot(start) || start; + } + }); + + + // allow movement of participants from lanes + eventBus.on('shape.move.start', HIGHEST_PRIORITY, function(event) { + var shape = event.shape; + + if (is$2(shape, 'bpmn:Lane')) { + event.shape = getLanesRoot(shape) || shape; + } + }); + +} + +FixHoverBehavior.$inject = [ + 'elementRegistry', + 'eventBus', + 'canvas' +]; + +/** + * @typedef {import('../../BpmnFactory').default} BpmnFactory + * + * @typedef {import('../../../model/Types').ModdleElement} ModdleElement + */ + +/** + * Creates a new bpmn:CategoryValue inside a new bpmn:Category + * + * @param {BpmnFactory} bpmnFactory + * + * @return {ModdleElement} + */ +function createCategory(bpmnFactory) { + return bpmnFactory.create('bpmn:Category'); +} + +/** + * Creates a new bpmn:CategoryValue inside a new bpmn:Category + * + * @param {BpmnFactory} bpmnFactory + * + * @return {ModdleElement} + */ +function createCategoryValue(bpmnFactory) { + return bpmnFactory.create('bpmn:CategoryValue'); +} + +/** + * Adds category value to definitions + * + * @param {ModdleElement} categoryValue + * @param {ModdleElement} category + * @param {ModdleElement} definitions + * + * @return {ModdleElement} + */ +function linkCategoryValue(categoryValue, category, definitions) { + add(category.get('categoryValue'), categoryValue); + categoryValue.$parent = category; + + add(definitions.get('rootElements'), category); + category.$parent = definitions; + + return categoryValue; +} + +/** + * Unlink category value from parent + * + * @param {ModdleElement} categoryValue + * + * @return {ModdleElement} + */ +function unlinkCategoryValue(categoryValue) { + var category = categoryValue.$parent; + + if (category) { + remove$2(category.get('categoryValue'), categoryValue); + categoryValue.$parent = null; + } + + return categoryValue; +} + +/** + * Unlink category from parent + * + * @param {ModdleElement} category + * + * @return {ModdleElement} + */ +function unlinkCategory(category) { + var definitions = category.$parent; + + if (definitions) { + remove$2(definitions.get('rootElements'), category); + category.$parent = null; + } + + return category; +} + +/** + * @typedef {import('../BpmnFactory').default} BpmnFactory + * @typedef {import('../../../Modeler').default} Modeler + * @typedef {import('diagram-js/lib/core/ElementRegistry').default} ElementRegistry + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * @typedef {import('didi').Injector} Injector + * @typedef {import('../../copy-paste/ModdleCopy').default} ModdleCopy + * + * @typedef {import('../../../model/Types').Element} Element + * @typedef {import('../../../model/Types').Shape} Shape + * + * @typedef {import('diagram-js/lib/util/Types').DirectionTRBL} DirectionTRBL + */ + +var LOWER_PRIORITY = 770; + + +/** + * BPMN specific group behavior. + * + * @param {BpmnFactory} bpmnFactory + * @param {Modeler} bpmnjs + * @param {ElementRegistry} elementRegistry + * @param {EventBus} eventBus + * @param {Injector} injector + * @param {ModdleCopy} moddleCopy + */ +function GroupBehavior( + bpmnFactory, + bpmnjs, + elementRegistry, + eventBus, + injector, + moddleCopy +) { + injector.invoke(CommandInterceptor, this); + + /** + * Returns all group element in the current registry. + * + * @return {Shape[]} + */ + function getGroupElements() { + return elementRegistry.filter(function(e) { + return is$2(e, 'bpmn:Group'); + }); + } + + /** + * Returns true if given category is referenced in one of the given elements. + * + * @param {Element[]} elements + * @param {ModdleElement} category + * + * @return {boolean} + */ + function isReferencedCategory(elements, category) { + return elements.some(function(element) { + var businessObject = getBusinessObject(element); + + var _category = businessObject.categoryValueRef && businessObject.categoryValueRef.$parent; + + return _category === category; + }); + } + + /** + * Returns true if given categoryValue is referenced in one of the given elements. + * + * @param {Element[]} elements + * @param {ModdleElement} categoryValue + * + * @return {boolean} + */ + function isReferencedCategoryValue(elements, categoryValue) { + return elements.some(function(element) { + var businessObject = getBusinessObject(element); + + return businessObject.categoryValueRef === categoryValue; + }); + } + + /** + * Remove category value unless it is still referenced. + * + * @param {ModdleElement} categoryValue + * @param {ModdleElement} category + * @param {ModdleElement} businessObject + */ + function removeCategoryValue(categoryValue, category, businessObject) { + + var groups = getGroupElements().filter(function(element) { + return element.businessObject !== businessObject; + }); + + if (category && !isReferencedCategory(groups, category)) { + unlinkCategory(category); + } + + if (categoryValue && !isReferencedCategoryValue(groups, categoryValue)) { + unlinkCategoryValue(categoryValue); + } + } + + /** + * Add category value. + * + * @param {ModdleElement} categoryValue + * @param {ModdleElement} category + * + * @return {ModdleElement} + */ + function addCategoryValue(categoryValue, category) { + return linkCategoryValue(categoryValue, category, bpmnjs.getDefinitions()); + } + + function setCategoryValue(element, context) { + var businessObject = getBusinessObject(element), + categoryValue = businessObject.categoryValueRef; + + if (!categoryValue) { + categoryValue = + businessObject.categoryValueRef = + context.categoryValue = ( + context.categoryValue || createCategoryValue(bpmnFactory) + ); + } + + var category = categoryValue.$parent; + + if (!category) { + category = + categoryValue.$parent = + context.category = ( + context.category || createCategory(bpmnFactory) + ); + } + + addCategoryValue(categoryValue, category, bpmnjs.getDefinitions()); + } + + function unsetCategoryValue(element, context) { + var category = context.category, + categoryValue = context.categoryValue, + businessObject = getBusinessObject(element); + + if (categoryValue) { + businessObject.categoryValueRef = null; + + removeCategoryValue(categoryValue, category, businessObject); + } else { + removeCategoryValue(null, businessObject.categoryValueRef.$parent, businessObject); + } + } + + + // ensure category + value exist before label editing + + this.execute('label.create', function(event) { + var context = event.context, + labelTarget = context.labelTarget; + + if (!is$2(labelTarget, 'bpmn:Group')) { + return; + } + + setCategoryValue(labelTarget, context); + }); + + this.revert('label.create', function(event) { + var context = event.context, + labelTarget = context.labelTarget; + + if (!is$2(labelTarget, 'bpmn:Group')) { + return; + } + + unsetCategoryValue(labelTarget, context); + }); + + + // remove referenced category + value when group was deleted + + this.execute('shape.delete', function(event) { + + var context = event.context, + shape = context.shape, + businessObject = getBusinessObject(shape); + + if (!is$2(shape, 'bpmn:Group') || shape.labelTarget) { + return; + } + + var categoryValue = context.categoryValue = businessObject.categoryValueRef, + category; + + if (categoryValue) { + category = context.category = categoryValue.$parent; + + removeCategoryValue(categoryValue, category, businessObject); + + businessObject.categoryValueRef = null; + } + }); + + this.reverted('shape.delete', function(event) { + + var context = event.context, + shape = context.shape; + + if (!is$2(shape, 'bpmn:Group') || shape.labelTarget) { + return; + } + + var category = context.category, + categoryValue = context.categoryValue, + businessObject = getBusinessObject(shape); + + if (categoryValue) { + businessObject.categoryValueRef = categoryValue; + + addCategoryValue(categoryValue, category); + } + }); + + + // create new category + value when group was created + + this.execute('shape.create', function(event) { + var context = event.context, + shape = context.shape; + + if (!is$2(shape, 'bpmn:Group') || shape.labelTarget) { + return; + } + + if (getBusinessObject(shape).categoryValueRef) { + setCategoryValue(shape, context); + } + }); + + this.reverted('shape.create', function(event) { + + var context = event.context, + shape = context.shape; + + if (!is$2(shape, 'bpmn:Group') || shape.labelTarget) { + return; + } + + if (getBusinessObject(shape).categoryValueRef) { + unsetCategoryValue(shape, context); + } + }); + + + // copy + paste categoryValueRef with group + + function copy(bo, clone) { + var targetBo = bpmnFactory.create(bo.$type); + + return moddleCopy.copyElement(bo, targetBo, null, clone); + } + + eventBus.on('copyPaste.copyElement', LOWER_PRIORITY, function(context) { + var descriptor = context.descriptor, + element = context.element; + + if (!is$2(element, 'bpmn:Group') || element.labelTarget) { + return; + } + + var groupBo = getBusinessObject(element); + + if (groupBo.categoryValueRef) { + + var categoryValue = groupBo.categoryValueRef; + + descriptor.categoryValue = copy(categoryValue, true); + + if (categoryValue.$parent) { + descriptor.category = copy(categoryValue.$parent, true); + } + } + }); + + eventBus.on('copyPaste.pasteElement', LOWER_PRIORITY, function(context) { + var descriptor = context.descriptor, + businessObject = descriptor.businessObject, + categoryValue = descriptor.categoryValue, + category = descriptor.category; + + if (categoryValue) { + categoryValue = businessObject.categoryValueRef = copy(categoryValue); + } + + if (category) { + categoryValue.$parent = copy(category); + } + + delete descriptor.category; + delete descriptor.categoryValue; + }); + +} + +GroupBehavior.$inject = [ + 'bpmnFactory', + 'bpmnjs', + 'elementRegistry', + 'eventBus', + 'injector', + 'moddleCopy' +]; + +e(GroupBehavior, CommandInterceptor); + +/** + * @typedef {import('diagram-js/lib/util/Types').Point} Point + */ + +/** + * Returns the intersection between two line segments a and b. + * + * @param {Point} l1s + * @param {Point} l1e + * @param {Point} l2s + * @param {Point} l2e + * + * @return {Point} + */ +function lineIntersect(l1s, l1e, l2s, l2e) { + + // if the lines intersect, the result contains the x and y of the + // intersection (treating the lines as infinite) and booleans for + // whether line segment 1 or line segment 2 contain the point + var denominator, a, b, c, numerator; + + denominator = ((l2e.y - l2s.y) * (l1e.x - l1s.x)) - ((l2e.x - l2s.x) * (l1e.y - l1s.y)); + + if (denominator == 0) { + return null; + } + + a = l1s.y - l2s.y; + b = l1s.x - l2s.x; + numerator = ((l2e.x - l2s.x) * a) - ((l2e.y - l2s.y) * b); + + c = numerator / denominator; + + // if we cast these lines infinitely in + // both directions, they intersect here + return { + x: Math.round(l1s.x + (c * (l1e.x - l1s.x))), + y: Math.round(l1s.y + (c * (l1e.y - l1s.y))) + }; +} + +/** + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + */ + +/** + * Fix broken dockings after DI imports. + * + * @param {EventBus} eventBus + */ +function ImportDockingFix(eventBus) { + + function adjustDocking(startPoint, nextPoint, elementMid) { + + var elementTop = { + x: elementMid.x, + y: elementMid.y - 50 + }; + + var elementLeft = { + x: elementMid.x - 50, + y: elementMid.y + }; + + var verticalIntersect = lineIntersect(startPoint, nextPoint, elementMid, elementTop), + horizontalIntersect = lineIntersect(startPoint, nextPoint, elementMid, elementLeft); + + // original is horizontal or vertical center cross intersection + var centerIntersect; + + if (verticalIntersect && horizontalIntersect) { + if (getDistance$1(verticalIntersect, elementMid) > getDistance$1(horizontalIntersect, elementMid)) { + centerIntersect = horizontalIntersect; + } else { + centerIntersect = verticalIntersect; + } + } else { + centerIntersect = verticalIntersect || horizontalIntersect; + } + + startPoint.original = centerIntersect; + } + + function fixDockings(connection) { + var waypoints = connection.waypoints; + + adjustDocking( + waypoints[0], + waypoints[1], + getMid$2(connection.source) + ); + + adjustDocking( + waypoints[waypoints.length - 1], + waypoints[waypoints.length - 2], + getMid$2(connection.target) + ); + } + + eventBus.on('bpmnElement.added', function(e) { + + var element = e.element; + + if (element.waypoints) { + fixDockings(element); + } + }); +} + +ImportDockingFix.$inject = [ + 'eventBus' +]; + + +// helpers ////////////////////// + +function getDistance$1(p1, p2) { + return Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2)); +} + +/** + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + */ + +/** + * A component that makes sure that each created or updated + * Pool and Lane is assigned an isHorizontal property set to true. + * + * @param {EventBus} eventBus + */ +function IsHorizontalFix(eventBus) { + + CommandInterceptor.call(this, eventBus); + + var elementTypesToUpdate = [ + 'bpmn:Participant', + 'bpmn:Lane' + ]; + + this.executed([ 'shape.move', 'shape.create', 'shape.resize' ], function(event) { + var shape = event.context.shape, + bo = getBusinessObject(shape), + di = getDi(shape); + + if (isAny(bo, elementTypesToUpdate) && !di.get('isHorizontal')) { + + // set attribute directly to avoid modeling#updateProperty side effects + di.set('isHorizontal', true); + } + }); + +} + +IsHorizontalFix.$inject = [ 'eventBus' ]; + +e(IsHorizontalFix, CommandInterceptor); + +/** + * @typedef {import('../../util/Types').Point} Point + * @typedef {import('../../util/Types').Vector} Vector + */ + +/** + * Returns the length of a vector. + * + * @param {Vector} vector + * + * @return {number} + */ +function vectorLength$1(vector) { + return Math.sqrt(Math.pow(vector.x, 2) + Math.pow(vector.y, 2)); +} + + +/** + * Calculates the angle between a line a the Y axis. + * + * @param {Point[]} line + * + * @return {number} + */ +function getAngle(line) { + + // return value is between 0, 180 and -180, -0 + // @janstuemmel: maybe replace return a/b with b/a + return Math.atan((line[1].y - line[0].y) / (line[1].x - line[0].x)); +} + + +/** + * Rotates a vector by a given angle. + * + * @param {Vector} vector + * @param {number} angle The angle in radians. + * + * @return {Vector} + */ +function rotateVector(vector, angle) { + return (!angle) ? vector : { + x: Math.cos(angle) * vector.x - Math.sin(angle) * vector.y, + y: Math.sin(angle) * vector.x + Math.cos(angle) * vector.y + }; +} + + +/** + * Solves a 2D equation system + * a + r*b = c, where a,b,c are 2D vectors + * + * @param {Vector} a + * @param {Vector} b + * @param {Vector} c + * + * @return {number} + */ +function solveLambaSystem(a, b, c) { + + // the 2d system + var system = [ + { n: a[0] - c[0], lambda: b[0] }, + { n: a[1] - c[1], lambda: b[1] } + ]; + + // solve + var n = system[0].n * b[0] + system[1].n * b[1], + l = system[0].lambda * b[0] + system[1].lambda * b[1]; + + return -n / l; +} + + +/** + * Calculates the position of the perpendicular foot. + * + * @param {Point} point + * @param {Point[]} line + * + * @return {Point} + */ +function perpendicularFoot(point, line) { + + var a = line[0], b = line[1]; + + // relative position of b from a + var bd = { x: b.x - a.x, y: b.y - a.y }; + + // solve equation system to the parametrized vectors param real value + var r = solveLambaSystem([ a.x, a.y ], [ bd.x, bd.y ], [ point.x, point.y ]); + + return { x: a.x + r * bd.x, y: a.y + r * bd.y }; +} + + +/** + * Calculates the distance between a point and a line. + * + * @param {Point} point + * @param {Point[]} line + * + * @return {number} + */ +function getDistancePointLine(point, line) { + + var pfPoint = perpendicularFoot(point, line); + + // distance vector + var connectionVector = { + x: pfPoint.x - point.x, + y: pfPoint.y - point.y + }; + + return vectorLength$1(connectionVector); +} + + +/** + * Calculates the distance between two points. + * + * @param {Point} point1 + * @param {Point} point2 + * + * @return {number} + */ +function getDistancePointPoint(point1, point2) { + + return vectorLength$1({ + x: point1.x - point2.x, + y: point1.y - point2.y + }); +} + +/** + * @typedef {import('diagram-js/lib/util/Types').Point} Point + * + * @typedef { { +* type: 'bendpoint' | 'segment'; +* position: Point; +* segmentIndex: number; +* bendpointIndex?: number; +* relativeLocation?: number; +* } } Attachment +*/ + +var sqrt = Math.sqrt, + min$3 = Math.min, + max$5 = Math.max, + abs$2 = Math.abs; + +/** + * Calculate the square (power to two) of a number. + * + * @param {number} n + * + * @return {number} + */ +function sq(n) { + return Math.pow(n, 2); +} + +/** + * Get distance between two points. + * + * @param {Point} p1 + * @param {Point} p2 + * + * @return {number} + */ +function getDistance(p1, p2) { + return sqrt(sq(p1.x - p2.x) + sq(p1.y - p2.y)); +} + +/** + * Return the attachment of the given point on the specified line. + * + * The attachment is either a bendpoint (attached to the given point) + * or segment (attached to a location on a line segment) attachment: + * + * ```javascript + * var pointAttachment = { + * type: 'bendpoint', + * bendpointIndex: 3, + * position: { x: 10, y: 10 } // the attach point on the line + * }; + * + * var segmentAttachment = { + * type: 'segment', + * segmentIndex: 2, + * relativeLocation: 0.31, // attach point location between 0 (at start) and 1 (at end) + * position: { x: 10, y: 10 } // the attach point on the line + * }; + * ``` + * + * @param {Point} point + * @param {Point[]} line + * + * @return {Attachment} + */ +function getAttachment(point, line) { + + var idx = 0, + segmentStart, + segmentEnd, + segmentStartDistance, + segmentEndDistance, + attachmentPosition, + minDistance, + intersections, + attachment, + attachmentDistance, + closestAttachmentDistance, + closestAttachment; + + for (idx = 0; idx < line.length - 1; idx++) { + + segmentStart = line[idx]; + segmentEnd = line[idx + 1]; + + if (pointsEqual(segmentStart, segmentEnd)) { + intersections = [ segmentStart ]; + } else { + segmentStartDistance = getDistance(point, segmentStart); + segmentEndDistance = getDistance(point, segmentEnd); + + minDistance = min$3(segmentStartDistance, segmentEndDistance); + + intersections = getCircleSegmentIntersections(segmentStart, segmentEnd, point, minDistance); + } + + if (intersections.length < 1) { + throw new Error('expected between [1, 2] circle -> line intersections'); + } + + // one intersection -> bendpoint attachment + if (intersections.length === 1) { + attachment = { + type: 'bendpoint', + position: intersections[0], + segmentIndex: idx, + bendpointIndex: pointsEqual(segmentStart, intersections[0]) ? idx : idx + 1 + }; + } + + // two intersections -> segment attachment + if (intersections.length === 2) { + + attachmentPosition = mid(intersections[0], intersections[1]); + + attachment = { + type: 'segment', + position: attachmentPosition, + segmentIndex: idx, + relativeLocation: getDistance(segmentStart, attachmentPosition) / getDistance(segmentStart, segmentEnd) + }; + } + + attachmentDistance = getDistance(attachment.position, point); + + if (!closestAttachment || closestAttachmentDistance > attachmentDistance) { + closestAttachment = attachment; + closestAttachmentDistance = attachmentDistance; + } + } + + return closestAttachment; +} + +/** + * Get the intersection between a circle and a line segment. + * + * @param {Point} s1 segment start + * @param {Point} s2 segment end + * @param {Point} cc circle center + * @param {number} cr circle radius + * + * @return {Point[]} intersections + */ +function getCircleSegmentIntersections(s1, s2, cc, cr) { + + var baX = s2.x - s1.x; + var baY = s2.y - s1.y; + var caX = cc.x - s1.x; + var caY = cc.y - s1.y; + + var a = baX * baX + baY * baY; + var bBy2 = baX * caX + baY * caY; + var c = caX * caX + caY * caY - cr * cr; + + var pBy2 = bBy2 / a; + var q = c / a; + + var disc = pBy2 * pBy2 - q; + + // check against negative value to work around + // negative, very close to zero results (-4e-15) + // being produced in some environments + if (disc < 0 && disc > -0.000001) { + disc = 0; + } + + if (disc < 0) { + return []; + } + + // if disc == 0 ... dealt with later + var tmpSqrt = sqrt(disc); + var abScalingFactor1 = -pBy2 + tmpSqrt; + var abScalingFactor2 = -pBy2 - tmpSqrt; + + var i1 = { + x: s1.x - baX * abScalingFactor1, + y: s1.y - baY * abScalingFactor1 + }; + + if (disc === 0) { // abScalingFactor1 == abScalingFactor2 + return [ i1 ]; + } + + var i2 = { + x: s1.x - baX * abScalingFactor2, + y: s1.y - baY * abScalingFactor2 + }; + + // return only points on line segment + return [ i1, i2 ].filter(function(p) { + return isPointInSegment(p, s1, s2); + }); +} + + +function isPointInSegment(p, segmentStart, segmentEnd) { + return ( + fenced(p.x, segmentStart.x, segmentEnd.x) && + fenced(p.y, segmentStart.y, segmentEnd.y) + ); +} + +function fenced(n, rangeStart, rangeEnd) { + + // use matching threshold to work around + // precision errors in intersection computation + + return ( + n >= min$3(rangeStart, rangeEnd) - EQUAL_THRESHOLD && + n <= max$5(rangeStart, rangeEnd) + EQUAL_THRESHOLD + ); +} + +/** + * Calculate the mid between two points. + * + * @param {Point} p1 + * @param {Point} p2 + * + * @return {Point} + */ +function mid(p1, p2) { + + return { + x: (p1.x + p2.x) / 2, + y: (p1.y + p2.y) / 2 + }; +} + +var EQUAL_THRESHOLD = 0.1; + +function pointsEqual(p1, p2) { + + return ( + abs$2(p1.x - p2.x) <= EQUAL_THRESHOLD && + abs$2(p1.y - p2.y) <= EQUAL_THRESHOLD + ); +} + +/** + * @typedef {import('diagram-js/lib/util/Types').Point} Point + * + * @typedef {import('./LineAttachmentUtil').Attachment} Attachment + * + * @typedef { { + * point: Point; + * delta: Point; + * } } AnchorPointAdjustment + * + * @typedef { { + * segmentMove?: { +* segmentStartIndex: number; +* newSegmentStartIndex: number; +* }; +* bendpointMove?: { +* insert: boolean; +* bendpointIndex: number; +* }; +* connectionStart: boolean; +* connectionEnd: boolean; +* } } FindNewLineStartIndexHints + */ + +/** + * @param {Point[]} oldWaypoints + * @param {Point[]} newWaypoints + * @param {Attachment} attachment + * @param {FindNewLineStartIndexHints} hints + * + * @return {number} + */ +function findNewLineStartIndex(oldWaypoints, newWaypoints, attachment, hints) { + + var index = attachment.segmentIndex; + + var offset = newWaypoints.length - oldWaypoints.length; + + // segmentMove happened + if (hints.segmentMove) { + + var oldSegmentStartIndex = hints.segmentMove.segmentStartIndex, + newSegmentStartIndex = hints.segmentMove.newSegmentStartIndex; + + // if point was on moved segment return new segment index + if (index === oldSegmentStartIndex) { + return newSegmentStartIndex; + } + + // point is after new segment index + if (index >= newSegmentStartIndex) { + return (index + offset < newSegmentStartIndex) ? newSegmentStartIndex : index + offset; + } + + // if point is before new segment index + return index; + } + + // bendpointMove happened + if (hints.bendpointMove) { + + var insert = hints.bendpointMove.insert, + bendpointIndex = hints.bendpointMove.bendpointIndex, + newIndex; + + // waypoints length didnt change + if (offset === 0) { + return index; + } + + // point behind new/removed bendpoint + if (index >= bendpointIndex) { + newIndex = insert ? index + 1 : index - 1; + } + + // point before new/removed bendpoint + if (index < bendpointIndex) { + + newIndex = index; + + // decide point should take right or left segment + if (insert && attachment.type !== 'bendpoint' && bendpointIndex - 1 === index) { + + var rel = relativePositionMidWaypoint(newWaypoints, bendpointIndex); + + if (rel < attachment.relativeLocation) { + newIndex++; + } + } + } + + return newIndex; + } + + // start/end changed + if (offset === 0) { + return index; + } + + if (hints.connectionStart && index === 0) { + return 0; + } + + if (hints.connectionEnd && index === oldWaypoints.length - 2) { + return newWaypoints.length - 2; + } + + // if nothing fits, take the middle segment + return Math.floor((newWaypoints.length - 2) / 2); +} + + +/** + * Calculate the required adjustment (move delta) for the given point + * after the connection waypoints got updated. + * + * @param {Point} position + * @param {Point[]} newWaypoints + * @param {Point[]} oldWaypoints + * @param {FindNewLineStartIndexHints} hints + * + * @return {AnchorPointAdjustment} result + */ +function getAnchorPointAdjustment(position, newWaypoints, oldWaypoints, hints) { + + var dx = 0, + dy = 0; + + var oldPosition = { + point: position, + delta: { x: 0, y: 0 } + }; + + // get closest attachment + var attachment = getAttachment(position, oldWaypoints), + oldLabelLineIndex = attachment.segmentIndex, + newLabelLineIndex = findNewLineStartIndex(oldWaypoints, newWaypoints, attachment, hints); + + + // should never happen + // TODO(@janstuemmel): throw an error here when connectionSegmentMove is refactored + if (newLabelLineIndex < 0 || + newLabelLineIndex > newWaypoints.length - 2 || + newLabelLineIndex === null) { + return oldPosition; + } + + var oldLabelLine = getLine(oldWaypoints, oldLabelLineIndex), + newLabelLine = getLine(newWaypoints, newLabelLineIndex), + oldFoot = attachment.position; + + var relativeFootPosition = getRelativeFootPosition(oldLabelLine, oldFoot), + angleDelta = getAngleDelta(oldLabelLine, newLabelLine); + + // special rule if label on bendpoint + if (attachment.type === 'bendpoint') { + + var offset = newWaypoints.length - oldWaypoints.length, + oldBendpointIndex = attachment.bendpointIndex, + oldBendpoint = oldWaypoints[oldBendpointIndex]; + + // bendpoint position hasn't changed, return same position + if (newWaypoints.indexOf(oldBendpoint) !== -1) { + return oldPosition; + } + + // new bendpoint and old bendpoint have same index, then just return the offset + if (offset === 0) { + var newBendpoint = newWaypoints[oldBendpointIndex]; + + dx = newBendpoint.x - attachment.position.x, + dy = newBendpoint.y - attachment.position.y; + + return { + delta: { + x: dx, + y: dy + }, + point: { + x: position.x + dx, + y: position.y + dy + } + }; + } + + // if bendpoints get removed + if (offset < 0 && oldBendpointIndex !== 0 && oldBendpointIndex < oldWaypoints.length - 1) { + relativeFootPosition = relativePositionMidWaypoint(oldWaypoints, oldBendpointIndex); + } + } + + var newFoot = { + x: (newLabelLine[1].x - newLabelLine[0].x) * relativeFootPosition + newLabelLine[0].x, + y: (newLabelLine[1].y - newLabelLine[0].y) * relativeFootPosition + newLabelLine[0].y + }; + + // the rotated vector to label + var newLabelVector = rotateVector({ + x: position.x - oldFoot.x, + y: position.y - oldFoot.y + }, angleDelta); + + // the new relative position + dx = newFoot.x + newLabelVector.x - position.x; + dy = newFoot.y + newLabelVector.y - position.y; + + return { + point: roundPoint(newFoot), + delta: roundPoint({ + x: dx, + y: dy + }) + }; +} + + +// HELPERS ////////////////////// + +function relativePositionMidWaypoint(waypoints, idx) { + + var distanceSegment1 = getDistancePointPoint(waypoints[idx - 1], waypoints[idx]), + distanceSegment2 = getDistancePointPoint(waypoints[idx], waypoints[idx + 1]); + + var relativePosition = distanceSegment1 / (distanceSegment1 + distanceSegment2); + + return relativePosition; +} + +function getAngleDelta(l1, l2) { + var a1 = getAngle(l1), + a2 = getAngle(l2); + return a2 - a1; +} + +function getLine(waypoints, idx) { + return [ waypoints[idx], waypoints[idx + 1] ]; +} + +function getRelativeFootPosition(line, foot) { + + var length = getDistancePointPoint(line[0], line[1]), + lengthToFoot = getDistancePointPoint(line[0], foot); + + return length === 0 ? 0 : lengthToFoot / length; +} + +/** + * Calculate the required adjustment (move delta) for the given label + * after the connection waypoints got updated. + * + * @param {Label} label + * @param {Point[]} newWaypoints + * @param {Point[]} oldWaypoints + * @param {FindNewLineStartIndexHints} hints + * + * @return {Point} + */ +function getLabelAdjustment(label, newWaypoints, oldWaypoints, hints) { + var labelPosition = getMid$2(label); + + return getAnchorPointAdjustment(labelPosition, newWaypoints, oldWaypoints, hints).delta; +} + +/** + * @typedef {import('../model/Types').Shape} Shape + * + * @typedef {import('../util/Types').Point} Point + * @typedef {import('../util/Types').Rect} Rect + */ + +/** + * Calculates the absolute point relative to the new element's position. + * + * @param {Point} point [absolute] + * @param {Rect} oldBounds + * @param {Rect} newBounds + * + * @return {Point} point [absolute] + */ +function getNewAttachPoint(point, oldBounds, newBounds) { + var oldCenter = center(oldBounds), + newCenter = center(newBounds), + oldDelta = delta(point, oldCenter); + + var newDelta = { + x: oldDelta.x * (newBounds.width / oldBounds.width), + y: oldDelta.y * (newBounds.height / oldBounds.height) + }; + + return roundPoint({ + x: newCenter.x + newDelta.x, + y: newCenter.y + newDelta.y + }); +} + + +/** + * Calculates the shape's delta relative to a new position + * of a certain element's bounds. + * + * @param {Shape} shape + * @param {Rect} oldBounds + * @param {Rect} newBounds + * + * @return {Point} delta + */ +function getNewAttachShapeDelta(shape, oldBounds, newBounds) { + var shapeCenter = center(shape), + oldCenter = center(oldBounds), + newCenter = center(newBounds), + shapeDelta = delta(shape, shapeCenter), + oldCenterDelta = delta(shapeCenter, oldCenter), + stickyPositionDelta = getStickyPositionDelta(shapeCenter, oldBounds, newBounds); + + if (stickyPositionDelta) { + return stickyPositionDelta; + } + + var newCenterDelta = { + x: oldCenterDelta.x * (newBounds.width / oldBounds.width), + y: oldCenterDelta.y * (newBounds.height / oldBounds.height) + }; + + var newShapeCenter = { + x: newCenter.x + newCenterDelta.x, + y: newCenter.y + newCenterDelta.y + }; + + return roundPoint({ + x: newShapeCenter.x + shapeDelta.x - shape.x, + y: newShapeCenter.y + shapeDelta.y - shape.y + }); +} + +function getStickyPositionDelta(oldShapeCenter, oldBounds, newBounds) { + var oldTRBL = asTRBL(oldBounds), + newTRBL = asTRBL(newBounds); + + if (isMoved(oldTRBL, newTRBL)) { + return null; + } + + var oldOrientation = getOrientation(oldBounds, oldShapeCenter), + stickyPositionDelta, + newShapeCenter, + newOrientation; + + if (oldOrientation === 'top') { + stickyPositionDelta = { + x: 0, + y: newTRBL.bottom - oldTRBL.bottom + }; + } else if (oldOrientation === 'bottom') { + stickyPositionDelta = { + x: 0, + y: newTRBL.top - oldTRBL.top + }; + } else if (oldOrientation === 'right') { + stickyPositionDelta = { + x: newTRBL.left - oldTRBL.left, + y: 0 + }; + } else if (oldOrientation === 'left') { + stickyPositionDelta = { + x: newTRBL.right - oldTRBL.right, + y: 0 + }; + } else { + + // fallback to proportional movement for corner-placed attachments + return null; + } + + newShapeCenter = { + x: oldShapeCenter.x + stickyPositionDelta.x, + y: oldShapeCenter.y + stickyPositionDelta.y + }; + + newOrientation = getOrientation(newBounds, newShapeCenter); + + if (newOrientation !== oldOrientation) { + + // fallback to proportional movement if orientation would otherwise change + return null; + } + + return stickyPositionDelta; +} + +function isMoved(oldTRBL, newTRBL) { + return isHorizontallyMoved(oldTRBL, newTRBL) || isVerticallyMoved(oldTRBL, newTRBL); +} + +function isHorizontallyMoved(oldTRBL, newTRBL) { + return oldTRBL.right !== newTRBL.right && oldTRBL.left !== newTRBL.left; +} + +function isVerticallyMoved(oldTRBL, newTRBL) { + return oldTRBL.top !== newTRBL.top && oldTRBL.bottom !== newTRBL.bottom; +} + +var NAME_PROPERTY = 'name'; +var TEXT_PROPERTY = 'text'; + +/** + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * @typedef {import('../Modeling').default} Modeling + * @typedef {import('../BpmnFactory').default} BpmnFactory + * @typedef {import('../../../draw/TextRenderer').default} TextRenderer + * + * @typedef {import('diagram-js/lib/util/Types').Point} Point + * @typedef {import('diagram-js/lib/util/Types').Rect} Rect + * + * @typedef {Point[]} Line + */ + +/** + * A component that makes sure that external labels are added + * together with respective elements and properly updated (DI wise) + * during move. + * + * @param {EventBus} eventBus + * @param {Modeling} modeling + * @param {BpmnFactory} bpmnFactory + * @param {TextRenderer} textRenderer + */ +function LabelBehavior( + eventBus, modeling, bpmnFactory, + textRenderer) { + + CommandInterceptor.call(this, eventBus); + + // update label if name property was updated + this.postExecute('element.updateProperties', onPropertyUpdate); + this.postExecute('element.updateModdleProperties', e => { + const elementBo = getBusinessObject(e.context.element); + + if (elementBo === e.context.moddleElement) { + onPropertyUpdate(e); + } + }); + + function onPropertyUpdate(e) { + var context = e.context, + element = context.element, + properties = context.properties; + + if (NAME_PROPERTY in properties) { + modeling.updateLabel(element, properties[NAME_PROPERTY]); + } + + if (TEXT_PROPERTY in properties + && is$2(element, 'bpmn:TextAnnotation')) { + + var newBounds = textRenderer.getTextAnnotationBounds( + { + x: element.x, + y: element.y, + width: element.width, + height: element.height + }, + properties[TEXT_PROPERTY] || '' + ); + + modeling.updateLabel(element, properties.text, newBounds); + } + } + + // create label shape after shape/connection was created + this.postExecute([ 'shape.create', 'connection.create' ], function(e) { + var context = e.context, + hints = context.hints || {}; + + if (hints.createElementsBehavior === false) { + return; + } + + var element = context.shape || context.connection; + + if (isLabel(element) || !isLabelExternal(element)) { + return; + } + + // only create label if attribute available + if (!getLabel(element)) { + return; + } + + modeling.updateLabel(element, getLabel(element)); + }); + + // update label after label shape was deleted + this.postExecute('shape.delete', function(event) { + var context = event.context, + labelTarget = context.labelTarget, + hints = context.hints || {}; + + // check if label + if (labelTarget && hints.unsetLabel !== false) { + modeling.updateLabel(labelTarget, null, null, { removeShape: false }); + } + }); + + function getVisibleLabelAdjustment(event) { + + var context = event.context, + connection = context.connection, + label = connection.label, + hints = assign$3({}, context.hints), + newWaypoints = context.newWaypoints || connection.waypoints, + oldWaypoints = context.oldWaypoints; + + + if (typeof hints.startChanged === 'undefined') { + hints.startChanged = !!hints.connectionStart; + } + + if (typeof hints.endChanged === 'undefined') { + hints.endChanged = !!hints.connectionEnd; + } + + return getLabelAdjustment(label, newWaypoints, oldWaypoints, hints); + } + + this.postExecute([ + 'connection.layout', + 'connection.updateWaypoints' + ], function(event) { + var context = event.context, + hints = context.hints || {}; + + if (hints.labelBehavior === false) { + return; + } + + var connection = context.connection, + label = connection.label, + labelAdjustment; + + // handle missing label as well as the case + // that the label parent does not exist (yet), + // because it is being pasted / created via multi element create + // + // Cf. https://github.com/bpmn-io/bpmn-js/pull/1227 + if (!label || !label.parent) { + return; + } + + labelAdjustment = getVisibleLabelAdjustment(event); + + modeling.moveShape(label, labelAdjustment); + }); + + + // keep label position on shape replace + this.postExecute([ 'shape.replace' ], function(event) { + var context = event.context, + newShape = context.newShape, + oldShape = context.oldShape; + + var businessObject = getBusinessObject(newShape); + + if (businessObject + && isLabelExternal(businessObject) + && oldShape.label + && newShape.label) { + newShape.label.x = oldShape.label.x; + newShape.label.y = oldShape.label.y; + } + }); + + + // move external label after resizing + this.postExecute('shape.resize', function(event) { + + var context = event.context, + shape = context.shape, + newBounds = context.newBounds, + oldBounds = context.oldBounds; + + if (hasExternalLabel(shape)) { + + var label = shape.label, + labelMid = getMid$2(label), + edges = asEdges(oldBounds); + + // get nearest border point to label as reference point + var referencePoint = getReferencePoint(labelMid, edges); + + var delta = getReferencePointDelta(referencePoint, oldBounds, newBounds); + + modeling.moveShape(label, delta); + + } + + }); + +} + +e(LabelBehavior, CommandInterceptor); + +LabelBehavior.$inject = [ + 'eventBus', + 'modeling', + 'bpmnFactory', + 'textRenderer' +]; + +// helpers ////////////////////// + +/** + * Calculates a reference point delta relative to a new position + * of a certain element's bounds + * + * @param {Point} referencePoint + * @param {Rect} oldBounds + * @param {Rect} newBounds + * + * @return {Point} + */ +function getReferencePointDelta(referencePoint, oldBounds, newBounds) { + + var newReferencePoint = getNewAttachPoint(referencePoint, oldBounds, newBounds); + + return roundPoint(delta(newReferencePoint, referencePoint)); +} + +/** + * Generates the nearest point (reference point) for a given point + * onto given set of lines + * + * @param {Point} point + * @param {Line[]} lines + * + * @return {Point} + */ +function getReferencePoint(point, lines) { + + if (!lines.length) { + return; + } + + var nearestLine = getNearestLine(point, lines); + + return perpendicularFoot(point, nearestLine); +} + +/** + * Convert the given bounds to a lines array containing all edges + * + * @param {Rect|Point} bounds + * + * @return {Line[]} + */ +function asEdges(bounds) { + return [ + [ // top + { + x: bounds.x, + y: bounds.y + }, + { + x: bounds.x + (bounds.width || 0), + y: bounds.y + } + ], + [ // right + { + x: bounds.x + (bounds.width || 0), + y: bounds.y + }, + { + x: bounds.x + (bounds.width || 0), + y: bounds.y + (bounds.height || 0) + } + ], + [ // bottom + { + x: bounds.x, + y: bounds.y + (bounds.height || 0) + }, + { + x: bounds.x + (bounds.width || 0), + y: bounds.y + (bounds.height || 0) + } + ], + [ // left + { + x: bounds.x, + y: bounds.y + }, + { + x: bounds.x, + y: bounds.y + (bounds.height || 0) + } + ] + ]; +} + +/** + * Returns the nearest line for a given point by distance + * @param {Point} point + * @param {Line[]} lines + * + * @return {Line} + */ +function getNearestLine(point, lines) { + + var distances = lines.map(function(l) { + return { + line: l, + distance: getDistancePointLine(point, l) + }; + }); + + var sorted = sortBy(distances, 'distance'); + + return sorted[0].line; +} + +/** + * @typedef {import('diagram-js/lib/util/Types').Point} Point + * + * @typedef {import('./LayoutUtil').FindNewLineStartIndexHints} FindNewLineStartIndexHints + */ + +/** + * Calculate the new point after the connection waypoints got updated. + * + * @param {Point} position + * @param {Point[]} newWaypoints + * @param {Point[]} oldWaypoints + * @param {FindNewLineStartIndexHints} hints + * + * @return {Point} + */ +function getConnectionAdjustment(position, newWaypoints, oldWaypoints, hints) { + return getAnchorPointAdjustment(position, newWaypoints, oldWaypoints, hints).point; +} + +/** + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * @typedef {import('../Modeling').default} Modeling + */ + +/** + * A component that makes sure that Associations connected to Connections + * are updated together with the Connection. + * + * @param {EventBus} eventBus + * @param {Modeling} modeling + */ +function LayoutConnectionBehavior(eventBus, modeling) { + + CommandInterceptor.call(this, eventBus); + + function getnewAnchorPoint(event, point) { + + var context = event.context, + connection = context.connection, + hints = assign$3({}, context.hints), + newWaypoints = context.newWaypoints || connection.waypoints, + oldWaypoints = context.oldWaypoints; + + + if (typeof hints.startChanged === 'undefined') { + hints.startChanged = !!hints.connectionStart; + } + + if (typeof hints.endChanged === 'undefined') { + hints.endChanged = !!hints.connectionEnd; + } + + return getConnectionAdjustment(point, newWaypoints, oldWaypoints, hints); + } + + this.postExecute([ + 'connection.layout', + 'connection.updateWaypoints' + ], function(event) { + var context = event.context; + + var connection = context.connection, + outgoing = connection.outgoing, + incoming = connection.incoming; + + incoming.forEach(function(connection) { + var endPoint = connection.waypoints[connection.waypoints.length - 1]; + var newEndpoint = getnewAnchorPoint(event, endPoint); + + var newWaypoints = [].concat(connection.waypoints.slice(0, -1), [ newEndpoint ]); + + modeling.updateWaypoints(connection, newWaypoints); + }); + + outgoing.forEach(function(connection) { + var startpoint = connection.waypoints[0]; + var newStartpoint = getnewAnchorPoint(event, startpoint); + + var newWaypoints = [].concat([ newStartpoint ], connection.waypoints.slice(1)); + + modeling.updateWaypoints(connection, newWaypoints); + }); + + }); + + + this.postExecute([ + 'connection.move' + ], function(event) { + var context = event.context; + + var connection = context.connection, + outgoing = connection.outgoing, + incoming = connection.incoming, + delta = context.delta; + + incoming.forEach(function(connection) { + var endPoint = connection.waypoints[connection.waypoints.length - 1]; + var newEndpoint = { + x: endPoint.x + delta.x, + y: endPoint.y + delta.y + }; + + var newWaypoints = [].concat(connection.waypoints.slice(0, -1), [ newEndpoint ]); + + modeling.updateWaypoints(connection, newWaypoints); + }); + + outgoing.forEach(function(connection) { + var startpoint = connection.waypoints[0]; + var newStartpoint = { + x: startpoint.x + delta.x, + y: startpoint.y + delta.y + }; + + var newWaypoints = [].concat([ newStartpoint ], connection.waypoints.slice(1)); + + modeling.updateWaypoints(connection, newWaypoints); + }); + + }); + +} + +e(LayoutConnectionBehavior, CommandInterceptor); + +LayoutConnectionBehavior.$inject = [ + 'eventBus', + 'modeling' +]; + +/** + * @typedef {import('../model/Types').Element} Element + * @typedef {import('../model/Types').ModdleElement} ModdleElement + */ + +/** + * @param {Element} element + * @param {ModdleElement} [di] + * + * @return {boolean} + */ +function isExpanded(element, di) { + + if (is$2(element, 'bpmn:CallActivity')) { + return false; + } + + if (is$2(element, 'bpmn:SubProcess')) { + di = di || getDi(element); + + if (di && is$2(di, 'bpmndi:BPMNPlane')) { + return true; + } + + return di && !!di.isExpanded; + } + + if (is$2(element, 'bpmn:Participant')) { + return !!getBusinessObject(element).processRef; + } + + return true; +} + +/** + * @param {Element} element + * + * @return {boolean} + */ +function isInterrupting(element) { + return element && getBusinessObject(element).isInterrupting !== false; +} + +/** + * @param {Element} element + * + * @return {boolean} + */ +function isEventSubProcess(element) { + return element && !!getBusinessObject(element).triggeredByEvent; +} + +/** + * @param {Element} element + * @param {string} eventType + * + * @return {boolean} + */ +function hasEventDefinition$2(element, eventType) { + var eventDefinitions = getBusinessObject(element).eventDefinitions; + + return some(eventDefinitions, function(event) { + return is$2(event, eventType); + }); +} + +/** + * @param {Element} element + * + * @return {boolean} + */ +function hasErrorEventDefinition(element) { + return hasEventDefinition$2(element, 'bpmn:ErrorEventDefinition'); +} + +/** + * @param {Element} element + * + * @return {boolean} + */ +function hasEscalationEventDefinition(element) { + return hasEventDefinition$2(element, 'bpmn:EscalationEventDefinition'); +} + +/** + * @param {Element} element + * + * @return {boolean} + */ +function hasCompensateEventDefinition(element) { + return hasEventDefinition$2(element, 'bpmn:CompensateEventDefinition'); +} + +/** + * @typedef {import('../../../../core/Types').ConnectionLike} Connection + * @typedef {import('../../../../core/Types').ShapeLike} Shape + * + * @typedef {import('../../../../util/Types').Point} Point + * @typedef {import('../../../../util/Types').Rect} Rect + */ + +/** + * @param {Connection} connection + * @param {Shape} shape + * @param {Rect} oldBounds + * @return {Point} + */ +function getResizedSourceAnchor(connection, shape, oldBounds) { + + var waypoints = safeGetWaypoints(connection), + waypointsInsideNewBounds = getWaypointsInsideBounds(waypoints, shape), + oldAnchor = waypoints[0]; + + // new anchor is the last waypoint enclosed be resized source + if (waypointsInsideNewBounds.length) { + return waypointsInsideNewBounds[ waypointsInsideNewBounds.length - 1 ]; + } + + return getNewAttachPoint(oldAnchor.original || oldAnchor, oldBounds, shape); +} + + +function getResizedTargetAnchor(connection, shape, oldBounds) { + + var waypoints = safeGetWaypoints(connection), + waypointsInsideNewBounds = getWaypointsInsideBounds(waypoints, shape), + oldAnchor = waypoints[waypoints.length - 1]; + + // new anchor is the first waypoint enclosed be resized target + if (waypointsInsideNewBounds.length) { + return waypointsInsideNewBounds[ 0 ]; + } + + return getNewAttachPoint(oldAnchor.original || oldAnchor, oldBounds, shape); +} + + +function getMovedSourceAnchor(connection, source, moveDelta) { + + var waypoints = safeGetWaypoints(connection), + oldBounds = subtract(source, moveDelta), + oldAnchor = waypoints[ 0 ]; + + return getNewAttachPoint(oldAnchor.original || oldAnchor, oldBounds, source); +} + + +function getMovedTargetAnchor(connection, target, moveDelta) { + + var waypoints = safeGetWaypoints(connection), + oldBounds = subtract(target, moveDelta), + oldAnchor = waypoints[ waypoints.length - 1 ]; + + return getNewAttachPoint(oldAnchor.original || oldAnchor, oldBounds, target); +} + + +// helpers ////////////////////// + +function subtract(bounds, delta) { + return { + x: bounds.x - delta.x, + y: bounds.y - delta.y, + width: bounds.width, + height: bounds.height + }; +} + + +/** + * Return waypoints of given connection; throw if non exists (should not happen!!). + * + * @param {Connection} connection + * + * @return {Point[]} + */ +function safeGetWaypoints(connection) { + + var waypoints = connection.waypoints; + + if (!waypoints.length) { + throw new Error('connection#' + connection.id + ': no waypoints'); + } + + return waypoints; +} + +function getWaypointsInsideBounds(waypoints, bounds) { + var originalWaypoints = map$2(waypoints, getOriginal$1); + + return filter(originalWaypoints, function(waypoint) { + return isInsideBounds(waypoint, bounds); + }); +} + +/** + * Checks if point is inside bounds, incl. edges. + * + * @param {Point} point + * @param {Rect} bounds + */ +function isInsideBounds(point, bounds) { + return getOrientation(bounds, point, 1) === 'intersect'; +} + +function getOriginal$1(point) { + return point.original || point; +} + +/** + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * @typedef {import('../Modeling').default} Modeling + */ + +/** + * BPMN-specific message flow behavior. + * + * @param {EventBus} eventBus + * @param {Modeling} modeling + */ +function MessageFlowBehavior(eventBus, modeling) { + + CommandInterceptor.call(this, eventBus); + + this.postExecute('shape.replace', function(context) { + var oldShape = context.oldShape, + newShape = context.newShape; + + if (!isParticipantCollapse(oldShape, newShape)) { + return; + } + + var messageFlows = getMessageFlows(oldShape); + + messageFlows.incoming.forEach(function(incoming) { + var anchor = getResizedTargetAnchor(incoming, newShape, oldShape); + + modeling.reconnectEnd(incoming, newShape, anchor); + }); + + messageFlows.outgoing.forEach(function(outgoing) { + var anchor = getResizedSourceAnchor(outgoing, newShape, oldShape); + + modeling.reconnectStart(outgoing, newShape, anchor); + }); + }, true); + +} + +MessageFlowBehavior.$inject = [ 'eventBus', 'modeling' ]; + +e(MessageFlowBehavior, CommandInterceptor); + +// helpers ////////// + +function isParticipantCollapse(oldShape, newShape) { + return is$2(oldShape, 'bpmn:Participant') + && isExpanded(oldShape) + && is$2(newShape, 'bpmn:Participant') + && !isExpanded(newShape); +} + +function getMessageFlows(parent) { + var elements = selfAndAllChildren([ parent ], false); + + var incoming = [], + outgoing = []; + + elements.forEach(function(element) { + if (element === parent) { + return; + } + + element.incoming.forEach(function(connection) { + if (is$2(connection, 'bpmn:MessageFlow')) { + incoming.push(connection); + } + }); + + element.outgoing.forEach(function(connection) { + if (is$2(connection, 'bpmn:MessageFlow')) { + outgoing.push(connection); + } + }); + }, []); + + return { + incoming: incoming, + outgoing: outgoing + }; +} + +/** + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * @typedef {import('diagram-js/lib/features/tooltips/Tooltips').default} Tooltips + * @typedef {import('diagram-js/lib/i18n/translate/translate').default} Translate + */ + +var COLLAB_ERR_MSG = 'flow elements must be children of pools/participants'; + +/** + * @param {EventBus} eventBus + * @param {Tooltips} tooltips + * @param {Translate} translate + */ +function ModelingFeedback(eventBus, tooltips, translate) { + + function showError(position, message, timeout) { + tooltips.add({ + position: { + x: position.x + 5, + y: position.y + 5 + }, + type: 'error', + timeout: timeout || 2000, + html: '
' + message + '
' + }); + } + + eventBus.on([ 'shape.move.rejected', 'create.rejected' ], function(event) { + var context = event.context, + shape = context.shape, + target = context.target; + + if (is$2(target, 'bpmn:Collaboration') && is$2(shape, 'bpmn:FlowNode')) { + showError(event, translate(COLLAB_ERR_MSG)); + } + }); + +} + +ModelingFeedback.$inject = [ + 'eventBus', + 'tooltips', + 'translate' +]; + +/** + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * @typedef {import('../Modeling').default} Modeling + */ + +/** + * BPMN specific behavior ensuring that bpmndi:Label's dc:Bounds are removed + * when shape is resized. + * + * @param {EventBus} eventBus + * @param {Modeling} modeling + */ +function RemoveEmbeddedLabelBoundsBehavior(eventBus, modeling) { + CommandInterceptor.call(this, eventBus); + + this.preExecute('shape.resize', function(context) { + var shape = context.shape; + + var di = getDi(shape), + label = di && di.get('label'), + bounds = label && label.get('bounds'); + + if (bounds) { + modeling.updateModdleProperties(shape, label, { + bounds: undefined + }); + } + }, true); +} + +e(RemoveEmbeddedLabelBoundsBehavior, CommandInterceptor); + +RemoveEmbeddedLabelBoundsBehavior.$inject = [ + 'eventBus', + 'modeling' +]; + +/** + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * @typedef {import('../../rules/BpmnRules').default} BpmnRules + * @typedef {import('../Modeling').default} Modeling + */ + +/** + * @param {EventBus} eventBus + * @param {BpmnRules} bpmnRules + * @param {Modeling} modeling + */ +function RemoveElementBehavior(eventBus, bpmnRules, modeling) { + + CommandInterceptor.call(this, eventBus); + + /** + * Combine sequence flows when deleting an element + * if there is one incoming and one outgoing + * sequence flow + */ + this.preExecute('shape.delete', function(e) { + + var shape = e.context.shape; + + // only handle [a] -> [shape] -> [b] patterns + if (shape.incoming.length !== 1 || shape.outgoing.length !== 1) { + return; + } + + var inConnection = shape.incoming[0], + outConnection = shape.outgoing[0]; + + // only handle sequence flows + if (!is$2(inConnection, 'bpmn:SequenceFlow') || !is$2(outConnection, 'bpmn:SequenceFlow')) { + return; + } + + if (bpmnRules.canConnect(inConnection.source, outConnection.target, inConnection)) { + + // compute new, combined waypoints + var newWaypoints = getNewWaypoints(inConnection.waypoints, outConnection.waypoints); + + modeling.reconnectEnd(inConnection, outConnection.target, newWaypoints); + } + }); + +} + +e(RemoveElementBehavior, CommandInterceptor); + +RemoveElementBehavior.$inject = [ + 'eventBus', + 'bpmnRules', + 'modeling' +]; + + +// helpers ////////////////////// + +function getDocking$1(point) { + return point.original || point; +} + + +function getNewWaypoints(inWaypoints, outWaypoints) { + + var intersection = lineIntersect( + getDocking$1(inWaypoints[inWaypoints.length - 2]), + getDocking$1(inWaypoints[inWaypoints.length - 1]), + getDocking$1(outWaypoints[1]), + getDocking$1(outWaypoints[0])); + + if (intersection) { + return [].concat( + inWaypoints.slice(0, inWaypoints.length - 1), + [ intersection ], + outWaypoints.slice(1)); + } else { + return [ + getDocking$1(inWaypoints[0]), + getDocking$1(outWaypoints[outWaypoints.length - 1]) + ]; + } +} + +/** + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * @typedef {import('../Modeling').default} Modeling + */ + +/** + * BPMN specific remove behavior. + * + * @param {EventBus} eventBus + * @param {Modeling} modeling + */ +function RemoveParticipantBehavior(eventBus, modeling) { + + CommandInterceptor.call(this, eventBus); + + + /** + * morph collaboration diagram into process diagram + * after the last participant has been removed + */ + + this.preExecute('shape.delete', function(context) { + + var shape = context.shape, + parent = shape.parent; + + // activate the behavior if the shape to be removed + // is a participant + if (is$2(shape, 'bpmn:Participant')) { + context.collaborationRoot = parent; + } + }, true); + + this.postExecute('shape.delete', function(context) { + + var collaborationRoot = context.collaborationRoot; + + if (collaborationRoot && !collaborationRoot.businessObject.participants.length) { + + // replace empty collaboration with process diagram + modeling.makeProcess(); + } + }, true); + +} + +RemoveParticipantBehavior.$inject = [ 'eventBus', 'modeling' ]; + +e(RemoveParticipantBehavior, CommandInterceptor); + +/** + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * @typedef {import('../Modeling').default} Modeling + * @typedef {import('../../rules/BpmnRules').default} BpmnRules + * @typedef {import('didi').Injector} Injector + */ + +/** + * @param {EventBus} eventBus + * @param {Modeling} modeling + * @param {BpmnRules} bpmnRules + * @param {Injector} injector + */ +function ReplaceConnectionBehavior(eventBus, modeling, bpmnRules, injector) { + + CommandInterceptor.call(this, eventBus); + + var dragging = injector.get('dragging', false); + + function fixConnection(connection) { + + var source = connection.source, + target = connection.target, + parent = connection.parent; + + // do not do anything if connection + // is already deleted (may happen due to other + // behaviors plugged-in before) + if (!parent) { + return; + } + + var replacementType, + remove; + + /** + * Check if incoming or outgoing connections + * can stay or could be substituted with an + * appropriate replacement. + * + * This holds true for SequenceFlow <> MessageFlow. + */ + + if (is$2(connection, 'bpmn:SequenceFlow')) { + if (!bpmnRules.canConnectSequenceFlow(source, target)) { + remove = true; + } + + if (bpmnRules.canConnectMessageFlow(source, target)) { + replacementType = 'bpmn:MessageFlow'; + } + } + + // transform message flows into sequence flows, if possible + + if (is$2(connection, 'bpmn:MessageFlow')) { + + if (!bpmnRules.canConnectMessageFlow(source, target)) { + remove = true; + } + + if (bpmnRules.canConnectSequenceFlow(source, target)) { + replacementType = 'bpmn:SequenceFlow'; + } + } + + if (is$2(connection, 'bpmn:Association') && !bpmnRules.canConnectAssociation(source, target)) { + remove = true; + } + + + // remove invalid connection, + // unless it has been removed already + if (remove) { + modeling.removeConnection(connection); + } + + // replace SequenceFlow <> MessageFlow + + if (replacementType) { + modeling.connect(source, target, { + type: replacementType, + waypoints: connection.waypoints.slice() + }); + } + } + + function replaceReconnectedConnection(event) { + + var context = event.context, + connection = context.connection, + source = context.newSource || connection.source, + target = context.newTarget || connection.target, + allowed, + replacement; + + allowed = bpmnRules.canConnect(source, target); + + if (!allowed || allowed.type === connection.type) { + return; + } + + replacement = modeling.connect(source, target, { + type: allowed.type, + waypoints: connection.waypoints.slice() + }); + + // remove old connection + modeling.removeConnection(connection); + + // replace connection in context to reconnect end/start + context.connection = replacement; + + if (dragging) { + cleanDraggingSelection(connection, replacement); + } + } + + // monkey-patch selection saved in dragging in order to re-select it when operation is finished + function cleanDraggingSelection(oldConnection, newConnection) { + var context = dragging.context(), + previousSelection = context && context.payload.previousSelection, + index; + + // do nothing if not dragging or no selection was present + if (!previousSelection || !previousSelection.length) { + return; + } + + index = previousSelection.indexOf(oldConnection); + + if (index === -1) { + return; + } + + previousSelection.splice(index, 1, newConnection); + } + + // lifecycle hooks + + this.postExecuted('elements.move', function(context) { + + var closure = context.closure, + allConnections = closure.allConnections; + + forEach$2(allConnections, fixConnection); + }, true); + + this.preExecute('connection.reconnect', replaceReconnectedConnection); + + this.postExecuted('element.updateProperties', function(event) { + var context = event.context, + properties = context.properties, + element = context.element, + businessObject = element.businessObject, + connection; + + // remove condition on change to default + if (properties.default) { + connection = find( + element.outgoing, + matchPattern({ id: element.businessObject.default.id }) + ); + + if (connection) { + modeling.updateProperties(connection, { conditionExpression: undefined }); + } + } + + // remove default from source on change to conditional + if (properties.conditionExpression && businessObject.sourceRef.default === businessObject) { + modeling.updateProperties(element.source, { default: undefined }); + } + }); +} + +e(ReplaceConnectionBehavior, CommandInterceptor); + +ReplaceConnectionBehavior.$inject = [ + 'eventBus', + 'modeling', + 'bpmnRules', + 'injector' +]; + +/** + * @typedef {import('../../replace/BpmnReplace').default} BpmnReplace + * @typedef {import('../../rules/BpmnRules').default} BpmnRules + * @typedef {import('diagram-js/lib/core/ElementRegistry').default} ElementRegistry + * @typedef {import('didi').Injector} Injector + * @typedef {import('../Modeling').default} Modeling + * @typedef {import('diagram-js/lib/features/selection/Selection').default} Selection + */ + +/** + * BPMN-specific replace behavior. + * + * @param {BpmnReplace} bpmnReplace + * @param {BpmnRules} bpmnRules + * @param {ElementRegistry} elementRegistry + * @param {Injector} injector + * @param {Modeling} modeling + * @param {Selection} selection + */ +function ReplaceElementBehaviour( + bpmnReplace, + bpmnRules, + elementRegistry, + injector, + modeling, + selection +) { + injector.invoke(CommandInterceptor, this); + + this._bpmnReplace = bpmnReplace; + this._elementRegistry = elementRegistry; + this._selection = selection; + + // replace elements on create, e.g. during copy-paste + this.postExecuted([ 'elements.create' ], 500, function(event) { + var context = event.context, + target = context.parent, + elements = context.elements; + + var elementReplacements = reduce(elements, function(replacements, element) { + var canReplace = bpmnRules.canReplace([ element ], element.host || element.parent || target); + + return canReplace ? replacements.concat(canReplace.replacements) : replacements; + }, []); + + if (elementReplacements.length) { + this._replaceElements(elements, elementReplacements); + } + }, this); + + // replace elements on move + this.postExecuted([ 'elements.move' ], 500, function(event) { + var context = event.context, + target = context.newParent, + newHost = context.newHost, + elements = []; + + forEach$2(context.closure.topLevel, function(topLevelElements) { + if (isEventSubProcess(topLevelElements)) { + elements = elements.concat(topLevelElements.children); + } else { + elements = elements.concat(topLevelElements); + } + }); + + // set target to host if attaching + if (elements.length === 1 && newHost) { + target = newHost; + } + + var canReplace = bpmnRules.canReplace(elements, target); + + if (canReplace) { + this._replaceElements(elements, canReplace.replacements, newHost); + } + }, this); + + // update attachments on host replace + this.postExecute([ 'shape.replace' ], 1500, function(e) { + var context = e.context, + oldShape = context.oldShape, + newShape = context.newShape, + attachers = oldShape.attachers, + canReplace; + + if (attachers && attachers.length) { + canReplace = bpmnRules.canReplace(attachers, newShape); + + this._replaceElements(attachers, canReplace.replacements); + } + + }, this); + + // keep ID on shape replace + this.postExecuted([ 'shape.replace' ], 1500, function(e) { + var context = e.context, + oldShape = context.oldShape, + newShape = context.newShape; + + modeling.unclaimId(oldShape.businessObject.id, oldShape.businessObject); + modeling.updateProperties(newShape, { id: oldShape.id }); + }); +} + +e(ReplaceElementBehaviour, CommandInterceptor); + +ReplaceElementBehaviour.prototype._replaceElements = function(elements, newElements) { + var elementRegistry = this._elementRegistry, + bpmnReplace = this._bpmnReplace, + selection = this._selection; + + forEach$2(newElements, function(replacement) { + var newElement = { + type: replacement.newElementType + }; + + var oldElement = elementRegistry.get(replacement.oldElementId); + + var idx = elements.indexOf(oldElement); + + elements[idx] = bpmnReplace.replaceElement(oldElement, newElement, { select: false }); + }); + + if (newElements) { + selection.select(elements); + } +}; + +ReplaceElementBehaviour.$inject = [ + 'bpmnReplace', + 'bpmnRules', + 'elementRegistry', + 'injector', + 'modeling', + 'selection' +]; + +var HIGH_PRIORITY$c = 1500; + +/** + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * + * @typedef {import('../../../model/Types').Shape} Shape + * + * @typedef {import('diagram-js/lib/util/Types').Dimensions} Dimensions + * @typedef {import('diagram-js/lib/util/Types').Direction} Direction + * @typedef {import('diagram-js/lib/util/Types').RectTRBL} RectTRBL + */ + +/** + * @type {Dimensions} + */ +var GROUP_MIN_DIMENSIONS = { width: 140, height: 120 }; + +/** + * @type {Dimensions} + */ +var LANE_MIN_DIMENSIONS = { width: 300, height: 60 }; + +/** + * @type {Dimensions} + */ +var PARTICIPANT_MIN_DIMENSIONS = { width: 300, height: 150 }; + +/** + * @type {Dimensions} + */ +var SUB_PROCESS_MIN_DIMENSIONS = { width: 140, height: 120 }; + +/** + * @type {Dimensions} + */ +var TEXT_ANNOTATION_MIN_DIMENSIONS = { width: 50, height: 30 }; + +/** + * Set minimum bounds/resize constraints on resize. + * + * @param {EventBus} eventBus + */ +function ResizeBehavior(eventBus) { + eventBus.on('resize.start', HIGH_PRIORITY$c, function(event) { + var context = event.context, + shape = context.shape, + direction = context.direction, + balanced = context.balanced; + + if (is$2(shape, 'bpmn:Lane') || is$2(shape, 'bpmn:Participant')) { + context.resizeConstraints = getParticipantResizeConstraints(shape, direction, balanced); + } + + if (is$2(shape, 'bpmn:Participant')) { + context.minDimensions = PARTICIPANT_MIN_DIMENSIONS; + } + + if (is$2(shape, 'bpmn:SubProcess') && isExpanded(shape)) { + context.minDimensions = SUB_PROCESS_MIN_DIMENSIONS; + } + + if (is$2(shape, 'bpmn:TextAnnotation')) { + context.minDimensions = TEXT_ANNOTATION_MIN_DIMENSIONS; + } + }); +} + +ResizeBehavior.$inject = [ 'eventBus' ]; + + +var abs$1 = Math.abs, + min$2 = Math.min, + max$4 = Math.max; + + +function addToTrbl(trbl, attr, value, choice) { + var current = trbl[attr]; + + // make sure to set the value if it does not exist + // or apply the correct value by comparing against + // choice(value, currentValue) + trbl[attr] = current === undefined ? value : choice(value, current); +} + +function addMin(trbl, attr, value) { + return addToTrbl(trbl, attr, value, min$2); +} + +function addMax(trbl, attr, value) { + return addToTrbl(trbl, attr, value, max$4); +} + +var LANE_RIGHT_PADDING = 20, + LANE_LEFT_PADDING = 50, + LANE_TOP_PADDING = 20, + LANE_BOTTOM_PADDING = 20; + +/** + * @param {Shape} laneShape + * @param {Direction} resizeDirection + * @param {boolean} [balanced=false] + * + * @return { { + * min: RectTRBL; + * max: RectTRBL; + * } } + */ +function getParticipantResizeConstraints(laneShape, resizeDirection, balanced) { + var lanesRoot = getLanesRoot(laneShape); + + var isFirst = true, + isLast = true; + + // max top/bottom size for lanes + var allLanes = collectLanes(lanesRoot, [ lanesRoot ]); + + var laneTrbl = asTRBL(laneShape); + + var maxTrbl = {}, + minTrbl = {}; + + if (/e/.test(resizeDirection)) { + minTrbl.right = laneTrbl.left + LANE_MIN_DIMENSIONS.width; + } else + if (/w/.test(resizeDirection)) { + minTrbl.left = laneTrbl.right - LANE_MIN_DIMENSIONS.width; + } + + allLanes.forEach(function(other) { + + var otherTrbl = asTRBL(other); + + if (/n/.test(resizeDirection)) { + + if (otherTrbl.top < (laneTrbl.top - 10)) { + isFirst = false; + } + + // max top size (based on next element) + if (balanced && abs$1(laneTrbl.top - otherTrbl.bottom) < 10) { + addMax(maxTrbl, 'top', otherTrbl.top + LANE_MIN_DIMENSIONS.height); + } + + // min top size (based on self or nested element) + if (abs$1(laneTrbl.top - otherTrbl.top) < 5) { + addMin(minTrbl, 'top', otherTrbl.bottom - LANE_MIN_DIMENSIONS.height); + } + } + + if (/s/.test(resizeDirection)) { + + if (otherTrbl.bottom > (laneTrbl.bottom + 10)) { + isLast = false; + } + + // max bottom size (based on previous element) + if (balanced && abs$1(laneTrbl.bottom - otherTrbl.top) < 10) { + addMin(maxTrbl, 'bottom', otherTrbl.bottom - LANE_MIN_DIMENSIONS.height); + } + + // min bottom size (based on self or nested element) + if (abs$1(laneTrbl.bottom - otherTrbl.bottom) < 5) { + addMax(minTrbl, 'bottom', otherTrbl.top + LANE_MIN_DIMENSIONS.height); + } + } + }); + + // max top/bottom/left/right size based on flow nodes + var flowElements = lanesRoot.children.filter(function(s) { + return !s.hidden && !s.waypoints && (is$2(s, 'bpmn:FlowElement') || is$2(s, 'bpmn:Artifact')); + }); + + flowElements.forEach(function(flowElement) { + + var flowElementTrbl = asTRBL(flowElement); + + if (isFirst && /n/.test(resizeDirection)) { + addMin(minTrbl, 'top', flowElementTrbl.top - LANE_TOP_PADDING); + } + + if (/e/.test(resizeDirection)) { + addMax(minTrbl, 'right', flowElementTrbl.right + LANE_RIGHT_PADDING); + } + + if (isLast && /s/.test(resizeDirection)) { + addMax(minTrbl, 'bottom', flowElementTrbl.bottom + LANE_BOTTOM_PADDING); + } + + if (/w/.test(resizeDirection)) { + addMin(minTrbl, 'left', flowElementTrbl.left - LANE_LEFT_PADDING); + } + }); + + return { + min: minTrbl, + max: maxTrbl + }; +} + +/** + * @typedef {import('../util/Types').Point} Point + */ + +function __stopPropagation(event) { + if (!event || typeof event.stopPropagation !== 'function') { + return; + } + + event.stopPropagation(); +} + +/** + * @param {import('../core/EventBus').Event} event + * + * @return {Event} + */ +function getOriginal(event) { + return event.originalEvent || event.srcEvent; +} + +/** + * @param {Event|import('../core/EventBus').Event} event + */ +function stopPropagation(event) { + __stopPropagation(event); + __stopPropagation(getOriginal(event)); +} + +/** + * @param {Event} event + * + * @return {Point|null} + */ +function toPoint(event) { + + if (event.pointers && event.pointers.length) { + event = event.pointers[0]; + } + + if (event.touches && event.touches.length) { + event = event.touches[0]; + } + + return event ? { + x: event.clientX, + y: event.clientY + } : null; +} + +function isMac() { + return (/mac/i).test(navigator.platform); +} + +/** + * @param {MouseEvent} event + * @param {string} button + * + * @return {boolean} + */ +function isButton(event, button) { + return (getOriginal(event) || event).button === button; +} + +/** + * @param {MouseEvent} event + * + * @return {boolean} + */ +function isPrimaryButton(event) { + + // button === 0 -> left áka primary mouse button + return isButton(event, 0); +} + +/** + * @param {MouseEvent} event + * + * @return {boolean} + */ +function isAuxiliaryButton(event) { + + // button === 1 -> auxiliary áka wheel button + return isButton(event, 1); +} + +/** + * @param {MouseEvent} event + * + * @return {boolean} + */ +function hasPrimaryModifier(event) { + var originalEvent = getOriginal(event) || event; + + if (!isPrimaryButton(event)) { + return false; + } + + // Use cmd as primary modifier key for mac OS + if (isMac()) { + return originalEvent.metaKey; + } else { + return originalEvent.ctrlKey; + } +} + +/** + * @param {MouseEvent} event + * + * @return {boolean} + */ +function hasSecondaryModifier(event) { + var originalEvent = getOriginal(event) || event; + + return isPrimaryButton(event) && originalEvent.shiftKey; +} + +/** + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * @typedef {import('../Modeling').default} Modeling + */ + +var SLIGHTLY_HIGHER_PRIORITY = 1001; + + +/** + * Invoke {@link Modeling#resizeLane} instead of {@link Modeling#resizeShape} + * when resizing a lane or participant shape. + * + * @param {EventBus} eventBus + * @param {Modeling} modeling + */ +function ResizeLaneBehavior(eventBus, modeling) { + + eventBus.on('resize.start', SLIGHTLY_HIGHER_PRIORITY + 500, function(event) { + var context = event.context, + shape = context.shape; + + if (is$2(shape, 'bpmn:Lane') || is$2(shape, 'bpmn:Participant')) { + + // should we resize the opposite lane(s) in + // order to compensate for the resize operation? + context.balanced = !hasPrimaryModifier(event); + } + }); + + /** + * Intercept resize end and call resize lane function instead. + */ + eventBus.on('resize.end', SLIGHTLY_HIGHER_PRIORITY, function(event) { + var context = event.context, + shape = context.shape, + canExecute = context.canExecute, + newBounds = context.newBounds; + + if (is$2(shape, 'bpmn:Lane') || is$2(shape, 'bpmn:Participant')) { + + if (canExecute) { + + // ensure we have actual pixel values for new bounds + // (important when zoom level was > 1 during move) + newBounds = roundBounds(newBounds); + + // perform the actual resize + modeling.resizeLane(shape, newBounds, context.balanced); + } + + // stop propagation + return false; + } + }); +} + +ResizeLaneBehavior.$inject = [ + 'eventBus', + 'modeling' +]; + +/** + * @typedef {import('../../../Modeler').default} Modeler + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * @typedef {import('didi').Injector} Injector + * @typedef {import('../../copy-paste/ModdleCopy').default} ModdleCopy + * @typedef {import('../BpmnFactory').default} BpmnFactory + * + * @typedef {import('../../../model/Types').Element} Element + * @typedef {import('../../../model/Types').Shape} Shape + * + * @typedef {import('diagram-js/lib/util/Types').DirectionTRBL} DirectionTRBL + */ + +var LOW_PRIORITY$h = 500; + + +/** + * Add referenced root elements (error, escalation, message, signal) if they don't exist. + * Copy referenced root elements on copy & paste. + * + * @param {Modeler} bpmnjs + * @param {EventBus} eventBus + * @param {Injector} injector + * @param {ModdleCopy} moddleCopy + * @param {BpmnFactory} bpmnFactory + */ +function RootElementReferenceBehavior( + bpmnjs, eventBus, injector, moddleCopy, bpmnFactory +) { + injector.invoke(CommandInterceptor, this); + + function canHaveRootElementReference(element) { + return isAny(element, [ 'bpmn:ReceiveTask', 'bpmn:SendTask' ]) || + hasAnyEventDefinition(element, [ + 'bpmn:ErrorEventDefinition', + 'bpmn:EscalationEventDefinition', + 'bpmn:MessageEventDefinition', + 'bpmn:SignalEventDefinition' + ]); + } + + function hasRootElement(rootElement) { + var definitions = bpmnjs.getDefinitions(), + rootElements = definitions.get('rootElements'); + + return !!find(rootElements, matchPattern({ id: rootElement.id })); + } + + function getRootElementReferencePropertyName(eventDefinition) { + if (is$2(eventDefinition, 'bpmn:ErrorEventDefinition')) { + return 'errorRef'; + } else if (is$2(eventDefinition, 'bpmn:EscalationEventDefinition')) { + return 'escalationRef'; + } else if (is$2(eventDefinition, 'bpmn:MessageEventDefinition')) { + return 'messageRef'; + } else if (is$2(eventDefinition, 'bpmn:SignalEventDefinition')) { + return 'signalRef'; + } + } + + function getRootElement(businessObject) { + if (isAny(businessObject, [ 'bpmn:ReceiveTask', 'bpmn:SendTask' ])) { + return businessObject.get('messageRef'); + } + + var eventDefinitions = businessObject.get('eventDefinitions'), + eventDefinition = eventDefinitions[ 0 ]; + + return eventDefinition.get(getRootElementReferencePropertyName(eventDefinition)); + } + + function setRootElement(businessObject, rootElement) { + if (isAny(businessObject, [ 'bpmn:ReceiveTask', 'bpmn:SendTask' ])) { + return businessObject.set('messageRef', rootElement); + } + + var eventDefinitions = businessObject.get('eventDefinitions'), + eventDefinition = eventDefinitions[ 0 ]; + + return eventDefinition.set(getRootElementReferencePropertyName(eventDefinition), rootElement); + } + + // create shape + this.executed([ + 'shape.create', + 'element.updateProperties', + 'element.updateModdleProperties' + ], function(context) { + var shape = context.shape || context.element; + + if (!canHaveRootElementReference(shape)) { + return; + } + + var businessObject = getBusinessObject(shape), + rootElement = getRootElement(businessObject), + rootElements; + + if (rootElement && !hasRootElement(rootElement)) { + rootElements = bpmnjs.getDefinitions().get('rootElements'); + + // add root element + add(rootElements, rootElement); + + context.addedRootElement = rootElement; + } + }, true); + + this.reverted([ + 'shape.create', + 'element.updateProperties', + 'element.updateModdleProperties' + ], function(context) { + var addedRootElement = context.addedRootElement; + + if (!addedRootElement) { + return; + } + + var rootElements = bpmnjs.getDefinitions().get('rootElements'); + + // remove root element + remove$2(rootElements, addedRootElement); + }, true); + + eventBus.on('copyPaste.copyElement', function(context) { + var descriptor = context.descriptor, + element = context.element; + + if (element.labelTarget || !canHaveRootElementReference(element)) { + return; + } + + var businessObject = getBusinessObject(element), + rootElement = getRootElement(businessObject); + + if (rootElement) { + + // TODO(nikku): clone on copy + descriptor.referencedRootElement = rootElement; + } + }); + + eventBus.on('copyPaste.pasteElement', LOW_PRIORITY$h, function(context) { + var descriptor = context.descriptor, + businessObject = descriptor.businessObject, + referencedRootElement = descriptor.referencedRootElement; + + if (!referencedRootElement) { + return; + } + + if (!hasRootElement(referencedRootElement)) { + referencedRootElement = moddleCopy.copyElement( + referencedRootElement, + bpmnFactory.create(referencedRootElement.$type) + ); + } + + setRootElement(businessObject, referencedRootElement); + + delete descriptor.referencedRootElement; + }); +} + +RootElementReferenceBehavior.$inject = [ + 'bpmnjs', + 'eventBus', + 'injector', + 'moddleCopy', + 'bpmnFactory' +]; + +e(RootElementReferenceBehavior, CommandInterceptor); + +// helpers ////////// + +function hasAnyEventDefinition(element, types) { + if (!isArray$4(types)) { + types = [ types ]; + } + + return some(types, function(type) { + return hasEventDefinition$2(element, type); + }); +} + +/** + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * + * @typedef {import('../../../model/Types').Shape} Shape + */ + +var max$3 = Math.max; + +/** + * @param {EventBus} eventBus + */ +function SpaceToolBehavior(eventBus) { + eventBus.on('spaceTool.getMinDimensions', function(context) { + var shapes = context.shapes, + axis = context.axis, + start = context.start, + minDimensions = {}; + + forEach$2(shapes, function(shape) { + var id = shape.id; + + if (is$2(shape, 'bpmn:Participant')) { + + if (isHorizontal(axis)) { + minDimensions[ id ] = PARTICIPANT_MIN_DIMENSIONS; + } else { + minDimensions[ id ] = { + width: PARTICIPANT_MIN_DIMENSIONS.width, + height: getParticipantMinHeight(shape, start) + }; + } + + } + + if (is$2(shape, 'bpmn:SubProcess') && isExpanded(shape)) { + minDimensions[ id ] = SUB_PROCESS_MIN_DIMENSIONS; + } + + if (is$2(shape, 'bpmn:TextAnnotation')) { + minDimensions[ id ] = TEXT_ANNOTATION_MIN_DIMENSIONS; + } + + if (is$2(shape, 'bpmn:Group')) { + minDimensions[ id ] = GROUP_MIN_DIMENSIONS; + } + }); + + return minDimensions; + }); +} + +SpaceToolBehavior.$inject = [ 'eventBus' ]; + + +// helpers ////////// +function isHorizontal(axis) { + return axis === 'x'; +} + +/** + * Get minimum height for participant taking lanes into account. + * + * @param {Shape} participant + * @param {number} start + * + * @return {number} + */ +function getParticipantMinHeight(participant, start) { + var lanesMinHeight; + + if (!hasChildLanes(participant)) { + return PARTICIPANT_MIN_DIMENSIONS.height; + } + + lanesMinHeight = getLanesMinHeight(participant, start); + + return max$3(PARTICIPANT_MIN_DIMENSIONS.height, lanesMinHeight); +} + +function hasChildLanes(element) { + return !!getChildLanes(element).length; +} + +function getLanesMinHeight(participant, resizeStart) { + var lanes = getChildLanes(participant), + resizedLane; + + // find the nested lane which is currently resized + resizedLane = findResizedLane(lanes, resizeStart); + + // resized lane cannot shrink below the minimum height + // but remaining lanes' dimensions are kept intact + return participant.height - resizedLane.height + LANE_MIN_DIMENSIONS.height; +} + +/** + * Find nested lane which is currently resized. + * + * @param {Shape[]} lanes + * @param {number} resizeStart + * + * @return {Shape} + */ +function findResizedLane(lanes, resizeStart) { + var i, lane, childLanes; + + for (i = 0; i < lanes.length; i++) { + lane = lanes[i]; + + // resizing current lane or a lane nested + if (resizeStart >= lane.y && resizeStart <= lane.y + lane.height) { + childLanes = getChildLanes(lane); + + // a nested lane is resized + if (childLanes.length) { + return findResizedLane(childLanes, resizeStart); + } + + // current lane is the resized one + return lane; + } + } +} + +/** + * @typedef {import('../model/Types').Element} Element + * @typedef {import('../model/Types').ModdleElement} ModdleElement + */ + +var planeSuffix = '_plane'; + +/** + * Get primary shape ID for a plane. + * + * @param {Element|ModdleElement} element + * + * @return {string} + */ +function getShapeIdFromPlane(element) { + var id = element.id; + + return removePlaneSuffix(id); +} + +/** + * Get plane ID for a primary shape. + * + * @param {Element|ModdleElement} element + * + * @return {string} + */ +function getPlaneIdFromShape(element) { + var id = element.id; + + if (is$2(element, 'bpmn:SubProcess')) { + return addPlaneSuffix(id); + } + + return id; +} + +/** + * Get plane ID for primary shape ID. + * + * @param {string} id + * + * @return {string} + */ +function toPlaneId(id) { + return addPlaneSuffix(id); +} + +/** + * Check wether element is plane. + * + * @param {Element|ModdleElement} element + * + * @return {boolean} + */ +function isPlane(element) { + var di = getDi(element); + + return is$2(di, 'bpmndi:BPMNPlane'); +} + +function addPlaneSuffix(id) { + return id + planeSuffix; +} + +function removePlaneSuffix(id) { + return id.replace(new RegExp(planeSuffix + '$'), ''); +} + +/** + * @typedef {import('diagram-js/lib/core/Canvas').default} Canvas + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * @typedef {import('../Modeling').default} Modeling + * @typedef {import('../ElementFactory').default} ElementFactory + * @typedef {import('../BpmnFactory').default} BpmnFactory + * @typedef {import('../../../Modeler').default} Modeler + * @typedef {import('diagram-js/lib/core/ElementRegistry').default} ElementRegistry + * + * @typedef {import('../../../model/Types').Element} Element + * @typedef {import('../../../model/Types').Root} Root + * @typedef {import('../../../model/Types').ModdleElement} ModdleElement + */ + +var LOW_PRIORITY$g = 400; +var HIGH_PRIORITY$b = 600; + +var DEFAULT_POSITION$1 = { + x: 180, + y: 160 +}; + + +/** + * Creates bpmndi:BPMNPlane elements and canvas planes when collapsed subprocesses are created. + * + * @param {Canvas} canvas + * @param {EventBus} eventBus + * @param {Modeling} modeling + * @param {ElementFactory} elementFactory + * @param {BpmnFactory} bpmnFactory + * @param {Modeler} bpmnjs + * @param {ElementRegistry} elementRegistry + */ +function SubProcessPlaneBehavior( + canvas, eventBus, modeling, + elementFactory, bpmnFactory, bpmnjs, elementRegistry) { + + CommandInterceptor.call(this, eventBus); + + this._canvas = canvas; + this._eventBus = eventBus; + this._modeling = modeling; + this._elementFactory = elementFactory; + this._bpmnFactory = bpmnFactory; + this._bpmnjs = bpmnjs; + this._elementRegistry = elementRegistry; + + var self = this; + + function isCollapsedSubProcess(element) { + return is$2(element, 'bpmn:SubProcess') && !isExpanded(element); + } + + function createRoot(context) { + var shape = context.shape, + rootElement = context.newRootElement; + + var businessObject = getBusinessObject(shape); + + rootElement = self._addDiagram(rootElement || businessObject); + + context.newRootElement = canvas.addRootElement(rootElement); + } + + function removeRoot(context) { + var shape = context.shape; + + var businessObject = getBusinessObject(shape); + self._removeDiagram(businessObject); + + var rootElement = context.newRootElement = elementRegistry.get(getPlaneIdFromShape(businessObject)); + + canvas.removeRootElement(rootElement); + } + + // add plane elements for newly created sub-processes + // this ensures we can actually drill down into the element + this.executed('shape.create', function(context) { + var shape = context.shape; + if (!isCollapsedSubProcess(shape)) { + return; + } + + createRoot(context); + }, true); + + + this.postExecuted('shape.create', function(context) { + var shape = context.shape, + rootElement = context.newRootElement; + + if (!rootElement || !shape.children) { + return; + } + + self._showRecursively(shape.children); + + self._moveChildrenToShape(shape, rootElement); + }, true); + + + this.reverted('shape.create', function(context) { + var shape = context.shape; + if (!isCollapsedSubProcess(shape)) { + return; + } + + removeRoot(context); + }, true); + + + this.preExecuted('shape.delete', function(context) { + var shape = context.shape; + if (!isCollapsedSubProcess(shape)) { + return; + } + + var attachedRoot = elementRegistry.get(getPlaneIdFromShape(shape)); + + if (!attachedRoot) { + return; + } + + modeling.removeElements(attachedRoot.children.slice()); + }, true); + + + this.executed('shape.delete', function(context) { + var shape = context.shape; + if (!isCollapsedSubProcess(shape)) { + return; + } + removeRoot(context); + }, true); + + + this.reverted('shape.delete', function(context) { + var shape = context.shape; + if (!isCollapsedSubProcess(shape)) { + return; + } + + createRoot(context); + }, true); + + + this.preExecuted('shape.replace', function(context) { + var oldShape = context.oldShape; + var newShape = context.newShape; + + if (!isCollapsedSubProcess(oldShape) || !isCollapsedSubProcess(newShape)) { + return; + } + + // old plane could have content, + // we remove it so it is not recursively deleted from 'shape.delete' + context.oldRoot = canvas.removeRootElement(getPlaneIdFromShape(oldShape)); + }, true); + + + this.postExecuted('shape.replace', function(context) { + var newShape = context.newShape, + source = context.oldRoot, + target = canvas.findRoot(getPlaneIdFromShape(newShape)); + + if (!source || !target) { + return; + } + var elements = source.children; + + modeling.moveElements(elements, { x: 0, y: 0 }, target); + }, true); + + + // rename primary elements when the secondary element changes + // this ensures rootElement.id = element.id + '_plane' + this.executed('element.updateProperties', function(context) { + var shape = context.element; + + if (!is$2(shape, 'bpmn:SubProcess')) { + return; + } + + var properties = context.properties; + var oldProperties = context.oldProperties; + + var oldId = oldProperties.id, + newId = properties.id; + + if (oldId === newId) { + return; + } + + if (isPlane(shape)) { + elementRegistry.updateId(shape, toPlaneId(newId)); + elementRegistry.updateId(oldId, newId); + + return; + } + + var planeElement = elementRegistry.get(toPlaneId(oldId)); + + if (!planeElement) { + return; + } + + elementRegistry.updateId(toPlaneId(oldId), toPlaneId(newId)); + }, true); + + + this.reverted('element.updateProperties', function(context) { + var shape = context.element; + + if (!is$2(shape, 'bpmn:SubProcess')) { + return; + } + + var properties = context.properties; + var oldProperties = context.oldProperties; + + var oldId = oldProperties.id, + newId = properties.id; + + if (oldId === newId) { + return; + } + + if (isPlane(shape)) { + elementRegistry.updateId(shape, toPlaneId(oldId)); + elementRegistry.updateId(newId, oldId); + + return; + } + + var planeElement = elementRegistry.get(toPlaneId(newId)); + + if (!planeElement) { + return; + } + + elementRegistry.updateId(planeElement, toPlaneId(oldId)); + }, true); + + // re-throw element.changed to re-render primary shape if associated plane has + // changed (e.g. bpmn:name property has changed) + eventBus.on('element.changed', function(context) { + var element = context.element; + + if (!isPlane(element)) { + return; + } + + var plane = element; + + var primaryShape = elementRegistry.get(getShapeIdFromPlane(plane)); + + // do not re-throw if no associated primary shape (e.g. bpmn:Process) + if (!primaryShape || primaryShape === plane) { + return; + } + + eventBus.fire('element.changed', { element: primaryShape }); + }); + + + // create/remove plane for the subprocess + this.executed('shape.toggleCollapse', LOW_PRIORITY$g, function(context) { + var shape = context.shape; + + if (!is$2(shape, 'bpmn:SubProcess')) { + return; + } + + if (!isExpanded(shape)) { + createRoot(context); + self._showRecursively(shape.children); + } else { + removeRoot(context); + } + + }, true); + + + // create/remove plane for the subprocess + this.reverted('shape.toggleCollapse', LOW_PRIORITY$g, function(context) { + var shape = context.shape; + + if (!is$2(shape, 'bpmn:SubProcess')) { + return; + } + + if (!isExpanded(shape)) { + createRoot(context); + self._showRecursively(shape.children); + } else { + removeRoot(context); + } + + }, true); + + // move elements between planes + this.postExecuted('shape.toggleCollapse', HIGH_PRIORITY$b, function(context) { + var shape = context.shape; + + if (!is$2(shape, 'bpmn:SubProcess')) { + return; + } + + var rootElement = context.newRootElement; + + if (!rootElement) { + return; + } + + if (!isExpanded(shape)) { + + // collapsed + self._moveChildrenToShape(shape, rootElement); + + } else { + self._moveChildrenToShape(rootElement, shape); + } + }, true); + + + // copy-paste /////////// + + // add elements in plane to tree + eventBus.on('copyPaste.createTree', function(context) { + var element = context.element, + children = context.children; + + if (!isCollapsedSubProcess(element)) { + return; + } + + var id = getPlaneIdFromShape(element); + var parent = elementRegistry.get(id); + + if (parent) { + + // do not copy invisible root element + children.push.apply(children, parent.children); + } + }); + + // set plane children as direct children of collapsed shape + eventBus.on('copyPaste.copyElement', function(context) { + var descriptor = context.descriptor, + element = context.element, + elements = context.elements; + + var parent = element.parent; + + var isPlane = is$2(getDi(parent), 'bpmndi:BPMNPlane'); + if (!isPlane) { + return; + } + + var parentId = getShapeIdFromPlane(parent); + + var referencedShape = find(elements, function(element) { + return element.id === parentId; + }); + + if (!referencedShape) { + return; + } + + descriptor.parent = referencedShape.id; + }); + + // hide children during pasting + eventBus.on('copyPaste.pasteElement', function(context) { + var descriptor = context.descriptor; + + if (!descriptor.parent) { + return; + } + + if (isCollapsedSubProcess(descriptor.parent) || descriptor.parent.hidden) { + descriptor.hidden = true; + } + }); + +} + +e(SubProcessPlaneBehavior, CommandInterceptor); + +/** + * Moves the child elements from source to target. + * + * If the target is a plane, the children are moved to the top left corner. + * Otherwise, the center of the target is used. + * + * @param {Root} source + * @param {Root} target + */ +SubProcessPlaneBehavior.prototype._moveChildrenToShape = function(source, target) { + var modeling = this._modeling; + + var children = source.children; + var offset; + + if (!children) { + return; + } + + // add external labels that weren't children of sub process + children = children.concat(children.reduce(function(labels, child) { + if (child.label && child.label.parent !== source) { + return labels.concat(child.label); + } + + return labels; + }, [])); + + // only change plane if there are no visible children, but don't move them + var visibleChildren = children.filter(function(child) { + return !child.hidden; + }); + + if (!visibleChildren.length) { + modeling.moveElements(children, { x: 0, y: 0 }, target, { autoResize: false }); + return; + } + + var childrenBounds = getBBox(visibleChildren); + + // target is a plane + if (!target.x) { + offset = { + x: DEFAULT_POSITION$1.x - childrenBounds.x, + y: DEFAULT_POSITION$1.y - childrenBounds.y + }; + } + + // source is a plane + else { + + // move relative to the center of the shape + var targetMid = getMid$2(target); + var childrenMid = getMid$2(childrenBounds); + + offset = { + x: targetMid.x - childrenMid.x, + y: targetMid.y - childrenMid.y + }; + } + + modeling.moveElements(children, offset, target, { autoResize: false }); +}; + +/** + * Sets `hidden` property on all children of the given shape. + * + * @param {Element[]} elements + * @param {boolean} [hidden=false] + * + * @return {Element[]} + */ +SubProcessPlaneBehavior.prototype._showRecursively = function(elements, hidden) { + var self = this; + + var result = []; + elements.forEach(function(element) { + element.hidden = !!hidden; + + result = result.concat(element); + + if (element.children) { + result = result.concat( + self._showRecursively(element.children, element.collapsed || hidden) + ); + } + }); + + return result; +}; + +/** + * Adds a given root element to the BPMNDI diagrams. + * + * @param {Root|ModdleElement} planeElement + * + * @return {Root} + */ +SubProcessPlaneBehavior.prototype._addDiagram = function(planeElement) { + var bpmnjs = this._bpmnjs; + var diagrams = bpmnjs.getDefinitions().diagrams; + + if (!planeElement.businessObject) { + planeElement = this._createNewDiagram(planeElement); + } + + diagrams.push(planeElement.di.$parent); + + return planeElement; +}; + + +/** + * Creates a new plane element for the given sub process. + * + * @param {ModdleElement} bpmnElement + * + * @return {Root} + */ +SubProcessPlaneBehavior.prototype._createNewDiagram = function(bpmnElement) { + var bpmnFactory = this._bpmnFactory, + elementFactory = this._elementFactory; + + var diPlane = bpmnFactory.create('bpmndi:BPMNPlane', { + bpmnElement: bpmnElement + }); + + var diDiagram = bpmnFactory.create('bpmndi:BPMNDiagram', { + plane: diPlane + }); + + diPlane.$parent = diDiagram; + + // add a virtual element (not being drawn), + // a copy cat of our BpmnImporter code + var planeElement = elementFactory.createRoot({ + id: getPlaneIdFromShape(bpmnElement), + type: bpmnElement.$type, + di: diPlane, + businessObject: bpmnElement, + collapsed: true + }); + + return planeElement; +}; + +/** + * Removes the diagram for a given root element. + * + * @param {Root} rootElement + * + * @return {ModdleElement} + */ +SubProcessPlaneBehavior.prototype._removeDiagram = function(rootElement) { + var bpmnjs = this._bpmnjs; + + var diagrams = bpmnjs.getDefinitions().diagrams; + + var removedDiagram = find(diagrams, function(diagram) { + return diagram.plane.bpmnElement.id === rootElement.id; + }); + + diagrams.splice(diagrams.indexOf(removedDiagram), 1); + + return removedDiagram; +}; + + +SubProcessPlaneBehavior.$inject = [ + 'canvas', + 'eventBus', + 'modeling', + 'elementFactory', + 'bpmnFactory', + 'bpmnjs', + 'elementRegistry' +]; + +/** + * @typedef {import('didi').Injector} Injector + * @typedef {import('../Modeling').default} Modeling + */ + +/** + * Add start event replacing element with expanded sub process. + * + * @param {Injector} injector + * @param {Modeling} modeling + */ +function SubProcessStartEventBehavior(injector, modeling) { + injector.invoke(CommandInterceptor, this); + + this.postExecuted('shape.replace', function(event) { + var oldShape = event.context.oldShape, + newShape = event.context.newShape; + + if ( + !is$2(newShape, 'bpmn:SubProcess') || + ! (is$2(oldShape, 'bpmn:Task') || is$2(oldShape, 'bpmn:CallActivity')) || + !isExpanded(newShape) + ) { + return; + } + + var position = getStartEventPosition(newShape); + + modeling.createShape({ type: 'bpmn:StartEvent' }, position, newShape); + }); +} + +SubProcessStartEventBehavior.$inject = [ + 'injector', + 'modeling' +]; + +e(SubProcessStartEventBehavior, CommandInterceptor); + +// helpers ////////// + +function getStartEventPosition(shape) { + return { + x: shape.x + shape.width / 6, + y: shape.y + shape.height / 2 + }; +} + +/** + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * @typedef {import('../Modeling').default} Modeling + * + * @typedef {import('../../../model/Types').Element} Element + * @typedef {import('../../../model/Types').Shape} Shape + * + * @typedef {import('diagram-js/lib/util/Types').DirectionTRBL} DirectionTRBL + */ + +/** + * @param {EventBus} eventBus + * @param {Modeling} modeling + */ +function ToggleCollapseConnectionBehaviour( + eventBus, modeling +) { + + CommandInterceptor.call(this, eventBus); + + this.postExecuted('shape.toggleCollapse', 1500, function(context) { + + // var shape = context.shape; + var shape = context.shape; + + // only change connections when collapsing + if (isExpanded(shape)) { + return; + } + + var allChildren = selfAndAllChildren(shape); + + allChildren.forEach(function(child) { + + // Ensure that the connection array is not modified during iteration + var incomingConnections = child.incoming.slice(), + outgoingConnections = child.outgoing.slice(); + + forEach$2(incomingConnections, function(c) { + handleConnection(c, true); + }); + + forEach$2(outgoingConnections, function(c) { + handleConnection(c, false); + }); + }); + + + function handleConnection(c, incoming) { + if (allChildren.indexOf(c.source) !== -1 && allChildren.indexOf(c.target) !== -1) { + return; + } + + if (incoming) { + modeling.reconnectEnd(c, shape, getMid$2(shape)); + } else { + modeling.reconnectStart(c, shape, getMid$2(shape)); + } + + } + + }, true); + +} + +e(ToggleCollapseConnectionBehaviour, CommandInterceptor); + +ToggleCollapseConnectionBehaviour.$inject = [ + 'eventBus', + 'modeling', +]; + +/** + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * @typedef {import('../ElementFactory').default} ElementFactory + * @typedef {import('../Modeling').default} Modeling + */ + +var LOW_PRIORITY$f = 500; + +/** + * @param {EventBus} eventBus + * @param {ElementFactory} elementFactory + * @param {Modeling} modeling + */ +function ToggleElementCollapseBehaviour( + eventBus, elementFactory, modeling) { + + CommandInterceptor.call(this, eventBus); + + + function hideEmptyLabels(children) { + if (children.length) { + children.forEach(function(child) { + if (child.type === 'label' && !child.businessObject.name) { + child.hidden = true; + } + }); + } + } + + function expandedBounds(shape, defaultSize) { + var children = shape.children, + newBounds = defaultSize, + visibleElements, + visibleBBox; + + visibleElements = filterVisible(children).concat([ shape ]); + + visibleBBox = computeChildrenBBox(visibleElements); + + if (visibleBBox) { + + // center to visibleBBox with max(defaultSize, childrenBounds) + newBounds.width = Math.max(visibleBBox.width, newBounds.width); + newBounds.height = Math.max(visibleBBox.height, newBounds.height); + + newBounds.x = visibleBBox.x + (visibleBBox.width - newBounds.width) / 2; + newBounds.y = visibleBBox.y + (visibleBBox.height - newBounds.height) / 2; + } else { + + // center to collapsed shape with defaultSize + newBounds.x = shape.x + (shape.width - newBounds.width) / 2; + newBounds.y = shape.y + (shape.height - newBounds.height) / 2; + } + + return newBounds; + } + + function collapsedBounds(shape, defaultSize) { + + return { + x: shape.x + (shape.width - defaultSize.width) / 2, + y: shape.y + (shape.height - defaultSize.height) / 2, + width: defaultSize.width, + height: defaultSize.height + }; + } + + this.executed([ 'shape.toggleCollapse' ], LOW_PRIORITY$f, function(e) { + + var context = e.context, + shape = context.shape; + + if (!is$2(shape, 'bpmn:SubProcess')) { + return; + } + + if (!shape.collapsed) { + + // all children got made visible through djs, hide empty labels + hideEmptyLabels(shape.children); + + // remove collapsed marker + getDi(shape).isExpanded = true; + } else { + + // place collapsed marker + getDi(shape).isExpanded = false; + } + }); + + this.reverted([ 'shape.toggleCollapse' ], LOW_PRIORITY$f, function(e) { + + var context = e.context; + var shape = context.shape; + + + // revert removing/placing collapsed marker + if (!shape.collapsed) { + getDi(shape).isExpanded = true; + + } else { + getDi(shape).isExpanded = false; + } + }); + + this.postExecuted([ 'shape.toggleCollapse' ], LOW_PRIORITY$f, function(e) { + var shape = e.context.shape, + defaultSize = elementFactory.getDefaultSize(shape), + newBounds; + + if (shape.collapsed) { + + // resize to default size of collapsed shapes + newBounds = collapsedBounds(shape, defaultSize); + } else { + + // resize to bounds of max(visible children, defaultSize) + newBounds = expandedBounds(shape, defaultSize); + } + + modeling.resizeShape(shape, newBounds, null, { + autoResize: shape.collapsed ? false : 'nwse' + }); + }); + +} + + +e(ToggleElementCollapseBehaviour, CommandInterceptor); + +ToggleElementCollapseBehaviour.$inject = [ + 'eventBus', + 'elementFactory', + 'modeling' +]; + + +// helpers ////////////////////// + +function filterVisible(elements) { + return elements.filter(function(e) { + return !e.hidden; + }); +} + +/** + * @typedef {import('diagram-js/lib/core/Canvas').default} Canvas + * @typedef {import('didi').Injector} Injector + * @typedef {import('../Modeling').default} Modeling + * + * @typedef {import('../../../model/Types').Moddle} Moddle + */ + +/** + * Unclaims model IDs on element deletion. + * + * @param {Canvas} canvas + * @param {Injector} injector + * @param {Moddle} moddle + * @param {Modeling} modeling + */ +function UnclaimIdBehavior(canvas, injector, moddle, modeling) { + injector.invoke(CommandInterceptor, this); + + this.preExecute('shape.delete', function(event) { + var context = event.context, + shape = context.shape, + shapeBo = shape.businessObject; + + if (isLabel(shape)) { + return; + } + + if (is$2(shape, 'bpmn:Participant') && isExpanded(shape)) { + moddle.ids.unclaim(shapeBo.processRef.id); + } + + modeling.unclaimId(shapeBo.id, shapeBo); + }); + + + this.preExecute('connection.delete', function(event) { + var context = event.context, + connection = context.connection, + connectionBo = connection.businessObject; + + modeling.unclaimId(connectionBo.id, connectionBo); + }); + + this.preExecute('canvas.updateRoot', function() { + var rootElement = canvas.getRootElement(), + rootElementBo = rootElement.businessObject; + + if (is$2(rootElement, 'bpmn:Collaboration')) { + moddle.ids.unclaim(rootElementBo.id); + } + }); +} + +e(UnclaimIdBehavior, CommandInterceptor); + +UnclaimIdBehavior.$inject = [ 'canvas', 'injector', 'moddle', 'modeling' ]; + +/** + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * @typedef {import('../Modeling').default} Modeling + */ + +/** + * A behavior that unsets the Default property of sequence flow source on + * element delete, if the removed element is the Gateway or Task's default flow. + * + * @param {EventBus} eventBus + * @param {Modeling} modeling + */ +function DeleteSequenceFlowBehavior(eventBus, modeling) { + + CommandInterceptor.call(this, eventBus); + + + this.preExecute('connection.delete', function(event) { + var context = event.context, + connection = context.connection, + source = connection.source; + + if (isDefaultFlow(connection, source)) { + modeling.updateProperties(source, { + 'default': null + }); + } + }); +} + +e(DeleteSequenceFlowBehavior, CommandInterceptor); + +DeleteSequenceFlowBehavior.$inject = [ + 'eventBus', + 'modeling' +]; + + +// helpers ////////////////////// + +function isDefaultFlow(connection, source) { + + if (!is$2(connection, 'bpmn:SequenceFlow')) { + return false; + } + + var sourceBo = getBusinessObject(source), + sequenceFlow = getBusinessObject(connection); + + return sourceBo.get('default') === sequenceFlow; +} + +/** + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * @typedef {import('../Modeling').default} Modeling + * @typedef {import('diagram-js/lib/i18n/translate/translate').default} Translate + */ + +var LOW_PRIORITY$e = 500, + HIGH_PRIORITY$a = 5000; + + +/** + * BPMN specific delete lane behavior. + * + * @param {EventBus} eventBus + * @param {Modeling} modeling + * @param {Translate} translate + */ +function UpdateFlowNodeRefsBehavior(eventBus, modeling, translate) { + + CommandInterceptor.call(this, eventBus); + + /** + * Update Lane#flowNodeRefs and FlowNode#lanes with every flow node + * move/resize and lane move/resize. Groups elements to recompute containments + * as efficient as possible. + */ + + // the update context + var context; + + + function initContext() { + context = context || new UpdateContext(); + context.enter(); + + return context; + } + + function getContext() { + if (!context) { + throw new Error(translate('out of bounds release')); + } + + return context; + } + + function releaseContext() { + + if (!context) { + throw new Error(translate('out of bounds release')); + } + + var triggerUpdate = context.leave(); + + if (triggerUpdate) { + modeling.updateLaneRefs(context.flowNodes, context.lanes); + + context = null; + } + + return triggerUpdate; + } + + + var laneRefUpdateEvents = [ + 'spaceTool', + 'lane.add', + 'lane.resize', + 'lane.split', + 'elements.create', + 'elements.delete', + 'elements.move', + 'shape.create', + 'shape.delete', + 'shape.move', + 'shape.resize' + ]; + + + // listen to a lot of stuff to group lane updates + + this.preExecute(laneRefUpdateEvents, HIGH_PRIORITY$a, function(event) { + initContext(); + }); + + this.postExecuted(laneRefUpdateEvents, LOW_PRIORITY$e, function(event) { + releaseContext(); + }); + + + // Mark flow nodes + lanes that need an update + + this.preExecute([ + 'shape.create', + 'shape.move', + 'shape.delete', + 'shape.resize' + ], function(event) { + + var context = event.context, + shape = context.shape; + + var updateContext = getContext(); + + // no need to update labels + if (shape.labelTarget) { + return; + } + + if (is$2(shape, 'bpmn:Lane')) { + updateContext.addLane(shape); + } + + if (is$2(shape, 'bpmn:FlowNode')) { + updateContext.addFlowNode(shape); + } + }); +} + +UpdateFlowNodeRefsBehavior.$inject = [ + 'eventBus', + 'modeling' , + 'translate' +]; + +e(UpdateFlowNodeRefsBehavior, CommandInterceptor); + + +function UpdateContext() { + + this.flowNodes = []; + this.lanes = []; + + this.counter = 0; + + this.addLane = function(lane) { + this.lanes.push(lane); + }; + + this.addFlowNode = function(flowNode) { + this.flowNodes.push(flowNode); + }; + + this.enter = function() { + this.counter++; + }; + + this.leave = function() { + this.counter--; + + return !this.counter; + }; +} + +/** + * @type { import('didi').ModuleDeclaration } + */ +var BehaviorModule = { + __init__: [ + 'adaptiveLabelPositioningBehavior', + 'appendBehavior', + 'associationBehavior', + 'attachEventBehavior', + 'boundaryEventBehavior', + 'createBehavior', + 'createDataObjectBehavior', + 'createParticipantBehavior', + 'dataInputAssociationBehavior', + 'dataStoreBehavior', + 'deleteLaneBehavior', + 'detachEventBehavior', + 'dropOnFlowBehavior', + 'eventBasedGatewayBehavior', + 'fixHoverBehavior', + 'groupBehavior', + 'importDockingFix', + 'isHorizontalFix', + 'labelBehavior', + 'layoutConnectionBehavior', + 'messageFlowBehavior', + 'modelingFeedback', + 'removeElementBehavior', + 'removeEmbeddedLabelBoundsBehavior', + 'removeParticipantBehavior', + 'replaceConnectionBehavior', + 'replaceElementBehaviour', + 'resizeBehavior', + 'resizeLaneBehavior', + 'rootElementReferenceBehavior', + 'spaceToolBehavior', + 'subProcessPlaneBehavior', + 'subProcessStartEventBehavior', + 'toggleCollapseConnectionBehaviour', + 'toggleElementCollapseBehaviour', + 'unclaimIdBehavior', + 'updateFlowNodeRefsBehavior', + 'unsetDefaultFlowBehavior' + ], + adaptiveLabelPositioningBehavior: [ 'type', AdaptiveLabelPositioningBehavior ], + appendBehavior: [ 'type', AppendBehavior ], + associationBehavior: [ 'type', AssociationBehavior ], + attachEventBehavior: [ 'type', AttachEventBehavior ], + boundaryEventBehavior: [ 'type', BoundaryEventBehavior ], + createBehavior: [ 'type', CreateBehavior ], + createDataObjectBehavior: [ 'type', CreateDataObjectBehavior ], + createParticipantBehavior: [ 'type', CreateParticipantBehavior ], + dataInputAssociationBehavior: [ 'type', DataInputAssociationBehavior ], + dataStoreBehavior: [ 'type', DataStoreBehavior ], + deleteLaneBehavior: [ 'type', DeleteLaneBehavior ], + detachEventBehavior: [ 'type', DetachEventBehavior ], + dropOnFlowBehavior: [ 'type', DropOnFlowBehavior ], + eventBasedGatewayBehavior: [ 'type', EventBasedGatewayBehavior ], + fixHoverBehavior: [ 'type', FixHoverBehavior ], + groupBehavior: [ 'type', GroupBehavior ], + importDockingFix: [ 'type', ImportDockingFix ], + isHorizontalFix: [ 'type', IsHorizontalFix ], + labelBehavior: [ 'type', LabelBehavior ], + layoutConnectionBehavior: [ 'type', LayoutConnectionBehavior ], + messageFlowBehavior: [ 'type', MessageFlowBehavior ], + modelingFeedback: [ 'type', ModelingFeedback ], + removeElementBehavior: [ 'type', RemoveElementBehavior ], + removeEmbeddedLabelBoundsBehavior: [ 'type', RemoveEmbeddedLabelBoundsBehavior ], + removeParticipantBehavior: [ 'type', RemoveParticipantBehavior ], + replaceConnectionBehavior: [ 'type', ReplaceConnectionBehavior ], + replaceElementBehaviour: [ 'type', ReplaceElementBehaviour ], + resizeBehavior: [ 'type', ResizeBehavior ], + resizeLaneBehavior: [ 'type', ResizeLaneBehavior ], + rootElementReferenceBehavior: [ 'type', RootElementReferenceBehavior ], + spaceToolBehavior: [ 'type', SpaceToolBehavior ], + subProcessPlaneBehavior: [ 'type', SubProcessPlaneBehavior ], + subProcessStartEventBehavior: [ 'type', SubProcessStartEventBehavior ], + toggleCollapseConnectionBehaviour: [ 'type', ToggleCollapseConnectionBehaviour ], + toggleElementCollapseBehaviour : [ 'type', ToggleElementCollapseBehaviour ], + unclaimIdBehavior: [ 'type', UnclaimIdBehavior ], + unsetDefaultFlowBehavior: [ 'type', DeleteSequenceFlowBehavior ], + updateFlowNodeRefsBehavior: [ 'type', UpdateFlowNodeRefsBehavior ] +}; + +/** + * @typedef {import('didi').Injector} Injector + */ + +/** + * A service that provides rules for certain diagram actions. + * + * The default implementation will hook into the {@link CommandStack} + * to perform the actual rule evaluation. Make sure to provide the + * `commandStack` service with this module if you plan to use it. + * + * Together with this implementation you may use the {@link import('./RuleProvider').default} + * to implement your own rule checkers. + * + * This module is ment to be easily replaced, thus the tiny foot print. + * + * @param {Injector} injector + */ +function Rules(injector) { + this._commandStack = injector.get('commandStack', false); +} + +Rules.$inject = [ 'injector' ]; + + +/** + * Returns whether or not a given modeling action can be executed + * in the specified context. + * + * This implementation will respond with allow unless anyone + * objects. + * + * @param {string} action The action to be allowed or disallowed. + * @param {Object} [context] The context for allowing or disallowing the action. + * + * @return {boolean|null} Wether the action is allowed. Returns `null` if the action + * is to be ignored. + */ +Rules.prototype.allowed = function(action, context) { + var allowed = true; + + var commandStack = this._commandStack; + + if (commandStack) { + allowed = commandStack.canExecute(action, context); + } + + // map undefined to true, i.e. no rules + return allowed === undefined ? true : allowed; +}; + +/** + * @type { import('didi').ModuleDeclaration } + */ +var RulesModule$1 = { + __init__: [ 'rules' ], + rules: [ 'type', Rules ] +}; + +/** + * @typedef {import('../../core/EventBus').default} EventBus + */ + +/** + * A basic provider that may be extended to implement modeling rules. + * + * Extensions should implement the init method to actually add their custom + * modeling checks. Checks may be added via the #addRule(action, fn) method. + * + * @class + * + * @param {EventBus} eventBus + */ +function RuleProvider(eventBus) { + CommandInterceptor.call(this, eventBus); + + this.init(); +} + +RuleProvider.$inject = [ 'eventBus' ]; + +e(RuleProvider, CommandInterceptor); + + +/** + * Adds a modeling rule for the given action, implemented through + * a callback function. + * + * The callback receives a modeling specific action context + * to perform its check. It must return `false` to disallow the + * action from happening or `true` to allow the action. Usually returing + * `null` denotes that a particular interaction shall be ignored. + * By returning nothing or `undefined` you pass evaluation to lower + * priority rules. + * + * @example + * + * ```javascript + * ResizableRules.prototype.init = function() { + * + * \/** + * * Return `true`, `false` or nothing to denote + * * _allowed_, _not allowed_ and _continue evaluating_. + * *\/ + * this.addRule('shape.resize', function(context) { + * + * var shape = context.shape; + * + * if (!context.newBounds) { + * // check general resizability + * if (!shape.resizable) { + * return false; + * } + * + * // not returning anything (read: undefined) + * // will continue the evaluation of other rules + * // (with lower priority) + * return; + * } else { + * // element must have minimum size of 10*10 points + * return context.newBounds.width > 10 && context.newBounds.height > 10; + * } + * }); + * }; + * ``` + * + * @param {string|string[]} actions the identifier for the modeling action to check + * @param {number} [priority] the priority at which this rule is being applied + * @param {(any) => any} fn the callback function that performs the actual check + */ +RuleProvider.prototype.addRule = function(actions, priority, fn) { + + var self = this; + + if (typeof actions === 'string') { + actions = [ actions ]; + } + + actions.forEach(function(action) { + + self.canExecute(action, priority, function(context, action, event) { + return fn(context); + }, true); + }); +}; + +/** + * Implement this method to add new rules during provider initialization. + */ +RuleProvider.prototype.init = function() {}; + +/** + * @typedef {import('diagram-js/lib/util/Types').DirectionTRBL} DirectionTRBL + * @typedef {import('diagram-js/lib/util/Types').Point} Point + * @typedef {import('diagram-js/lib/util/Types').Rect} Rect + */ + +/** + * @param {Point} position + * @param {Rect} targetBounds + * + * @return {DirectionTRBL|null} + */ +function getBoundaryAttachment(position, targetBounds) { + + var orientation = getOrientation(position, targetBounds, -15); + + if (orientation !== 'intersect') { + return orientation; + } else { + return null; + } +} + +/** + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * + * @typedef {import('../../model/Types').Connection} Connection + * @typedef {import('../../model/Types').Element} Element + * @typedef {import('../../model/Types').Shape} Shape + * @typedef {import('../../model/Types').ModdleElement} ModdleElement + * + * @typedef {import('diagram-js/lib/util/Types').Point} Point + * @typedef {import('diagram-js/lib/util/Types').Rect} Rect + * + * @typedef { { + * associationDirection?: string; + * type: string; + * } | boolean | null } CanConnectResult + * + * @typedef { { + * id: string; + * type: string; + * } | boolean } CanReplaceResult + */ + +/** + * BPMN-specific modeling rules. + * + * @param {EventBus} eventBus + */ +function BpmnRules(eventBus) { + RuleProvider.call(this, eventBus); +} + +e(BpmnRules, RuleProvider); + +BpmnRules.$inject = [ 'eventBus' ]; + +BpmnRules.prototype.init = function() { + + this.addRule('connection.start', function(context) { + var source = context.source; + + return canStartConnection(source); + }); + + this.addRule('connection.create', function(context) { + var source = context.source, + target = context.target, + hints = context.hints || {}, + targetParent = hints.targetParent, + targetAttach = hints.targetAttach; + + // don't allow incoming connections on + // newly created boundary events + // to boundary events + if (targetAttach) { + return false; + } + + // temporarily set target parent for scoping + // checks to work + if (targetParent) { + target.parent = targetParent; + } + + try { + return canConnect(source, target); + } finally { + + // unset temporary target parent + if (targetParent) { + target.parent = null; + } + } + }); + + this.addRule('connection.reconnect', function(context) { + + var connection = context.connection, + source = context.source, + target = context.target; + + return canConnect(source, target, connection); + }); + + this.addRule('connection.updateWaypoints', function(context) { + return { + type: context.connection.type + }; + }); + + this.addRule('shape.resize', function(context) { + + var shape = context.shape, + newBounds = context.newBounds; + + return canResize(shape, newBounds); + }); + + this.addRule('elements.create', function(context) { + var elements = context.elements, + position = context.position, + target = context.target; + + if (isConnection(target) && !canInsert(elements, target)) { + return false; + } + + return every(elements, function(element) { + if (isConnection(element)) { + return canConnect(element.source, element.target, element); + } + + if (element.host) { + return canAttach(element, element.host, null, position); + } + + return canCreate(element, target, null); + }); + }); + + this.addRule('elements.move', function(context) { + + var target = context.target, + shapes = context.shapes, + position = context.position; + + return canAttach(shapes, target, null, position) || + canReplace(shapes, target, position) || + canMove(shapes, target) || + canInsert(shapes, target); + }); + + this.addRule('shape.create', function(context) { + return canCreate( + context.shape, + context.target, + context.source, + context.position + ); + }); + + this.addRule('shape.attach', function(context) { + + return canAttach( + context.shape, + context.target, + null, + context.position + ); + }); + + this.addRule('element.copy', function(context) { + var element = context.element, + elements = context.elements; + + return canCopy(elements, element); + }); +}; + +BpmnRules.prototype.canConnectMessageFlow = canConnectMessageFlow; + +BpmnRules.prototype.canConnectSequenceFlow = canConnectSequenceFlow; + +BpmnRules.prototype.canConnectDataAssociation = canConnectDataAssociation; + +BpmnRules.prototype.canConnectAssociation = canConnectAssociation; + +BpmnRules.prototype.canMove = canMove; + +BpmnRules.prototype.canAttach = canAttach; + +BpmnRules.prototype.canReplace = canReplace; + +BpmnRules.prototype.canDrop = canDrop; + +BpmnRules.prototype.canInsert = canInsert; + +BpmnRules.prototype.canCreate = canCreate; + +BpmnRules.prototype.canConnect = canConnect; + +BpmnRules.prototype.canResize = canResize; + +BpmnRules.prototype.canCopy = canCopy; + +/** + * Utility functions for rule checking + */ + +/** + * Checks if given element can be used for starting connection. + * + * @param {Element} source + * + * @return {boolean} + */ +function canStartConnection(element) { + if (nonExistingOrLabel(element)) { + return null; + } + + return isAny(element, [ + 'bpmn:FlowNode', + 'bpmn:InteractionNode', + 'bpmn:DataObjectReference', + 'bpmn:DataStoreReference', + 'bpmn:Group', + 'bpmn:TextAnnotation' + ]); +} + +/** + * @param {Element} element + * + * @return {boolean} + */ +function nonExistingOrLabel(element) { + return !element || isLabel(element); +} + +function isSame$1(a, b) { + return a === b; +} + +/** + * @param {Element} element + * + * @return {ModdleElement} + */ +function getOrganizationalParent(element) { + + do { + if (is$2(element, 'bpmn:Process')) { + return getBusinessObject(element); + } + + if (is$2(element, 'bpmn:Participant')) { + return ( + getBusinessObject(element).processRef || + getBusinessObject(element) + ); + } + } while ((element = element.parent)); + +} + +/** + * @param {Element} element + * + * @return {boolean} + */ +function isTextAnnotation(element) { + return is$2(element, 'bpmn:TextAnnotation'); +} + +/** + * @param {Element} element + * + * @return {boolean} + */ +function isGroup(element) { + return is$2(element, 'bpmn:Group') && !element.labelTarget; +} + +/** + * @param {Element} element + * + * @return {boolean} + */ +function isCompensationBoundary(element) { + return is$2(element, 'bpmn:BoundaryEvent') && + hasEventDefinition$1(element, 'bpmn:CompensateEventDefinition'); +} + +/** + * @param {Element} element + * + * @return {boolean} + */ +function isForCompensation(element) { + return getBusinessObject(element).isForCompensation; +} + +/** + * @param {Element} a + * @param {Element} b + * + * @return {boolean} + */ +function isSameOrganization(a, b) { + var parentA = getOrganizationalParent(a), + parentB = getOrganizationalParent(b); + + return parentA === parentB; +} + +/** + * @param {Element} element + * + * @return {boolean} + */ +function isMessageFlowSource(element) { + return ( + is$2(element, 'bpmn:InteractionNode') && + !is$2(element, 'bpmn:BoundaryEvent') && ( + !is$2(element, 'bpmn:Event') || ( + is$2(element, 'bpmn:ThrowEvent') && + hasEventDefinitionOrNone(element, 'bpmn:MessageEventDefinition') + ) + ) + ); +} + +/** + * @param {Element} element + * + * @return {boolean} + */ +function isMessageFlowTarget(element) { + return ( + is$2(element, 'bpmn:InteractionNode') && + !isForCompensation(element) && ( + !is$2(element, 'bpmn:Event') || ( + is$2(element, 'bpmn:CatchEvent') && + hasEventDefinitionOrNone(element, 'bpmn:MessageEventDefinition') + ) + ) && !( + is$2(element, 'bpmn:BoundaryEvent') && + !hasEventDefinition$1(element, 'bpmn:MessageEventDefinition') + ) + ); +} + +/** + * @param {Element} element + * + * @return {ModdleElement} + */ +function getScopeParent(element) { + + var parent = element; + + while ((parent = parent.parent)) { + + if (is$2(parent, 'bpmn:FlowElementsContainer')) { + return getBusinessObject(parent); + } + + if (is$2(parent, 'bpmn:Participant')) { + return getBusinessObject(parent).processRef; + } + } + + return null; +} + +/** + * @param {Element} a + * @param {Element} b + * + * @return {boolean} + */ +function isSameScope(a, b) { + var scopeParentA = getScopeParent(a), + scopeParentB = getScopeParent(b); + + return scopeParentA === scopeParentB; +} + +/** + * @param {Element} element + * @param {string} eventDefinition + * + * @return {boolean} + */ +function hasEventDefinition$1(element, eventDefinition) { + var businessObject = getBusinessObject(element); + + return !!find(businessObject.eventDefinitions || [], function(definition) { + return is$2(definition, eventDefinition); + }); +} + +/** + * @param {Element} element + * @param {string} eventDefinition + * + * @return {boolean} + */ +function hasEventDefinitionOrNone(element, eventDefinition) { + var businessObject = getBusinessObject(element); + + return (businessObject.eventDefinitions || []).every(function(definition) { + return is$2(definition, eventDefinition); + }); +} + +/** + * @param {Element} element + * + * @return {boolean} + */ +function isSequenceFlowSource(element) { + return ( + is$2(element, 'bpmn:FlowNode') && + !is$2(element, 'bpmn:EndEvent') && + !isEventSubProcess(element) && + !(is$2(element, 'bpmn:IntermediateThrowEvent') && + hasEventDefinition$1(element, 'bpmn:LinkEventDefinition') + ) && + !isCompensationBoundary(element) && + !isForCompensation(element) + ); +} + +/** + * @param {Element} element + * + * @return {boolean} + */ +function isSequenceFlowTarget(element) { + return ( + is$2(element, 'bpmn:FlowNode') && + !is$2(element, 'bpmn:StartEvent') && + !is$2(element, 'bpmn:BoundaryEvent') && + !isEventSubProcess(element) && + !(is$2(element, 'bpmn:IntermediateCatchEvent') && + hasEventDefinition$1(element, 'bpmn:LinkEventDefinition') + ) && + !isForCompensation(element) + ); +} + +/** + * @param {Element} element + * + * @return {boolean} + */ +function isEventBasedTarget(element) { + return ( + is$2(element, 'bpmn:ReceiveTask') || ( + is$2(element, 'bpmn:IntermediateCatchEvent') && ( + hasEventDefinition$1(element, 'bpmn:MessageEventDefinition') || + hasEventDefinition$1(element, 'bpmn:TimerEventDefinition') || + hasEventDefinition$1(element, 'bpmn:ConditionalEventDefinition') || + hasEventDefinition$1(element, 'bpmn:SignalEventDefinition') + ) + ) + ); +} + +/** + * @param {Element} element + * + * @return {Shape[]} + */ +function getParents(element) { + + var parents = []; + + while (element) { + element = element.parent; + + if (element) { + parents.push(element); + } + } + + return parents; +} + +/** + * @param {Shape} possibleParent + * @param {Element} element + * + * @return {boolean} + */ +function isParent(possibleParent, element) { + var allParents = getParents(element); + + return allParents.indexOf(possibleParent) !== -1; +} + +/** + * @param {Element} source + * @param {Element} target + * @param {Connection} connection + * + * @return {CanConnectResult} + */ +function canConnect(source, target, connection) { + + if (nonExistingOrLabel(source) || nonExistingOrLabel(target)) { + return null; + } + + if (!is$2(connection, 'bpmn:DataAssociation')) { + + if (canConnectMessageFlow(source, target)) { + return { type: 'bpmn:MessageFlow' }; + } + + if (canConnectSequenceFlow(source, target)) { + return { type: 'bpmn:SequenceFlow' }; + } + } + + var connectDataAssociation = canConnectDataAssociation(source, target); + + if (connectDataAssociation) { + return connectDataAssociation; + } + + if (isCompensationBoundary(source) && isForCompensation(target)) { + return { + type: 'bpmn:Association', + associationDirection: 'One' + }; + } + + if (canConnectAssociation(source, target)) { + + return { + type: 'bpmn:Association' + }; + } + + return false; +} + +/** + * Can an element be dropped into the target element. + * + * @param {Element} element + * @param {Shape} target + * + * @return {boolean} + */ +function canDrop(element, target) { + + // can move labels and groups everywhere + if (isLabel(element) || isGroup(element)) { + return true; + } + + + // disallow to create elements on collapsed pools + if (is$2(target, 'bpmn:Participant') && !isExpanded(target)) { + return false; + } + + // allow to create new participants on + // existing collaboration and process diagrams + if (is$2(element, 'bpmn:Participant')) { + return is$2(target, 'bpmn:Process') || is$2(target, 'bpmn:Collaboration'); + } + + // allow moving DataInput / DataOutput within its original container only + if (isAny(element, [ 'bpmn:DataInput', 'bpmn:DataOutput' ])) { + + if (element.parent) { + return target === element.parent; + } + } + + // allow creating lanes on participants and other lanes only + if (is$2(element, 'bpmn:Lane')) { + return is$2(target, 'bpmn:Participant') || is$2(target, 'bpmn:Lane'); + } + + // disallow dropping boundary events which cannot replace with intermediate event + if (is$2(element, 'bpmn:BoundaryEvent') && !isDroppableBoundaryEvent(element)) { + return false; + } + + // drop flow elements onto flow element containers + // and participants + if (is$2(element, 'bpmn:FlowElement') && !is$2(element, 'bpmn:DataStoreReference')) { + if (is$2(target, 'bpmn:FlowElementsContainer')) { + return isExpanded(target); + } + + return isAny(target, [ 'bpmn:Participant', 'bpmn:Lane' ]); + } + + // disallow dropping data store reference if there is no process to append to + if (is$2(element, 'bpmn:DataStoreReference') && is$2(target, 'bpmn:Collaboration')) { + return some(getBusinessObject(target).get('participants'), function(participant) { + return !!participant.get('processRef'); + }); + } + + // account for the fact that data associations are always + // rendered and moved to top (Process or Collaboration level) + // + // artifacts may be placed wherever, too + if (isAny(element, [ 'bpmn:Artifact', 'bpmn:DataAssociation', 'bpmn:DataStoreReference' ])) { + return isAny(target, [ + 'bpmn:Collaboration', + 'bpmn:Lane', + 'bpmn:Participant', + 'bpmn:Process', + 'bpmn:SubProcess' ]); + } + + if (is$2(element, 'bpmn:MessageFlow')) { + return is$2(target, 'bpmn:Collaboration') + || element.source.parent == target + || element.target.parent == target; + } + + return false; +} + +/** + * @param {Shape} event + * + * @return {boolean} + */ +function isDroppableBoundaryEvent(event) { + return getBusinessObject(event).cancelActivity && ( + hasNoEventDefinition(event) || hasCommonBoundaryIntermediateEventDefinition(event) + ); +} + +/** + * @param {Element} element + * + * @return {boolean} + */ +function isBoundaryEvent(element) { + return !isLabel(element) && is$2(element, 'bpmn:BoundaryEvent'); +} + +/** + * @param {Element} element + * + * @return {boolean} + */ +function isLane(element) { + return is$2(element, 'bpmn:Lane'); +} + +/** + * `bpmn:IntermediateThrowEvents` are treated as boundary events during create. + * + * @param {Element} element + * + * @return {boolean} + */ +function isBoundaryCandidate(element) { + if (isBoundaryEvent(element)) { + return true; + } + + if (is$2(element, 'bpmn:IntermediateThrowEvent') && hasNoEventDefinition(element)) { + return true; + } + + return ( + is$2(element, 'bpmn:IntermediateCatchEvent') && + hasCommonBoundaryIntermediateEventDefinition(element) + ); +} + +/** + * @param {Element} element + * + * @return {boolean} + */ +function hasNoEventDefinition(element) { + var businessObject = getBusinessObject(element); + + return businessObject && !(businessObject.eventDefinitions && businessObject.eventDefinitions.length); +} + +/** + * @param {Element} element + * + * @return {boolean} + */ +function hasCommonBoundaryIntermediateEventDefinition(element) { + return hasOneOfEventDefinitions(element, [ + 'bpmn:MessageEventDefinition', + 'bpmn:TimerEventDefinition', + 'bpmn:SignalEventDefinition', + 'bpmn:ConditionalEventDefinition' + ]); +} + +/** + * @param {Element} element + * @param {string[]} eventDefinitions + * + * @return {boolean} + */ +function hasOneOfEventDefinitions(element, eventDefinitions) { + return eventDefinitions.some(function(definition) { + return hasEventDefinition$1(element, definition); + }); +} + +/** + * @param {Element} element + * + * @return {boolean} + */ +function isReceiveTaskAfterEventBasedGateway(element) { + return ( + is$2(element, 'bpmn:ReceiveTask') && + find(element.incoming, function(incoming) { + return is$2(incoming.source, 'bpmn:EventBasedGateway'); + }) + ); +} + +/** + * TODO(philippfromme): remove `source` parameter + * + * @param {Element[]} elements + * @param {Shape} target + * @param {Element} source + * @param {Point} [position] + * + * @return {boolean | 'attach'} + */ +function canAttach(elements, target, source, position) { + + if (!Array.isArray(elements)) { + elements = [ elements ]; + } + + // only (re-)attach one element at a time + if (elements.length !== 1) { + return false; + } + + var element = elements[0]; + + // do not attach labels + if (isLabel(element)) { + return false; + } + + // only handle boundary events + if (!isBoundaryCandidate(element)) { + return false; + } + + // disallow drop on event sub processes + if (isEventSubProcess(target)) { + return false; + } + + // only allow drop on non compensation activities + if (!is$2(target, 'bpmn:Activity') || isForCompensation(target)) { + return false; + } + + // only attach to subprocess border + if (position && !getBoundaryAttachment(position, target)) { + return false; + } + + // do not attach on receive tasks after event based gateways + if (isReceiveTaskAfterEventBasedGateway(target)) { + return false; + } + + return 'attach'; +} + +/** + * Check whether the given elements can be replaced. Return all elements which + * can be replaced. + * + * @example + * + * ```javascript + * [{ + * id: 'IntermediateEvent_1', + * type: 'bpmn:StartEvent' + * }, + * { + * id: 'Task_1', + * type: 'bpmn:ServiceTask' + * }] + * ``` + * + * @param {Element[]} elements + * @param {Shape} [target] + * @param {Point} [position] + * + * @return {CanReplaceResult} + */ +function canReplace(elements, target, position) { + + if (!target) { + return false; + } + + var canExecute = { + replacements: [] + }; + + forEach$2(elements, function(element) { + + if (!isEventSubProcess(target)) { + + if (is$2(element, 'bpmn:StartEvent') && + element.type !== 'label' && + canDrop(element, target)) { + + // replace a non-interrupting start event by a blank interrupting start event + // when the target is not an event sub process + if (!isInterrupting(element)) { + canExecute.replacements.push({ + oldElementId: element.id, + newElementType: 'bpmn:StartEvent' + }); + } + + // replace an error/escalation/compensate start event by a blank interrupting start event + // when the target is not an event sub process + if (hasErrorEventDefinition(element) || + hasEscalationEventDefinition(element) || + hasCompensateEventDefinition(element)) { + canExecute.replacements.push({ + oldElementId: element.id, + newElementType: 'bpmn:StartEvent' + }); + } + + // replace a typed start event by a blank interrupting start event + // when the target is a sub process but not an event sub process + if (hasOneOfEventDefinitions(element, + [ + 'bpmn:MessageEventDefinition', + 'bpmn:TimerEventDefinition', + 'bpmn:SignalEventDefinition', + 'bpmn:ConditionalEventDefinition' + ]) && + is$2(target, 'bpmn:SubProcess')) { + canExecute.replacements.push({ + oldElementId: element.id, + newElementType: 'bpmn:StartEvent' + }); + } + } + } + + if (!is$2(target, 'bpmn:Transaction')) { + if (hasEventDefinition$1(element, 'bpmn:CancelEventDefinition') && + element.type !== 'label') { + + if (is$2(element, 'bpmn:EndEvent') && canDrop(element, target)) { + canExecute.replacements.push({ + oldElementId: element.id, + newElementType: 'bpmn:EndEvent' + }); + } + + if (is$2(element, 'bpmn:BoundaryEvent') && canAttach(element, target, null, position)) { + canExecute.replacements.push({ + oldElementId: element.id, + newElementType: 'bpmn:BoundaryEvent' + }); + } + } + } + }); + + return canExecute.replacements.length ? canExecute : false; +} + +/** + * @param {Element[]} elements + * @param {Shape} target + * + * @return {boolean} + */ +function canMove(elements, target) { + + // do not move selection containing lanes + if (some(elements, isLane)) { + return false; + } + + // allow default move check to start move operation + if (!target) { + return true; + } + + return elements.every(function(element) { + return canDrop(element, target); + }); +} + +/** + * @param {Shape} shape + * @param {Shape} target + * @param {Element} source + * @param {Point} position + * + * @return {boolean} + */ +function canCreate(shape, target, source, position) { + + if (!target) { + return false; + } + + if (isLabel(shape) || isGroup(shape)) { + return true; + } + + if (isSame$1(source, target)) { + return false; + } + + // ensure we do not drop the element + // into source + if (source && isParent(source, target)) { + return false; + } + + return canDrop(shape, target) || canInsert(shape, target); +} + +/** + * @param {Shape} shape + * @param {Rect} newBounds + * + * @return {boolean} + */ +function canResize(shape, newBounds) { + if (is$2(shape, 'bpmn:SubProcess')) { + return ( + isExpanded(shape) && ( + !newBounds || (newBounds.width >= 100 && newBounds.height >= 80) + ) + ); + } + + if (is$2(shape, 'bpmn:Lane')) { + return !newBounds || (newBounds.width >= 130 && newBounds.height >= 60); + } + + if (is$2(shape, 'bpmn:Participant')) { + return !newBounds || (newBounds.width >= 250 && newBounds.height >= 50); + } + + if (isTextAnnotation(shape)) { + return true; + } + + if (isGroup(shape)) { + return true; + } + + return false; +} + +/** + * Check whether one of of the elements to be connected is a text annotation. + * + * @param {Element} source + * @param {Element} target + * + * @return {boolean} + */ +function isOneTextAnnotation(source, target) { + + var sourceTextAnnotation = isTextAnnotation(source), + targetTextAnnotation = isTextAnnotation(target); + + return ( + (sourceTextAnnotation || targetTextAnnotation) && + (sourceTextAnnotation !== targetTextAnnotation) + ); +} + +/** + * @param {Element} source + * @param {Element} target + * + * @return {CanConnectResult} + */ +function canConnectAssociation(source, target) { + + // compensation boundary events are exception + if (isCompensationBoundary(source) && isForCompensation(target)) { + return true; + } + + // don't connect parent <-> child + if (isParent(target, source) || isParent(source, target)) { + return false; + } + + // allow connection of associations between and + if (isOneTextAnnotation(source, target)) { + return true; + } + + // can connect associations where we can connect + // data associations, too (!) + return !!canConnectDataAssociation(source, target); +} + +/** + * @param {Element} source + * @param {Element} target + * + * @return {boolean} + */ +function canConnectMessageFlow(source, target) { + + // during connect user might move mouse out of canvas + // https://github.com/bpmn-io/bpmn-js/issues/1033 + if (getRootElement(source) && !getRootElement(target)) { + return false; + } + + return ( + isMessageFlowSource(source) && + isMessageFlowTarget(target) && + !isSameOrganization(source, target) + ); +} + +/** + * @param {Element} source + * @param {Element} target + * + * @return {boolean} + */ +function canConnectSequenceFlow(source, target) { + return isSequenceFlowSource(source) && + isSequenceFlowTarget(target) && + isSameScope(source, target) && + !(is$2(source, 'bpmn:EventBasedGateway') && !isEventBasedTarget(target)); +} + +/** + * @param {Element} source + * @param {Element} target + * + * @return {CanConnectResult} + */ +function canConnectDataAssociation(source, target) { + + if (isAny(source, [ 'bpmn:DataObjectReference', 'bpmn:DataStoreReference' ]) && + isAny(target, [ 'bpmn:Activity', 'bpmn:ThrowEvent' ])) { + return { type: 'bpmn:DataInputAssociation' }; + } + + if (isAny(target, [ 'bpmn:DataObjectReference', 'bpmn:DataStoreReference' ]) && + isAny(source, [ 'bpmn:Activity', 'bpmn:CatchEvent' ])) { + return { type: 'bpmn:DataOutputAssociation' }; + } + + return false; +} + +/** + * @param {Shape} shape + * @param {Connection} connection + * @param {Point} position + * + * @return {boolean} + */ +function canInsert(shape, connection, position) { + if (!connection) { + return false; + } + + if (Array.isArray(shape)) { + if (shape.length !== 1) { + return false; + } + + shape = shape[ 0 ]; + } + + if (connection.source === shape || + connection.target === shape) { + return false; + } + + // return true if shape can be inserted into connection parent + return ( + isAny(connection, [ 'bpmn:SequenceFlow', 'bpmn:MessageFlow' ]) && + !isLabel(connection) && + is$2(shape, 'bpmn:FlowNode') && + !is$2(shape, 'bpmn:BoundaryEvent') && + canDrop(shape, connection.parent)); +} + +/** + * @param {Element[]} elements + * @param {Element} element + * + * @return {boolean} + */ +function includes$4(elements, element) { + return (elements && element) && elements.indexOf(element) !== -1; +} + +/** + * @param {Element[]} elements + * @param {Element} element + * + * @return {boolean} + */ +function canCopy(elements, element) { + if (isLabel(element)) { + return true; + } + + if (is$2(element, 'bpmn:Lane') && !includes$4(elements, element.parent)) { + return false; + } + + return true; +} + +/** + * @param {Element} element + * + * @return {Element|null} + */ +function getRootElement(element) { + return getParent$2(element, 'bpmn:Process') || getParent$2(element, 'bpmn:Collaboration'); +} + +var RulesModule = { + __depends__: [ + RulesModule$1 + ], + __init__: [ 'bpmnRules' ], + bpmnRules: [ 'type', BpmnRules ] +}; + +/** + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * @typedef {import('diagram-js/lib/core/Canvas').default} Canvas + */ + +var HIGH_PRIORITY$9 = 2000; + +/** + * @param {EventBus} eventBus + * @param {Canvas} canvas + */ +function BpmnDiOrdering(eventBus, canvas) { + + eventBus.on('saveXML.start', HIGH_PRIORITY$9, orderDi); + + function orderDi() { + var rootElements = canvas.getRootElements(); + + forEach$2(rootElements, function(root) { + var rootDi = getDi(root), + elements, + diElements; + + elements = selfAndAllChildren([ root ], false); + + // only bpmndi:Shape and bpmndi:Edge can be direct children of bpmndi:Plane + elements = filter(elements, function(element) { + return element !== root && !element.labelTarget; + }); + + diElements = map$2(elements, getDi); + + rootDi.set('planeElement', diElements); + }); + } +} + +BpmnDiOrdering.$inject = [ 'eventBus', 'canvas' ]; + +var DiOrderingModule = { + __init__: [ + 'bpmnDiOrdering' + ], + bpmnDiOrdering: [ 'type', BpmnDiOrdering ] +}; + +/** + * @typedef { { + * [key: string]: string; + * } } TranslateReplacements + */ + +/** + * A simple translation stub to be used for multi-language support + * in diagrams. Can be easily replaced with a more sophisticated + * solution. + * + * @example + * + * ```javascript + * // use it inside any diagram component by injecting `translate`. + * + * function MyService(translate) { + * alert(translate('HELLO {you}', { you: 'You!' })); + * } + * ``` + * + * @param {string} template to interpolate + * @param {TranslateReplacements} [replacements] a map with substitutes + * + * @return {string} the translated string + */ +function translate$1(template, replacements) { + + replacements = replacements || {}; + + return template.replace(/{([^}]+)}/g, function(_, key) { + return replacements[key] || '{' + key + '}'; + }); +} + +/** + * @type { import('didi').ModuleDeclaration } + */ +var TranslateModule = { + translate: [ 'value', translate$1 ] +}; + +/** + * @typedef {import('../../core/Types').ElementLike} Element + * @typedef {import('../../core/Types').ShapeLike} Shape + * + * @typedef {import('../../core/EventBus').default} EventBus + */ + +/** + * An abstract provider that allows modelers to implement a custom + * ordering of diagram elements on the canvas. + * + * It makes sure that the order is always preserved during element + * creation and move operations. + * + * In order to use this behavior, inherit from it and override + * the method {@link OrderingProvider#getOrdering}. + * + * @example + * + * ```javascript + * function CustomOrderingProvider(eventBus) { + * OrderingProvider.call(this, eventBus); + * + * this.getOrdering = function(element, newParent) { + * // always insert elements at the front + * // when moving + * return { + * index: 0, + * parent: newParent + * }; + * }; + * } + * ``` + * + * @param {EventBus} eventBus + */ +function OrderingProvider(eventBus) { + + CommandInterceptor.call(this, eventBus); + + + var self = this; + + this.preExecute([ 'shape.create', 'connection.create' ], function(event) { + + var context = event.context, + element = context.shape || context.connection, + parent = context.parent; + + var ordering = self.getOrdering(element, parent); + + if (ordering) { + + if (ordering.parent !== undefined) { + context.parent = ordering.parent; + } + + context.parentIndex = ordering.index; + } + }); + + this.preExecute([ 'shape.move', 'connection.move' ], function(event) { + + var context = event.context, + element = context.shape || context.connection, + parent = context.newParent || element.parent; + + var ordering = self.getOrdering(element, parent); + + if (ordering) { + + if (ordering.parent !== undefined) { + context.newParent = ordering.parent; + } + + context.newParentIndex = ordering.index; + } + }); +} + +/** + * Return a custom ordering of the element, both in terms + * of parent element and index in the new parent. + * + * Implementors of this method must return an object with + * `parent` _and_ `index` in it. + * + * @param {Element} element + * @param {Shape} newParent + * + * @return {Object} ordering descriptor + */ +OrderingProvider.prototype.getOrdering = function(element, newParent) { + return null; +}; + +e(OrderingProvider, CommandInterceptor); + +/** + * @typedef {import('diagram-js/lib/core/Canvas').default} Canvas + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * @typedef {import('diagram-js/i18n/translate/translate').default} Translate + */ + +/** + * A BPMN-specific ordering provider. + * + * @param {EventBus} eventBus + * @param {Canvas} canvas + * @param {Translate} translate + */ +function BpmnOrderingProvider(eventBus, canvas, translate) { + + OrderingProvider.call(this, eventBus); + + var orders = [ + { type: 'bpmn:SubProcess', order: { level: 6 } }, + + // handle SequenceFlow(s) like message flows and render them always on top + { + type: 'bpmn:SequenceFlow', + order: { + level: 9, + containers: [ + 'bpmn:Participant', + 'bpmn:FlowElementsContainer' + ] + } + }, + + // handle DataAssociation(s) like message flows and render them always on top + { + type: 'bpmn:DataAssociation', + order: { + level: 9, + containers: [ + 'bpmn:Collaboration', + 'bpmn:FlowElementsContainer' + ] + } + }, + { + type: 'bpmn:MessageFlow', order: { + level: 9, + containers: [ 'bpmn:Collaboration' ] + } + }, + { + type: 'bpmn:Association', + order: { + level: 6, + containers: [ + 'bpmn:Participant', + 'bpmn:FlowElementsContainer', + 'bpmn:Collaboration' + ] + } + }, + { type: 'bpmn:BoundaryEvent', order: { level: 8 } }, + { + type: 'bpmn:Group', + order: { + level: 10, + containers: [ + 'bpmn:Collaboration', + 'bpmn:FlowElementsContainer' + ] + } + }, + { type: 'bpmn:FlowElement', order: { level: 5 } }, + { type: 'bpmn:Participant', order: { level: -2 } }, + { type: 'bpmn:Lane', order: { level: -1 } } + ]; + + function computeOrder(element) { + if (element.labelTarget) { + return { level: 10 }; + } + + var entry = find(orders, function(o) { + return isAny(element, [ o.type ]); + }); + + return entry && entry.order || { level: 1 }; + } + + function getOrder(element) { + + var order = element.order; + + if (!order) { + element.order = order = computeOrder(element); + } + + if (!order) { + throw new Error('no order for <' + element.id + '>'); + } + + return order; + } + + function findActualParent(element, newParent, containers) { + + var actualParent = newParent; + + while (actualParent) { + + if (isAny(actualParent, containers)) { + break; + } + + actualParent = actualParent.parent; + } + + if (!actualParent) { + throw new Error('no parent for <' + element.id + '> in <' + (newParent && newParent.id) + '>'); + } + + return actualParent; + } + + this.getOrdering = function(element, newParent) { + + // render labels always on top + if (element.labelTarget) { + return { + parent: canvas.findRoot(newParent) || canvas.getRootElement(), + index: -1 + }; + } + + var elementOrder = getOrder(element); + + if (elementOrder.containers) { + newParent = findActualParent(element, newParent, elementOrder.containers); + } + + var currentIndex = newParent.children.indexOf(element); + + var insertIndex = findIndex$1(newParent.children, function(child) { + + // do not compare with labels, they are created + // in the wrong order (right after elements) during import and + // mess up the positioning. + if (!element.labelTarget && child.labelTarget) { + return false; + } + + return elementOrder.level < getOrder(child).level; + }); + + + // if the element is already in the child list at + // a smaller index, we need to adjust the insert index. + // this takes into account that the element is being removed + // before being re-inserted + if (insertIndex !== -1) { + if (currentIndex !== -1 && currentIndex < insertIndex) { + insertIndex -= 1; + } + } + + return { + index: insertIndex, + parent: newParent + }; + }; +} + +BpmnOrderingProvider.$inject = [ 'eventBus', 'canvas', 'translate' ]; + +e(BpmnOrderingProvider, OrderingProvider); + +var OrderingModule = { + __depends__: [ + TranslateModule + ], + __init__: [ 'bpmnOrderingProvider' ], + bpmnOrderingProvider: [ 'type', BpmnOrderingProvider ] +}; + +/** + * A clip board stub + */ +function Clipboard() {} + + +Clipboard.prototype.get = function() { + return this._data; +}; + +Clipboard.prototype.set = function(data) { + this._data = data; +}; + +Clipboard.prototype.clear = function() { + var data = this._data; + + delete this._data; + + return data; +}; + +Clipboard.prototype.isEmpty = function() { + return !this._data; +}; + +/** + * @type { import('didi').ModuleDeclaration } + */ +var ClipboardModule = { + clipboard: [ 'type', Clipboard ] +}; + +function _mergeNamespaces(n, m) { + m.forEach(function (e) { + e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) { + if (k !== 'default' && !(k in n)) { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + }); + return Object.freeze(n); +} + +/** + * Flatten array, one level deep. + * + * @param {Array} arr + * + * @return {Array} + */ + +const nativeToString$1 = Object.prototype.toString; +const nativeHasOwnProperty$1 = Object.prototype.hasOwnProperty; + +function isUndefined$2(obj) { + return obj === undefined; +} + +function isArray$2(obj) { + return nativeToString$1.call(obj) === '[object Array]'; +} + +/** + * Return true, if target owns a property with the given key. + * + * @param {Object} target + * @param {String} key + * + * @return {Boolean} + */ +function has$1(target, key) { + return nativeHasOwnProperty$1.call(target, key); +} + + +/** + * Iterate over collection; returning something + * (non-undefined) will stop iteration. + * + * @param {Array|Object} collection + * @param {Function} iterator + * + * @return {Object} return result that stopped the iteration + */ +function forEach$1(collection, iterator) { + + let val, + result; + + if (isUndefined$2(collection)) { + return; + } + + const convertKey = isArray$2(collection) ? toNum$1 : identity$1; + + for (let key in collection) { + + if (has$1(collection, key)) { + val = collection[key]; + + result = iterator(val, convertKey(key)); + + if (result === false) { + return val; + } + } + } +} + + +function identity$1(arg) { + return arg; +} + +function toNum$1(arg) { + return Number(arg); +} + +/** + * Assigns style attributes in a style-src compliant way. + * + * @param {Element} element + * @param {...Object} styleSources + * + * @return {Element} the element + */ +function assign$2(element, ...styleSources) { + const target = element.style; + + forEach$1(styleSources, function(style) { + if (!style) { + return; + } + + forEach$1(style, function(value, key) { + target[key] = value; + }); + }); + + return element; +} + +/** + * Set attribute `name` to `val`, or get attr `name`. + * + * @param {Element} el + * @param {String} name + * @param {String} [val] + * @api public + */ +function attr$2(el, name, val) { + + // get + if (arguments.length == 2) { + return el.getAttribute(name); + } + + // remove + if (val === null) { + return el.removeAttribute(name); + } + + // set + el.setAttribute(name, val); + + return el; +} + +/** + * Taken from https://github.com/component/classes + * + * Without the component bits. + */ + +/** + * toString reference. + */ + +const toString$1 = Object.prototype.toString; + +/** + * Wrap `el` in a `ClassList`. + * + * @param {Element} el + * @return {ClassList} + * @api public + */ + +function classes$1(el) { + return new ClassList$1(el); +} + +/** + * Initialize a new ClassList for `el`. + * + * @param {Element} el + * @api private + */ + +function ClassList$1(el) { + if (!el || !el.nodeType) { + throw new Error('A DOM element reference is required'); + } + this.el = el; + this.list = el.classList; +} + +/** + * Add class `name` if not already present. + * + * @param {String} name + * @return {ClassList} + * @api public + */ + +ClassList$1.prototype.add = function(name) { + this.list.add(name); + return this; +}; + +/** + * Remove class `name` when present, or + * pass a regular expression to remove + * any which match. + * + * @param {String|RegExp} name + * @return {ClassList} + * @api public + */ + +ClassList$1.prototype.remove = function(name) { + if ('[object RegExp]' == toString$1.call(name)) { + return this.removeMatching(name); + } + + this.list.remove(name); + return this; +}; + +/** + * Remove all classes matching `re`. + * + * @param {RegExp} re + * @return {ClassList} + * @api private + */ + +ClassList$1.prototype.removeMatching = function(re) { + const arr = this.array(); + for (let i = 0; i < arr.length; i++) { + if (re.test(arr[i])) { + this.remove(arr[i]); + } + } + return this; +}; + +/** + * Toggle class `name`, can force state via `force`. + * + * For browsers that support classList, but do not support `force` yet, + * the mistake will be detected and corrected. + * + * @param {String} name + * @param {Boolean} force + * @return {ClassList} + * @api public + */ + +ClassList$1.prototype.toggle = function(name, force) { + if ('undefined' !== typeof force) { + if (force !== this.list.toggle(name, force)) { + this.list.toggle(name); // toggle again to correct + } + } else { + this.list.toggle(name); + } + return this; +}; + +/** + * Return an array of classes. + * + * @return {Array} + * @api public + */ + +ClassList$1.prototype.array = function() { + return Array.from(this.list); +}; + +/** + * Check if class `name` is present. + * + * @param {String} name + * @return {ClassList} + * @api public + */ + +ClassList$1.prototype.has = +ClassList$1.prototype.contains = function(name) { + return this.list.contains(name); +}; + +/** + * Remove all children from the given element. + */ +function clear$1(el) { + + var c; + + while (el.childNodes.length) { + c = el.childNodes[0]; + el.removeChild(c); + } + + return el; +} + +/** + * @param { HTMLElement } element + * @param { String } selector + * + * @return { boolean } + */ +function matches(element, selector) { + return element && typeof element.matches === 'function' && element.matches(selector); +} + +/** + * Closest + * + * @param {Element} el + * @param {String} selector + * @param {Boolean} checkYourSelf (optional) + */ +function closest(element, selector, checkYourSelf) { + var currentElem = checkYourSelf ? element : element.parentNode; + + while (currentElem && currentElem.nodeType !== document.DOCUMENT_NODE && + currentElem.nodeType !== document.DOCUMENT_FRAGMENT_NODE) { + + if (matches(currentElem, selector)) { + return currentElem; + } + + currentElem = currentElem.parentNode; + } + + return matches(currentElem, selector) ? currentElem : null; +} + +var componentEvent = {}; + +var bind$1, unbind$1, prefix$7; + +function detect () { + bind$1 = window.addEventListener ? 'addEventListener' : 'attachEvent'; + unbind$1 = window.removeEventListener ? 'removeEventListener' : 'detachEvent'; + prefix$7 = bind$1 !== 'addEventListener' ? 'on' : ''; +} + +/** + * Bind `el` event `type` to `fn`. + * + * @param {Element} el + * @param {String} type + * @param {Function} fn + * @param {Boolean} capture + * @return {Function} + * @api public + */ + +var bind_1 = componentEvent.bind = function(el, type, fn, capture){ + if (!bind$1) detect(); + el[bind$1](prefix$7 + type, fn, capture || false); + return fn; +}; + +/** + * Unbind `el` event `type`'s callback `fn`. + * + * @param {Element} el + * @param {String} type + * @param {Function} fn + * @param {Boolean} capture + * @return {Function} + * @api public + */ + +var unbind_1 = componentEvent.unbind = function(el, type, fn, capture){ + if (!unbind$1) detect(); + el[unbind$1](prefix$7 + type, fn, capture || false); + return fn; +}; + +var event = /*#__PURE__*/_mergeNamespaces({ + __proto__: null, + bind: bind_1, + unbind: unbind_1, + 'default': componentEvent +}, [componentEvent]); + +/** + * Module dependencies. + */ + +/** + * Delegate event `type` to `selector` + * and invoke `fn(e)`. A callback function + * is returned which may be passed to `.unbind()`. + * + * @param {Element} el + * @param {String} selector + * @param {String} type + * @param {Function} fn + * @param {Boolean} capture + * @return {Function} + * @api public + */ + +// Some events don't bubble, so we want to bind to the capture phase instead +// when delegating. +var forceCaptureEvents = [ 'focus', 'blur' ]; + +function bind(el, selector, type, fn, capture) { + if (forceCaptureEvents.indexOf(type) !== -1) { + capture = true; + } + + return event.bind(el, type, function(e) { + var target = e.target || e.srcElement; + e.delegateTarget = closest(target, selector, true); + if (e.delegateTarget) { + fn.call(el, e); + } + }, capture); +} + +/** + * Unbind event `type`'s callback `fn`. + * + * @param {Element} el + * @param {String} type + * @param {Function} fn + * @param {Boolean} capture + * @api public + */ +function unbind(el, type, fn, capture) { + if (forceCaptureEvents.indexOf(type) !== -1) { + capture = true; + } + + return event.unbind(el, type, fn, capture); +} + +var delegate = { + bind, + unbind +}; + +/** + * Expose `parse`. + */ + +var domify = parse$3; + +/** + * Tests for browser support. + */ + +var innerHTMLBug = false; +var bugTestDiv; +if (typeof document !== 'undefined') { + bugTestDiv = document.createElement('div'); + // Setup + bugTestDiv.innerHTML = '
a'; + // Make sure that link elements get serialized correctly by innerHTML + // This requires a wrapper element in IE + innerHTMLBug = !bugTestDiv.getElementsByTagName('link').length; + bugTestDiv = undefined; +} + +/** + * Wrap map from jquery. + */ + +var map$1 = { + legend: [1, '
', '
'], + tr: [2, '', '
'], + col: [2, '', '
'], + // for script/link/style tags to work in IE6-8, you have to wrap + // in a div with a non-whitespace character in front, ha! + _default: innerHTMLBug ? [1, 'X
', '
'] : [0, '', ''] +}; + +map$1.td = +map$1.th = [3, '', '
']; + +map$1.option = +map$1.optgroup = [1, '']; + +map$1.thead = +map$1.tbody = +map$1.colgroup = +map$1.caption = +map$1.tfoot = [1, '', '
']; + +map$1.polyline = +map$1.ellipse = +map$1.polygon = +map$1.circle = +map$1.text = +map$1.line = +map$1.path = +map$1.rect = +map$1.g = [1, '','']; + +/** + * Parse `html` and return a DOM Node instance, which could be a TextNode, + * HTML DOM Node of some kind (
for example), or a DocumentFragment + * instance, depending on the contents of the `html` string. + * + * @param {String} html - HTML string to "domify" + * @param {Document} doc - The `document` instance to create the Node for + * @return {DOMNode} the TextNode, DOM Node, or DocumentFragment instance + * @api private + */ + +function parse$3(html, doc) { + if ('string' != typeof html) throw new TypeError('String expected'); + + // default to the global `document` object + if (!doc) doc = document; + + // tag name + var m = /<([\w:]+)/.exec(html); + if (!m) return doc.createTextNode(html); + + html = html.replace(/^\s+|\s+$/g, ''); // Remove leading/trailing whitespace + + var tag = m[1]; + + // body support + if (tag == 'body') { + var el = doc.createElement('html'); + el.innerHTML = html; + return el.removeChild(el.lastChild); + } + + // wrap map + var wrap = Object.prototype.hasOwnProperty.call(map$1, tag) ? map$1[tag] : map$1._default; + var depth = wrap[0]; + var prefix = wrap[1]; + var suffix = wrap[2]; + var el = doc.createElement('div'); + el.innerHTML = prefix + html + suffix; + while (depth--) el = el.lastChild; + + // one element + if (el.firstChild == el.lastChild) { + return el.removeChild(el.firstChild); + } + + // several elements + var fragment = doc.createDocumentFragment(); + while (el.firstChild) { + fragment.appendChild(el.removeChild(el.firstChild)); + } + + return fragment; +} + +var domify$1 = domify; + +function query(selector, el) { + el = el || document; + + return el.querySelector(selector); +} + +function all(selector, el) { + el = el || document; + + return el.querySelectorAll(selector); +} + +function remove$1(el) { + el.parentNode && el.parentNode.removeChild(el); +} + +/** + * @typedef {import('didi').Injector} Injector + * + * @typedef {import('../../core/ElementRegistry').default} ElementRegistry + * @typedef {import('../../core/EventBus').default} EventBus + */ + +var HIGH_PRIORITY$8 = 1500; + + +/** + * Browsers may swallow certain events (hover, out ...) if users are to + * fast with the mouse. + * + * @see http://stackoverflow.com/questions/7448468/why-cant-i-reliably-capture-a-mouseout-event + * + * The fix implemented in this component ensure that we + * + * 1) have a hover state after a successful drag.move event + * 2) have an out event when dragging leaves an element + * + * @param {ElementRegistry} elementRegistry + * @param {EventBus} eventBus + * @param {Injector} injector + */ +function HoverFix(elementRegistry, eventBus, injector) { + + var self = this; + + var dragging = injector.get('dragging', false); + + /** + * Make sure we are god damn hovering! + * + * @param {Event} dragging event + */ + function ensureHover(event) { + + if (event.hover) { + return; + } + + var originalEvent = event.originalEvent; + + var gfx = self._findTargetGfx(originalEvent); + + var element = gfx && elementRegistry.get(gfx); + + if (gfx && element) { + + // 1) cancel current mousemove + event.stopPropagation(); + + // 2) emit fake hover for new target + dragging.hover({ element: element, gfx: gfx }); + + // 3) re-trigger move event + dragging.move(originalEvent); + } + } + + + if (dragging) { + + /** + * We wait for a specific sequence of events before + * emitting a fake drag.hover event. + * + * Event Sequence: + * + * drag.start + * drag.move >> ensure we are hovering + */ + eventBus.on('drag.start', function(event) { + + eventBus.once('drag.move', HIGH_PRIORITY$8, function(event) { + + ensureHover(event); + + }); + + }); + } + + + /** + * We make sure that element.out is always fired, even if the + * browser swallows an element.out event. + * + * Event sequence: + * + * element.hover + * (element.out >> sometimes swallowed) + * element.hover >> ensure we fired element.out + */ + (function() { + var hoverGfx; + var hover; + + eventBus.on('element.hover', function(event) { + + // (1) remember current hover element + hoverGfx = event.gfx; + hover = event.element; + }); + + eventBus.on('element.hover', HIGH_PRIORITY$8, function(event) { + + // (3) am I on an element still? + if (hover) { + + // (4) that is a problem, gotta "simulate the out" + eventBus.fire('element.out', { + element: hover, + gfx: hoverGfx + }); + } + + }); + + eventBus.on('element.out', function() { + + // (2) unset hover state if we correctly outed us *GG* + hoverGfx = null; + hover = null; + }); + + })(); + + this._findTargetGfx = function(event) { + var position, + target; + + if (!(event instanceof MouseEvent)) { + return; + } + + position = toPoint(event); + + // damn expensive operation, ouch! + target = document.elementFromPoint(position.x, position.y); + + return getGfx(target); + }; + +} + +HoverFix.$inject = [ + 'elementRegistry', + 'eventBus', + 'injector' +]; + + +// helpers ///////////////////// + +function getGfx(target) { + return closest(target, 'svg, .djs-element', true); +} + +/** + * @type { import('didi').ModuleDeclaration } + */ +var HoverFixModule = { + __init__: [ + 'hoverFix' + ], + hoverFix: [ 'type', HoverFix ], +}; + +function ensureImported(element, target) { + + if (element.ownerDocument !== target.ownerDocument) { + try { + + // may fail on webkit + return target.ownerDocument.importNode(element, true); + } catch (e) { + + // ignore + } + } + + return element; +} + +/** + * appendTo utility + */ + +/** + * Append a node to a target element and return the appended node. + * + * @param {SVGElement} element + * @param {SVGElement} target + * + * @return {SVGElement} the appended node + */ +function appendTo(element, target) { + return target.appendChild(ensureImported(element, target)); +} + +/** + * append utility + */ + +/** + * Append a node to an element + * + * @param {SVGElement} element + * @param {SVGElement} node + * + * @return {SVGElement} the element + */ +function append(target, node) { + appendTo(node, target); + return target; +} + +/** + * attribute accessor utility + */ + +var LENGTH_ATTR$1 = 2; + +var CSS_PROPERTIES$1 = { + 'alignment-baseline': 1, + 'baseline-shift': 1, + 'clip': 1, + 'clip-path': 1, + 'clip-rule': 1, + 'color': 1, + 'color-interpolation': 1, + 'color-interpolation-filters': 1, + 'color-profile': 1, + 'color-rendering': 1, + 'cursor': 1, + 'direction': 1, + 'display': 1, + 'dominant-baseline': 1, + 'enable-background': 1, + 'fill': 1, + 'fill-opacity': 1, + 'fill-rule': 1, + 'filter': 1, + 'flood-color': 1, + 'flood-opacity': 1, + 'font': 1, + 'font-family': 1, + 'font-size': LENGTH_ATTR$1, + 'font-size-adjust': 1, + 'font-stretch': 1, + 'font-style': 1, + 'font-variant': 1, + 'font-weight': 1, + 'glyph-orientation-horizontal': 1, + 'glyph-orientation-vertical': 1, + 'image-rendering': 1, + 'kerning': 1, + 'letter-spacing': 1, + 'lighting-color': 1, + 'marker': 1, + 'marker-end': 1, + 'marker-mid': 1, + 'marker-start': 1, + 'mask': 1, + 'opacity': 1, + 'overflow': 1, + 'pointer-events': 1, + 'shape-rendering': 1, + 'stop-color': 1, + 'stop-opacity': 1, + 'stroke': 1, + 'stroke-dasharray': 1, + 'stroke-dashoffset': 1, + 'stroke-linecap': 1, + 'stroke-linejoin': 1, + 'stroke-miterlimit': 1, + 'stroke-opacity': 1, + 'stroke-width': LENGTH_ATTR$1, + 'text-anchor': 1, + 'text-decoration': 1, + 'text-rendering': 1, + 'unicode-bidi': 1, + 'visibility': 1, + 'word-spacing': 1, + 'writing-mode': 1 +}; + + +function getAttribute$1(node, name) { + if (CSS_PROPERTIES$1[name]) { + return node.style[name]; + } else { + return node.getAttributeNS(null, name); + } +} + +function setAttribute$1(node, name, value) { + var hyphenated = name.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); + + var type = CSS_PROPERTIES$1[hyphenated]; + + if (type) { + + // append pixel unit, unless present + if (type === LENGTH_ATTR$1 && typeof value === 'number') { + value = String(value) + 'px'; + } + + node.style[hyphenated] = value; + } else { + node.setAttributeNS(null, name, value); + } +} + +function setAttributes$1(node, attrs) { + + var names = Object.keys(attrs), i, name; + + for (i = 0, name; (name = names[i]); i++) { + setAttribute$1(node, name, attrs[name]); + } +} + +/** + * Gets or sets raw attributes on a node. + * + * @param {SVGElement} node + * @param {Object} [attrs] + * @param {String} [name] + * @param {String} [value] + * + * @return {String} + */ +function attr$1(node, name, value) { + if (typeof name === 'string') { + if (value !== undefined) { + setAttribute$1(node, name, value); + } else { + return getAttribute$1(node, name); + } + } else { + setAttributes$1(node, name); + } + + return node; +} + +/** + * Taken from https://github.com/component/classes + * + * Without the component bits. + */ + +/** + * toString reference. + */ + +const toString = Object.prototype.toString; + +/** + * Wrap `el` in a `ClassList`. + * + * @param {Element} el + * @return {ClassList} + * @api public + */ + +function classes(el) { + return new ClassList(el); +} + +function ClassList(el) { + if (!el || !el.nodeType) { + throw new Error('A DOM element reference is required'); + } + this.el = el; + this.list = el.classList; +} + +/** + * Add class `name` if not already present. + * + * @param {String} name + * @return {ClassList} + * @api public + */ + +ClassList.prototype.add = function(name) { + this.list.add(name); + return this; +}; + +/** + * Remove class `name` when present, or + * pass a regular expression to remove + * any which match. + * + * @param {String|RegExp} name + * @return {ClassList} + * @api public + */ + +ClassList.prototype.remove = function(name) { + if ('[object RegExp]' == toString.call(name)) { + return this.removeMatching(name); + } + + this.list.remove(name); + return this; +}; + +/** + * Remove all classes matching `re`. + * + * @param {RegExp} re + * @return {ClassList} + * @api private + */ + +ClassList.prototype.removeMatching = function(re) { + const arr = this.array(); + for (let i = 0; i < arr.length; i++) { + if (re.test(arr[i])) { + this.remove(arr[i]); + } + } + return this; +}; + +/** + * Toggle class `name`, can force state via `force`. + * + * For browsers that support classList, but do not support `force` yet, + * the mistake will be detected and corrected. + * + * @param {String} name + * @param {Boolean} force + * @return {ClassList} + * @api public + */ + +ClassList.prototype.toggle = function(name, force) { + if ('undefined' !== typeof force) { + if (force !== this.list.toggle(name, force)) { + this.list.toggle(name); // toggle again to correct + } + } else { + this.list.toggle(name); + } + return this; +}; + +/** + * Return an array of classes. + * + * @return {Array} + * @api public + */ + +ClassList.prototype.array = function() { + return Array.from(this.list); +}; + +/** + * Check if class `name` is present. + * + * @param {String} name + * @return {ClassList} + * @api public + */ + +ClassList.prototype.has = + ClassList.prototype.contains = function(name) { + return this.list.contains(name); + }; + +function remove(element) { + var parent = element.parentNode; + + if (parent) { + parent.removeChild(element); + } + + return element; +} + +/** + * Clear utility + */ + +/** + * Removes all children from the given element + * + * @param {DOMElement} element + * @return {DOMElement} the element (for chaining) + */ +function clear(element) { + var child; + + while ((child = element.firstChild)) { + remove(child); + } + + return element; +} + +function clone(element) { + return element.cloneNode(true); +} + +var ns$1 = { + svg: 'http://www.w3.org/2000/svg' +}; + +/** + * DOM parsing utility + */ + +var SVG_START$1 = '' + svg + ''; + unwrap = true; + } + + var parsed = parseDocument$1(svg); + + if (!unwrap) { + return parsed; + } + + var fragment = document.createDocumentFragment(); + + var parent = parsed.firstChild; + + while (parent.firstChild) { + fragment.appendChild(parent.firstChild); + } + + return fragment; +} + +function parseDocument$1(svg) { + + var parser; + + // parse + parser = new DOMParser(); + parser.async = false; + + return parser.parseFromString(svg, 'text/xml'); +} + +/** + * Create utility for SVG elements + */ + + +/** + * Create a specific type from name or SVG markup. + * + * @param {String} name the name or markup of the element + * @param {Object} [attrs] attributes to set on the element + * + * @returns {SVGElement} + */ +function create$2(name, attrs) { + var element; + + if (name.charAt(0) === '<') { + element = parse$2(name).firstChild; + element = document.importNode(element, true); + } else { + element = document.createElementNS(ns$1.svg, name); + } + + if (attrs) { + attr$1(element, attrs); + } + + return element; +} + +/** + * Geometry helpers + */ + +// fake node used to instantiate svg geometry elements +var node = null; + +function getNode() { + if (node === null) { + node = create$2('svg'); + } + + return node; +} + +function extend$1(object, props) { + var i, k, keys = Object.keys(props); + + for (i = 0; (k = keys[i]); i++) { + object[k] = props[k]; + } + + return object; +} + +/** + * Create matrix via args. + * + * @example + * + * createMatrix({ a: 1, b: 1 }); + * createMatrix(); + * createMatrix(1, 2, 0, 0, 30, 20); + * + * @return {SVGMatrix} + */ +function createMatrix(a, b, c, d, e, f) { + var matrix = getNode().createSVGMatrix(); + + switch (arguments.length) { + case 0: + return matrix; + case 1: + return extend$1(matrix, a); + case 6: + return extend$1(matrix, { + a: a, + b: b, + c: c, + d: d, + e: e, + f: f + }); + } +} + +function createTransform(matrix) { + if (matrix) { + return getNode().createSVGTransformFromMatrix(matrix); + } else { + return getNode().createSVGTransform(); + } +} + +/** + * Serialization util + */ + +var TEXT_ENTITIES = /([&<>]{1})/g; +var ATTR_ENTITIES = /([\n\r"]{1})/g; + +var ENTITY_REPLACEMENT = { + '&': '&', + '<': '<', + '>': '>', + '"': '\'' +}; + +function escape$1(str, pattern) { + + function replaceFn(match, entity) { + return ENTITY_REPLACEMENT[entity] || entity; + } + + return str.replace(pattern, replaceFn); +} + +function serialize(node, output) { + + var i, len, attrMap, attrNode, childNodes; + + switch (node.nodeType) { + + // TEXT + case 3: + + // replace special XML characters + output.push(escape$1(node.textContent, TEXT_ENTITIES)); + break; + + // ELEMENT + case 1: + output.push('<', node.tagName); + + if (node.hasAttributes()) { + attrMap = node.attributes; + for (i = 0, len = attrMap.length; i < len; ++i) { + attrNode = attrMap.item(i); + output.push(' ', attrNode.name, '="', escape$1(attrNode.value, ATTR_ENTITIES), '"'); + } + } + + if (node.hasChildNodes()) { + output.push('>'); + childNodes = node.childNodes; + for (i = 0, len = childNodes.length; i < len; ++i) { + serialize(childNodes.item(i), output); + } + output.push(''); + } else { + output.push('/>'); + } + break; + + // COMMENT + case 8: + output.push(''); + break; + + // CDATA + case 4: + output.push(''); + break; + + default: + throw new Error('unable to handle node ' + node.nodeType); + } + + return output; +} + +/** + * innerHTML like functionality for SVG elements. + * based on innerSVG (https://code.google.com/p/innersvg) + */ + + +function set$2(element, svg) { + + var parsed = parse$2(svg); + + // clear element contents + clear(element); + + if (!svg) { + return; + } + + if (!isFragment(parsed)) { + + // extract from parsed document + parsed = parsed.documentElement; + } + + var nodes = slice$1(parsed.childNodes); + + // import + append each node + for (var i = 0; i < nodes.length; i++) { + appendTo(nodes[i], element); + } + +} + +function get$1(element) { + var child = element.firstChild, + output = []; + + while (child) { + serialize(child, output); + child = child.nextSibling; + } + + return output.join(''); +} + +function isFragment(node) { + return node.nodeName === '#document-fragment'; +} + +function innerSVG(element, svg) { + + if (svg !== undefined) { + + try { + set$2(element, svg); + } catch (e) { + throw new Error('error parsing SVG: ' + e.message); + } + + return element; + } else { + return get$1(element); + } +} + + +function slice$1(arr) { + return Array.prototype.slice.call(arr); +} + +/** + * transform accessor utility + */ + +function wrapMatrix(transformList, transform) { + if (transform instanceof SVGMatrix) { + return transformList.createSVGTransformFromMatrix(transform); + } + + return transform; +} + + +function setTransforms(transformList, transforms) { + var i, t; + + transformList.clear(); + + for (i = 0; (t = transforms[i]); i++) { + transformList.appendItem(wrapMatrix(transformList, t)); + } +} + +/** + * Get or set the transforms on the given node. + * + * @param {SVGElement} node + * @param {SVGTransform|SVGMatrix|Array} [transforms] + * + * @return {SVGTransform} the consolidated transform + */ +function transform$1(node, transforms) { + var transformList = node.transform.baseVal; + + if (transforms) { + + if (!Array.isArray(transforms)) { + transforms = [ transforms ]; + } + + setTransforms(transformList, transforms); + } + + return transformList.consolidate(); +} + +/** + * @typedef {(string|number)[]} Component + * + * @typedef {import('../util/Types').Point} Point + */ + +/** + * @param {Component[] | Component[][]} elements + * + * @return {string} + */ +function componentsToPath(elements) { + return elements.flat().join(',').replace(/,?([A-z]),?/g, '$1'); +} + +/** + * @param {Point} point + * + * @return {Component[]} + */ +function move(point) { + return [ 'M', point.x, point.y ]; +} + +/** + * @param {Point} point + * + * @return {Component[]} + */ +function lineTo(point) { + return [ 'L', point.x, point.y ]; +} + +/** + * @param {Point} p1 + * @param {Point} p2 + * @param {Point} p3 + * + * @return {Component[]} + */ +function curveTo(p1, p2, p3) { + return [ 'C', p1.x, p1.y, p2.x, p2.y, p3.x, p3.y ]; +} + +/** + * @param {Point[]} waypoints + * @param {number} [cornerRadius] + * @return {Component[][]} + */ +function drawPath(waypoints, cornerRadius) { + const pointCount = waypoints.length; + + const path = [ move(waypoints[0]) ]; + + for (let i = 1; i < pointCount; i++) { + + const pointBefore = waypoints[i - 1]; + const point = waypoints[i]; + const pointAfter = waypoints[i + 1]; + + if (!pointAfter || !cornerRadius) { + path.push(lineTo(point)); + + continue; + } + + const effectiveRadius = Math.min( + cornerRadius, + vectorLength(point.x - pointBefore.x, point.y - pointBefore.y), + vectorLength(pointAfter.x - point.x, pointAfter.y - point.y) + ); + + if (!effectiveRadius) { + path.push(lineTo(point)); + + continue; + } + + const beforePoint = getPointAtLength(point, pointBefore, effectiveRadius); + const beforePoint2 = getPointAtLength(point, pointBefore, effectiveRadius * .5); + + const afterPoint = getPointAtLength(point, pointAfter, effectiveRadius); + const afterPoint2 = getPointAtLength(point, pointAfter, effectiveRadius * .5); + + path.push(lineTo(beforePoint)); + path.push(curveTo(beforePoint2, afterPoint2, afterPoint)); + } + + return path; +} + +function getPointAtLength(start, end, length) { + + const deltaX = end.x - start.x; + const deltaY = end.y - start.y; + + const totalLength = vectorLength(deltaX, deltaY); + + const percent = length / totalLength; + + return { + x: start.x + deltaX * percent, + y: start.y + deltaY * percent + }; +} + +function vectorLength(x, y) { + return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); +} + +/** + * @param {Point[]} points + * @param {number|Object} [attrs] + * @param {number} [radius] + * + * @return {SVGElement} + */ +function createLine(points, attrs, radius) { + + if (isNumber(attrs)) { + radius = attrs; + attrs = null; + } + + if (!attrs) { + attrs = {}; + } + + const line = create$2('path', attrs); + + if (isNumber(radius)) { + line.dataset.cornerRadius = String(radius); + } + + return updateLine(line, points); +} + +/** + * @param {SVGElement} gfx + * @param {Point[]} points + * + * @return {SVGElement} + */ +function updateLine(gfx, points) { + + const cornerRadius = parseInt(gfx.dataset.cornerRadius, 10) || 0; + + attr$1(gfx, { + d: componentsToPath(drawPath(points, cornerRadius)) + }); + + return gfx; +} + +/** + * @typedef {import('../../model/Types').Element} Element + * + * @typedef {import('../../core/ElementRegistry').default} ElementRegistry + * @typedef {import('../../core/EventBus').default} EventBus + * @typedef {import('../../draw/Styles').default} Styles + * + * @typedef {import('../../util/Types').Point} Point + */ + +function allowAll(event) { return true; } + +function allowPrimaryAndAuxiliary(event) { + return isPrimaryButton(event) || isAuxiliaryButton(event); +} + +var LOW_PRIORITY$d = 500; + + +/** + * A plugin that provides interaction events for diagram elements. + * + * It emits the following events: + * + * * element.click + * * element.contextmenu + * * element.dblclick + * * element.hover + * * element.mousedown + * * element.mousemove + * * element.mouseup + * * element.out + * + * Each event is a tuple { element, gfx, originalEvent }. + * + * Canceling the event via Event#preventDefault() + * prevents the original DOM operation. + * + * @param {EventBus} eventBus + * @param {ElementRegistry} elementRegistry + * @param {Styles} styles + */ +function InteractionEvents(eventBus, elementRegistry, styles) { + + var self = this; + + /** + * Fire an interaction event. + * + * @param {string} type local event name, e.g. element.click. + * @param {MouseEvent|TouchEvent} event native event + * @param {Element} [element] the diagram element to emit the event on; + * defaults to the event target + */ + function fire(type, event, element) { + + if (isIgnored(type, event)) { + return; + } + + var target, gfx, returnValue; + + if (!element) { + target = event.delegateTarget || event.target; + + if (target) { + gfx = target; + element = elementRegistry.get(gfx); + } + } else { + gfx = elementRegistry.getGraphics(element); + } + + if (!gfx || !element) { + return; + } + + returnValue = eventBus.fire(type, { + element: element, + gfx: gfx, + originalEvent: event + }); + + if (returnValue === false) { + event.stopPropagation(); + event.preventDefault(); + } + } + + // TODO(nikku): document this + var handlers = {}; + + function mouseHandler(localEventName) { + return handlers[localEventName]; + } + + function isIgnored(localEventName, event) { + + var filter = ignoredFilters[localEventName] || isPrimaryButton; + + // only react on left mouse button interactions + // except for interaction events that are enabled + // for secundary mouse button + return !filter(event); + } + + var bindings = { + click: 'element.click', + contextmenu: 'element.contextmenu', + dblclick: 'element.dblclick', + mousedown: 'element.mousedown', + mousemove: 'element.mousemove', + mouseover: 'element.hover', + mouseout: 'element.out', + mouseup: 'element.mouseup', + }; + + var ignoredFilters = { + 'element.contextmenu': allowAll, + 'element.mousedown': allowPrimaryAndAuxiliary, + 'element.mouseup': allowPrimaryAndAuxiliary, + 'element.click': allowPrimaryAndAuxiliary, + 'element.dblclick': allowPrimaryAndAuxiliary + }; + + + // manual event trigger ////////// + + /** + * Trigger an interaction event (based on a native dom event) + * on the target shape or connection. + * + * @param {string} eventName the name of the triggered DOM event + * @param {MouseEvent|TouchEvent} event + * @param {Element} targetElement + */ + function triggerMouseEvent(eventName, event, targetElement) { + + // i.e. element.mousedown... + var localEventName = bindings[eventName]; + + if (!localEventName) { + throw new Error('unmapped DOM event name <' + eventName + '>'); + } + + return fire(localEventName, event, targetElement); + } + + + var ELEMENT_SELECTOR = 'svg, .djs-element'; + + // event handling /////// + + function registerEvent(node, event, localEvent, ignoredFilter) { + + var handler = handlers[localEvent] = function(event) { + fire(localEvent, event); + }; + + if (ignoredFilter) { + ignoredFilters[localEvent] = ignoredFilter; + } + + handler.$delegate = delegate.bind(node, ELEMENT_SELECTOR, event, handler); + } + + function unregisterEvent(node, event, localEvent) { + + var handler = mouseHandler(localEvent); + + if (!handler) { + return; + } + + delegate.unbind(node, event, handler.$delegate); + } + + function registerEvents(svg) { + forEach$2(bindings, function(val, key) { + registerEvent(svg, key, val); + }); + } + + function unregisterEvents(svg) { + forEach$2(bindings, function(val, key) { + unregisterEvent(svg, key, val); + }); + } + + eventBus.on('canvas.destroy', function(event) { + unregisterEvents(event.svg); + }); + + eventBus.on('canvas.init', function(event) { + registerEvents(event.svg); + }); + + + // hit box updating //////////////// + + eventBus.on([ 'shape.added', 'connection.added' ], function(event) { + var element = event.element, + gfx = event.gfx; + + eventBus.fire('interactionEvents.createHit', { element: element, gfx: gfx }); + }); + + // Update djs-hit on change. + // A low priortity is necessary, because djs-hit of labels has to be updated + // after the label bounds have been updated in the renderer. + eventBus.on([ + 'shape.changed', + 'connection.changed' + ], LOW_PRIORITY$d, function(event) { + + var element = event.element, + gfx = event.gfx; + + eventBus.fire('interactionEvents.updateHit', { element: element, gfx: gfx }); + }); + + eventBus.on('interactionEvents.createHit', LOW_PRIORITY$d, function(event) { + var element = event.element, + gfx = event.gfx; + + self.createDefaultHit(element, gfx); + }); + + eventBus.on('interactionEvents.updateHit', function(event) { + var element = event.element, + gfx = event.gfx; + + self.updateDefaultHit(element, gfx); + }); + + + // hit styles //////////// + + var STROKE_HIT_STYLE = createHitStyle('djs-hit djs-hit-stroke'); + + var CLICK_STROKE_HIT_STYLE = createHitStyle('djs-hit djs-hit-click-stroke'); + + var ALL_HIT_STYLE = createHitStyle('djs-hit djs-hit-all'); + + var NO_MOVE_HIT_STYLE = createHitStyle('djs-hit djs-hit-no-move'); + + var HIT_TYPES = { + 'all': ALL_HIT_STYLE, + 'click-stroke': CLICK_STROKE_HIT_STYLE, + 'stroke': STROKE_HIT_STYLE, + 'no-move': NO_MOVE_HIT_STYLE + }; + + function createHitStyle(classNames, attrs) { + + attrs = assign$3({ + stroke: 'white', + strokeWidth: 15 + }, attrs || {}); + + return styles.cls(classNames, [ 'no-fill', 'no-border' ], attrs); + } + + + // style helpers /////////////// + + function applyStyle(hit, type) { + + var attrs = HIT_TYPES[type]; + + if (!attrs) { + throw new Error('invalid hit type <' + type + '>'); + } + + attr$1(hit, attrs); + + return hit; + } + + function appendHit(gfx, hit) { + append(gfx, hit); + } + + + // API + + /** + * Remove hints on the given graphics. + * + * @param {SVGElement} gfx + */ + this.removeHits = function(gfx) { + var hits = all('.djs-hit', gfx); + + forEach$2(hits, remove); + }; + + /** + * Create default hit for the given element. + * + * @param {Element} element + * @param {SVGElement} gfx + * + * @return {SVGElement} created hit + */ + this.createDefaultHit = function(element, gfx) { + var waypoints = element.waypoints, + isFrame = element.isFrame, + boxType; + + if (waypoints) { + return this.createWaypointsHit(gfx, waypoints); + } else { + + boxType = isFrame ? 'stroke' : 'all'; + + return this.createBoxHit(gfx, boxType, { + width: element.width, + height: element.height + }); + } + }; + + /** + * Create hits for the given waypoints. + * + * @param {SVGElement} gfx + * @param {Point[]} waypoints + * + * @return {SVGElement} + */ + this.createWaypointsHit = function(gfx, waypoints) { + + var hit = createLine(waypoints); + + applyStyle(hit, 'stroke'); + + appendHit(gfx, hit); + + return hit; + }; + + /** + * Create hits for a box. + * + * @param {SVGElement} gfx + * @param {string} type + * @param {Object} attrs + * + * @return {SVGElement} + */ + this.createBoxHit = function(gfx, type, attrs) { + + attrs = assign$3({ + x: 0, + y: 0 + }, attrs); + + var hit = create$2('rect'); + + applyStyle(hit, type); + + attr$1(hit, attrs); + + appendHit(gfx, hit); + + return hit; + }; + + /** + * Update default hit of the element. + * + * @param {Element} element + * @param {SVGElement} gfx + * + * @return {SVGElement} updated hit + */ + this.updateDefaultHit = function(element, gfx) { + + var hit = query('.djs-hit', gfx); + + if (!hit) { + return; + } + + if (element.waypoints) { + updateLine(hit, element.waypoints); + } else { + attr$1(hit, { + width: element.width, + height: element.height + }); + } + + return hit; + }; + + this.fire = fire; + + this.triggerMouseEvent = triggerMouseEvent; + + this.mouseHandler = mouseHandler; + + this.registerEvent = registerEvent; + this.unregisterEvent = unregisterEvent; +} + + +InteractionEvents.$inject = [ + 'eventBus', + 'elementRegistry', + 'styles' +]; + + +/** + * An event indicating that the mouse hovered over an element + * + * @event element.hover + * + * @type {Object} + * @property {Element} element + * @property {SVGElement} gfx + * @property {Event} originalEvent + */ + +/** + * An event indicating that the mouse has left an element + * + * @event element.out + * + * @type {Object} + * @property {Element} element + * @property {SVGElement} gfx + * @property {Event} originalEvent + */ + +/** + * An event indicating that the mouse has clicked an element + * + * @event element.click + * + * @type {Object} + * @property {Element} element + * @property {SVGElement} gfx + * @property {Event} originalEvent + */ + +/** + * An event indicating that the mouse has double clicked an element + * + * @event element.dblclick + * + * @type {Object} + * @property {Element} element + * @property {SVGElement} gfx + * @property {Event} originalEvent + */ + +/** + * An event indicating that the mouse has gone down on an element. + * + * @event element.mousedown + * + * @type {Object} + * @property {Element} element + * @property {SVGElement} gfx + * @property {Event} originalEvent + */ + +/** + * An event indicating that the mouse has gone up on an element. + * + * @event element.mouseup + * + * @type {Object} + * @property {Element} element + * @property {SVGElement} gfx + * @property {Event} originalEvent + */ + +/** + * An event indicating that the context menu action is triggered + * via mouse or touch controls. + * + * @event element.contextmenu + * + * @type {Object} + * @property {Element} element + * @property {SVGElement} gfx + * @property {Event} originalEvent + */ + +/** + * @type { import('didi').ModuleDeclaration } + */ +var InteractionEventsModule = { + __init__: [ 'interactionEvents' ], + interactionEvents: [ 'type', InteractionEvents ] +}; + +var LOW_PRIORITY$c = 500; + +/** + * @typedef {import('../../model/Types').Element} Element + * + * @typedef {import('../../core/EventBus').default} EventBus + * @typedef {import('../../draw/Styles').default} Styles + */ + +/** + * @class + * + * A plugin that adds an outline to shapes and connections that may be activated and styled + * via CSS classes. + * + * @param {EventBus} eventBus + * @param {Styles} styles + */ +function Outline(eventBus, styles) { + + this.offset = 6; + + var OUTLINE_STYLE = styles.cls('djs-outline', [ 'no-fill' ]); + + var self = this; + + function createOutline(gfx, bounds) { + var outline = create$2('rect'); + + attr$1(outline, assign$3({ + x: 10, + y: 10, + rx: 4, + width: 100, + height: 100 + }, OUTLINE_STYLE)); + + append(gfx, outline); + + return outline; + } + + // A low priortity is necessary, because outlines of labels have to be updated + // after the label bounds have been updated in the renderer. + eventBus.on([ 'shape.added', 'shape.changed' ], LOW_PRIORITY$c, function(event) { + var element = event.element, + gfx = event.gfx; + + var outline = query('.djs-outline', gfx); + + if (!outline) { + outline = createOutline(gfx); + } + + self.updateShapeOutline(outline, element); + }); + + eventBus.on([ 'connection.added', 'connection.changed' ], function(event) { + var element = event.element, + gfx = event.gfx; + + var outline = query('.djs-outline', gfx); + + if (!outline) { + outline = createOutline(gfx); + } + + self.updateConnectionOutline(outline, element); + }); +} + + +/** + * Updates the outline of a shape respecting the dimension of the + * element and an outline offset. + * + * @param {SVGElement} outline + * @param {Element} element + */ +Outline.prototype.updateShapeOutline = function(outline, element) { + + attr$1(outline, { + x: -this.offset, + y: -this.offset, + width: element.width + this.offset * 2, + height: element.height + this.offset * 2 + }); + +}; + + +/** + * Updates the outline of a connection respecting the bounding box of + * the connection and an outline offset. + * + * @param {SVGElement} outline + * @param {Element} connection + */ +Outline.prototype.updateConnectionOutline = function(outline, connection) { + + var bbox = getBBox(connection); + + attr$1(outline, { + x: bbox.x - this.offset, + y: bbox.y - this.offset, + width: bbox.width + this.offset * 2, + height: bbox.height + this.offset * 2 + }); + +}; + + +Outline.$inject = [ 'eventBus', 'styles', 'elementRegistry' ]; + +/** + * @type { import('didi').ModuleDeclaration } + */ +var OutlineModule = { + __init__: [ 'outline' ], + outline: [ 'type', Outline ] +}; + +/** + * @typedef {import('../../core/Canvas').default} Canvas + * @typedef {import('../../core/EventBus').default} EventBus + */ + +/** + * A service that offers the current selection in a diagram. + * Offers the api to control the selection, too. + * + * @param {EventBus} eventBus + * @param {Canvas} canvas + */ +function Selection(eventBus, canvas) { + + this._eventBus = eventBus; + this._canvas = canvas; + + /** + * @type {Object[]} + */ + this._selectedElements = []; + + var self = this; + + eventBus.on([ 'shape.remove', 'connection.remove' ], function(e) { + var element = e.element; + self.deselect(element); + }); + + eventBus.on([ 'diagram.clear', 'root.set' ], function(e) { + self.select(null); + }); +} + +Selection.$inject = [ 'eventBus', 'canvas' ]; + +/** + * Deselect an element. + * + * @param {Object} element The element to deselect. + */ +Selection.prototype.deselect = function(element) { + var selectedElements = this._selectedElements; + + var idx = selectedElements.indexOf(element); + + if (idx !== -1) { + var oldSelection = selectedElements.slice(); + + selectedElements.splice(idx, 1); + + this._eventBus.fire('selection.changed', { oldSelection: oldSelection, newSelection: selectedElements }); + } +}; + +/** + * Get the selected elements. + * + * @return {Object[]} The selected elements. + */ +Selection.prototype.get = function() { + return this._selectedElements; +}; + +/** + * Check whether an element is selected. + * + * @param {Object} element The element. + * + * @return {boolean} Whether the element is selected. + */ +Selection.prototype.isSelected = function(element) { + return this._selectedElements.indexOf(element) !== -1; +}; + + +/** + * Select one or many elements. + * + * @param {Object|Object[]} elements The element(s) to select. + * @param {boolean} [add] Whether to add the element(s) to the selected elements. + * Defaults to `false`. + */ +Selection.prototype.select = function(elements, add) { + var selectedElements = this._selectedElements, + oldSelection = selectedElements.slice(); + + if (!isArray$4(elements)) { + elements = elements ? [ elements ] : []; + } + + var canvas = this._canvas; + + var rootElement = canvas.getRootElement(); + + elements = elements.filter(function(element) { + var elementRoot = canvas.findRoot(element); + + return rootElement === elementRoot; + }); + + // selection may be cleared by passing an empty array or null + // to the method + if (add) { + forEach$2(elements, function(element) { + if (selectedElements.indexOf(element) !== -1) { + + // already selected + return; + } else { + selectedElements.push(element); + } + }); + } else { + this._selectedElements = selectedElements = elements.slice(); + } + + this._eventBus.fire('selection.changed', { oldSelection: oldSelection, newSelection: selectedElements }); +}; + +/** + * @typedef {import('../../core/Canvas').default} Canvas + * @typedef {import('../../core/EventBus').default} EventBus + * @typedef {import('./Selection').default} Selection + */ + +var MARKER_HOVER = 'hover', + MARKER_SELECTED = 'selected'; + +var SELECTION_OUTLINE_PADDING = 6; + + +/** + * A plugin that adds a visible selection UI to shapes and connections + * by appending the hover and selected classes to them. + * + * @class + * + * Makes elements selectable, too. + * + * @param {Canvas} canvas + * @param {EventBus} eventBus + * @param {Selection} selection + */ +function SelectionVisuals(canvas, eventBus, selection) { + this._canvas = canvas; + + var self = this; + + this._multiSelectionBox = null; + + function addMarker(e, cls) { + canvas.addMarker(e, cls); + } + + function removeMarker(e, cls) { + canvas.removeMarker(e, cls); + } + + eventBus.on('element.hover', function(event) { + addMarker(event.element, MARKER_HOVER); + }); + + eventBus.on('element.out', function(event) { + removeMarker(event.element, MARKER_HOVER); + }); + + eventBus.on('selection.changed', function(event) { + + function deselect(s) { + removeMarker(s, MARKER_SELECTED); + } + + function select(s) { + addMarker(s, MARKER_SELECTED); + } + + var oldSelection = event.oldSelection, + newSelection = event.newSelection; + + forEach$2(oldSelection, function(e) { + if (newSelection.indexOf(e) === -1) { + deselect(e); + } + }); + + forEach$2(newSelection, function(e) { + if (oldSelection.indexOf(e) === -1) { + select(e); + } + }); + + self._updateSelectionOutline(newSelection); + }); + + + eventBus.on('element.changed', function(event) { + if (selection.isSelected(event.element)) { + self._updateSelectionOutline(selection.get()); + } + }); +} + +SelectionVisuals.$inject = [ + 'canvas', + 'eventBus', + 'selection' +]; + +SelectionVisuals.prototype._updateSelectionOutline = function(selection) { + var layer = this._canvas.getLayer('selectionOutline'); + + clear(layer); + + var enabled = selection.length > 1; + + var container = this._canvas.getContainer(); + + classes(container)[enabled ? 'add' : 'remove']('djs-multi-select'); + + if (!enabled) { + return; + } + + var bBox = addSelectionOutlinePadding(getBBox(selection)); + + var rect = create$2('rect'); + + attr$1(rect, assign$3({ + rx: 3 + }, bBox)); + + classes(rect).add('djs-selection-outline'); + + append(layer, rect); +}; + +// helpers ////////// + +function addSelectionOutlinePadding(bBox) { + return { + x: bBox.x - SELECTION_OUTLINE_PADDING, + y: bBox.y - SELECTION_OUTLINE_PADDING, + width: bBox.width + SELECTION_OUTLINE_PADDING * 2, + height: bBox.height + SELECTION_OUTLINE_PADDING * 2 + }; +} + +/** + * @typedef {import('../../core/Canvas').default} Canvas + * @typedef {import('../../core/ElementRegistry').default} ElementRegistry + * @typedef {import('../../core/EventBus').default} EventBus + * @typedef {import('./Selection').default} Selection + */ + +/** + * @param {EventBus} eventBus + * @param {Selection} selection + * @param {Canvas} canvas + * @param {ElementRegistry} elementRegistry + */ +function SelectionBehavior(eventBus, selection, canvas, elementRegistry) { + + // Select elements on create + eventBus.on('create.end', 500, function(event) { + var context = event.context, + canExecute = context.canExecute, + elements = context.elements, + hints = context.hints || {}, + autoSelect = hints.autoSelect; + + if (canExecute) { + if (autoSelect === false) { + + // Select no elements + return; + } + + if (isArray$4(autoSelect)) { + selection.select(autoSelect); + } else { + + // Select all elements by default + selection.select(elements.filter(isShown)); + } + } + }); + + // Select connection targets on connect + eventBus.on('connect.end', 500, function(event) { + var context = event.context, + connection = context.connection; + + if (connection) { + selection.select(connection); + } + }); + + // Select shapes on move + eventBus.on('shape.move.end', 500, function(event) { + var previousSelection = event.previousSelection || []; + + var shape = elementRegistry.get(event.context.shape.id); + + // Always select main shape on move + var isSelected = find(previousSelection, function(selectedShape) { + return shape.id === selectedShape.id; + }); + + if (!isSelected) { + selection.select(shape); + } + }); + + // Select elements on click + eventBus.on('element.click', function(event) { + + if (!isPrimaryButton(event)) { + return; + } + + var element = event.element; + + if (element === canvas.getRootElement()) { + element = null; + } + + var isSelected = selection.isSelected(element), + isMultiSelect = selection.get().length > 1; + + // Add to selection if CTRL or SHIFT pressed + var add = hasPrimaryModifier(event) || hasSecondaryModifier(event); + + if (isSelected && isMultiSelect) { + if (add) { + + // Deselect element + return selection.deselect(element); + } else { + + // Select element only + return selection.select(element); + } + } else if (!isSelected) { + + // Select element + selection.select(element, add); + } else { + + // Deselect element + selection.deselect(element); + } + }); +} + +SelectionBehavior.$inject = [ + 'eventBus', + 'selection', + 'canvas', + 'elementRegistry' +]; + + +function isShown(element) { + return !element.hidden; +} + +/** + * @type { import('didi').ModuleDeclaration } + */ +var SelectionModule = { + __init__: [ 'selectionVisuals', 'selectionBehavior' ], + __depends__: [ + InteractionEventsModule, + OutlineModule + ], + selection: [ 'type', Selection ], + selectionVisuals: [ 'type', SelectionVisuals ], + selectionBehavior: [ 'type', SelectionBehavior ] +}; + +var CURSOR_CLS_PATTERN = /^djs-cursor-.*$/; + +/** + * @param {string} mode + */ +function set$1(mode) { + var classes = classes$1(document.body); + + classes.removeMatching(CURSOR_CLS_PATTERN); + + if (mode) { + classes.add('djs-cursor-' + mode); + } +} + +function unset() { + set$1(null); +} + +/** + * @typedef {import('../core/EventBus').EventBus} EventBus + */ + +var TRAP_PRIORITY = 5000; + +/** + * Installs a click trap that prevents a ghost click following a dragging operation. + * + * @param {EventBus} eventBus + * @param {string} [eventName='element.click'] + * + * @return {() => void} a function to immediately remove the installed trap. + */ +function install(eventBus, eventName) { + + eventName = eventName || 'element.click'; + + function trap() { + return false; + } + + eventBus.once(eventName, TRAP_PRIORITY, trap); + + return function() { + eventBus.off(eventName, trap); + }; +} + +var KEYS_COPY = [ 'c', 'C' ]; +var KEYS_PASTE = [ 'v', 'V' ]; +var KEYS_REDO = [ 'y', 'Y' ]; +var KEYS_UNDO = [ 'z', 'Z' ]; + +/** + * Returns true if event was triggered with any modifier + * @param {KeyboardEvent} event + */ +function hasModifier(event) { + return (event.ctrlKey || event.metaKey || event.shiftKey || event.altKey); +} + +/** + * @param {KeyboardEvent} event + * @return {boolean} + */ +function isCmd(event) { + + // ensure we don't react to AltGr + // (mapped to CTRL + ALT) + if (event.altKey) { + return false; + } + + return event.ctrlKey || event.metaKey; +} + +/** + * Checks if key pressed is one of provided keys. + * + * @param {string|string[]} keys + * @param {KeyboardEvent} event + * @return {boolean} + */ +function isKey(keys, event) { + keys = isArray$4(keys) ? keys : [ keys ]; + + return keys.indexOf(event.key) !== -1 || keys.indexOf(event.code) !== -1; +} + +/** + * @param {KeyboardEvent} event + */ +function isShift(event) { + return event.shiftKey; +} + +/** + * @param {KeyboardEvent} event + */ +function isCopy(event) { + return isCmd(event) && isKey(KEYS_COPY, event); +} + +/** + * @param {KeyboardEvent} event + */ +function isPaste(event) { + return isCmd(event) && isKey(KEYS_PASTE, event); +} + +/** + * @param {KeyboardEvent} event + */ +function isUndo(event) { + return isCmd(event) && !isShift(event) && isKey(KEYS_UNDO, event); +} + +/** + * @param {KeyboardEvent} event + */ +function isRedo(event) { + return isCmd(event) && ( + isKey(KEYS_REDO, event) || ( + isKey(KEYS_UNDO, event) && isShift(event) + ) + ); +} + +var round$7 = Math.round; + +/** + * @typedef {import('../../util/Types').Point} Point + * + * @typedef {import('../../core/Canvas').default} Canvas + * @typedef {import('../../core/ElementRegistry').default} ElementRegistry + * @typedef {import('../../core/EventBus').default} EventBus + * @typedef {import('../selection/Selection').default} Selection + */ + +var DRAG_ACTIVE_CLS = 'djs-drag-active'; + + +function preventDefault(event) { + event.preventDefault(); +} + +function isTouchEvent(event) { + + // check for TouchEvent being available first + // (i.e. not available on desktop Firefox) + return typeof TouchEvent !== 'undefined' && event instanceof TouchEvent; +} + +function getLength(point) { + return Math.sqrt(Math.pow(point.x, 2) + Math.pow(point.y, 2)); +} + +/** + * A helper that fires canvas localized drag events and realizes + * the general "drag-and-drop" look and feel. + * + * Calling {@link Dragging#activate} activates dragging on a canvas. + * + * It provides the following: + * + * * emits life cycle events, namespaced with a prefix assigned + * during dragging activation + * * sets and restores the cursor + * * sets and restores the selection if elements still exist + * * ensures there can be only one drag operation active at a time + * + * Dragging may be canceled manually by calling {@link Dragging#cancel} + * or by pressing ESC. + * + * + * ## Life-cycle events + * + * Dragging can be in three different states, off, initialized + * and active. + * + * (1) off: no dragging operation is in progress + * (2) initialized: a new drag operation got initialized but not yet + * started (i.e. because of no initial move) + * (3) started: dragging is in progress + * + * Eventually dragging will be off again after a drag operation has + * been ended or canceled via user click or ESC key press. + * + * To indicate transitions between these states dragging emits generic + * life-cycle events with the `drag.` prefix _and_ events namespaced + * to a prefix choosen by a user during drag initialization. + * + * The following events are emitted (appropriately prefixed) via + * the {@link EventBus}. + * + * * `init` + * * `start` + * * `move` + * * `end` + * * `ended` (dragging already in off state) + * * `cancel` (only if previously started) + * * `canceled` (dragging already in off state, only if previously started) + * * `cleanup` + * + * + * @example + * + * ```javascript + * function MyDragComponent(eventBus, dragging) { + * + * eventBus.on('mydrag.start', function(event) { + * console.log('yes, we start dragging'); + * }); + * + * eventBus.on('mydrag.move', function(event) { + * console.log('canvas local coordinates', event.x, event.y, event.dx, event.dy); + * + * // local drag data is passed with the event + * event.context.foo; // "BAR" + * + * // the original mouse event, too + * event.originalEvent; // MouseEvent(...) + * }); + * + * eventBus.on('element.click', function(event) { + * dragging.init(event, 'mydrag', { + * cursor: 'grabbing', + * data: { + * context: { + * foo: "BAR" + * } + * } + * }); + * }); + * } + * ``` + * + * @param {EventBus} eventBus + * @param {Canvas} canvas + * @param {Selection} selection + * @param {ElementRegistry} elementRegistry + */ +function Dragging(eventBus, canvas, selection, elementRegistry) { + + var defaultOptions = { + threshold: 5, + trapClick: true + }; + + // the currently active drag operation + // dragging is active as soon as this context exists. + // + // it is visually _active_ only when a context.active flag is set to true. + var context; + + /* convert a global event into local coordinates */ + function toLocalPoint(globalPosition) { + + var viewbox = canvas.viewbox(); + + var clientRect = canvas._container.getBoundingClientRect(); + + return { + x: viewbox.x + (globalPosition.x - clientRect.left) / viewbox.scale, + y: viewbox.y + (globalPosition.y - clientRect.top) / viewbox.scale + }; + } + + // helpers + + function fire(type, dragContext) { + dragContext = dragContext || context; + + var event = eventBus.createEvent( + assign$3( + {}, + dragContext.payload, + dragContext.data, + { isTouch: dragContext.isTouch } + ) + ); + + // default integration + if (eventBus.fire('drag.' + type, event) === false) { + return false; + } + + return eventBus.fire(dragContext.prefix + '.' + type, event); + } + + function restoreSelection(previousSelection) { + var existingSelection = previousSelection.filter(function(element) { + return elementRegistry.get(element.id); + }); + + existingSelection.length && selection.select(existingSelection); + } + + // event listeners + + function move(event, activate) { + var payload = context.payload, + displacement = context.displacement; + + var globalStart = context.globalStart, + globalCurrent = toPoint(event), + globalDelta = delta(globalCurrent, globalStart); + + var localStart = context.localStart, + localCurrent = toLocalPoint(globalCurrent), + localDelta = delta(localCurrent, localStart); + + + // activate context explicitly or once threshold is reached + if (!context.active && (activate || getLength(globalDelta) > context.threshold)) { + + // fire start event with original + // starting coordinates + + assign$3(payload, { + x: round$7(localStart.x + displacement.x), + y: round$7(localStart.y + displacement.y), + dx: 0, + dy: 0 + }, { originalEvent: event }); + + if (false === fire('start')) { + return cancel(); + } + + context.active = true; + + // unset selection and remember old selection + // the previous (old) selection will always passed + // with the event via the event.previousSelection property + if (!context.keepSelection) { + payload.previousSelection = selection.get(); + selection.select(null); + } + + // allow custom cursor + if (context.cursor) { + set$1(context.cursor); + } + + // indicate dragging via marker on root element + canvas.addMarker(canvas.getRootElement(), DRAG_ACTIVE_CLS); + } + + stopPropagation(event); + + if (context.active) { + + // update payload with actual coordinates + assign$3(payload, { + x: round$7(localCurrent.x + displacement.x), + y: round$7(localCurrent.y + displacement.y), + dx: round$7(localDelta.x), + dy: round$7(localDelta.y) + }, { originalEvent: event }); + + // emit move event + fire('move'); + } + } + + function end(event) { + var previousContext, + returnValue = true; + + if (context.active) { + + if (event) { + context.payload.originalEvent = event; + + // suppress original event (click, ...) + // because we just ended a drag operation + stopPropagation(event); + } + + // implementations may stop restoring the + // original state (selections, ...) by preventing the + // end events default action + returnValue = fire('end'); + } + + if (returnValue === false) { + fire('rejected'); + } + + previousContext = cleanup(returnValue !== true); + + // last event to be fired when all drag operations are done + // at this point in time no drag operation is in progress anymore + fire('ended', previousContext); + } + + + // cancel active drag operation if the user presses + // the ESC key on the keyboard + + function checkCancel(event) { + + if (isKey('Escape', event)) { + preventDefault(event); + + cancel(); + } + } + + + // prevent ghost click that might occur after a finished + // drag and drop session + + function trapClickAndEnd(event) { + + var untrap; + + // trap the click in case we are part of an active + // drag operation. This will effectively prevent + // the ghost click that cannot be canceled otherwise. + if (context.active) { + + untrap = install(eventBus); + + // remove trap after minimal delay + setTimeout(untrap, 400); + + // prevent default action (click) + preventDefault(event); + } + + end(event); + } + + function trapTouch(event) { + move(event); + } + + // update the drag events model element (`hover`) and graphical element (`hoverGfx`) + // properties during hover and out and fire {prefix}.hover and {prefix}.out properties + // respectively + + function hover(event) { + var payload = context.payload; + + payload.hoverGfx = event.gfx; + payload.hover = event.element; + + fire('hover'); + } + + function out(event) { + fire('out'); + + var payload = context.payload; + + payload.hoverGfx = null; + payload.hover = null; + } + + + // life-cycle methods + + function cancel(restore) { + var previousContext; + + if (!context) { + return; + } + + var wasActive = context.active; + + if (wasActive) { + fire('cancel'); + } + + previousContext = cleanup(restore); + + if (wasActive) { + + // last event to be fired when all drag operations are done + // at this point in time no drag operation is in progress anymore + fire('canceled', previousContext); + } + } + + function cleanup(restore) { + var previousContext, + endDrag; + + fire('cleanup'); + + // reset cursor + unset(); + + if (context.trapClick) { + endDrag = trapClickAndEnd; + } else { + endDrag = end; + } + + // reset dom listeners + event.unbind(document, 'mousemove', move); + + event.unbind(document, 'dragstart', preventDefault); + event.unbind(document, 'selectstart', preventDefault); + + event.unbind(document, 'mousedown', endDrag, true); + event.unbind(document, 'mouseup', endDrag, true); + + event.unbind(document, 'keyup', checkCancel); + + event.unbind(document, 'touchstart', trapTouch, true); + event.unbind(document, 'touchcancel', cancel, true); + event.unbind(document, 'touchmove', move, true); + event.unbind(document, 'touchend', end, true); + + eventBus.off('element.hover', hover); + eventBus.off('element.out', out); + + // remove drag marker on root element + canvas.removeMarker(canvas.getRootElement(), DRAG_ACTIVE_CLS); + + // restore selection, unless it has changed + var previousSelection = context.payload.previousSelection; + + if (restore !== false && previousSelection && !selection.get().length) { + restoreSelection(previousSelection); + } + + previousContext = context; + + context = null; + + return previousContext; + } + + /** + * Initialize a drag operation. + * + * If `localPosition` is given, drag events will be emitted + * relative to it. + * + * @param {MouseEvent|TouchEvent} [event] + * @param {Point} [relativeTo] actual diagram local position this drag operation should start at + * @param {string} prefix + * @param {Object} [options] + */ + function init(event$1, relativeTo, prefix, options) { + + // only one drag operation may be active, at a time + if (context) { + cancel(false); + } + + if (typeof relativeTo === 'string') { + options = prefix; + prefix = relativeTo; + relativeTo = null; + } + + options = assign$3({}, defaultOptions, options || {}); + + var data = options.data || {}, + originalEvent, + globalStart, + localStart, + endDrag, + isTouch; + + if (options.trapClick) { + endDrag = trapClickAndEnd; + } else { + endDrag = end; + } + + if (event$1) { + originalEvent = getOriginal(event$1) || event$1; + globalStart = toPoint(event$1); + + stopPropagation(event$1); + + // prevent default browser dragging behavior + if (originalEvent.type === 'dragstart') { + preventDefault(originalEvent); + } + } else { + originalEvent = null; + globalStart = { x: 0, y: 0 }; + } + + localStart = toLocalPoint(globalStart); + + if (!relativeTo) { + relativeTo = localStart; + } + + isTouch = isTouchEvent(originalEvent); + + context = assign$3({ + prefix: prefix, + data: data, + payload: {}, + globalStart: globalStart, + displacement: delta(relativeTo, localStart), + localStart: localStart, + isTouch: isTouch + }, options); + + // skip dom registration if trigger + // is set to manual (during testing) + if (!options.manual) { + + // add dom listeners + + if (isTouch) { + event.bind(document, 'touchstart', trapTouch, true); + event.bind(document, 'touchcancel', cancel, true); + event.bind(document, 'touchmove', move, true); + event.bind(document, 'touchend', end, true); + } else { + + // assume we use the mouse to interact per default + event.bind(document, 'mousemove', move); + + // prevent default browser drag and text selection behavior + event.bind(document, 'dragstart', preventDefault); + event.bind(document, 'selectstart', preventDefault); + + event.bind(document, 'mousedown', endDrag, true); + event.bind(document, 'mouseup', endDrag, true); + } + + event.bind(document, 'keyup', checkCancel); + + eventBus.on('element.hover', hover); + eventBus.on('element.out', out); + } + + fire('init'); + + if (options.autoActivate) { + move(event$1, true); + } + } + + // cancel on diagram destruction + eventBus.on('diagram.destroy', cancel); + + + // API + + this.init = init; + this.move = move; + this.hover = hover; + this.out = out; + this.end = end; + + this.cancel = cancel; + + // for introspection + + this.context = function() { + return context; + }; + + this.setOptions = function(options) { + assign$3(defaultOptions, options); + }; +} + +Dragging.$inject = [ + 'eventBus', + 'canvas', + 'selection', + 'elementRegistry' +]; + +/** + * @type { import('didi').ModuleDeclaration } + */ +var DraggingModule = { + __depends__: [ + HoverFixModule, + SelectionModule, + ], + dragging: [ 'type', Dragging ], +}; + +/** + * SVGs for elements are generated by the {@link GraphicsFactory}. + * + * This utility gives quick access to the important semantic + * parts of an element. + */ + +/** + * Returns the visual part of a diagram element. + * + * @param {SVGElement} gfx + * + * @return {SVGElement} + */ +function getVisual(gfx) { + return gfx.childNodes[0]; +} + +/** + * Returns the children for a given diagram element. + * + * @param {SVGElement} gfx + * @return {SVGElement} + */ +function getChildren(gfx) { + return gfx.parentNode.childNodes[1]; +} + +/** + * @typedef {import('../../core/Types').ElementLike} Element + * @typedef {import('../../core/Types').ShapeLike} Shape + * + * @typedef {import('../../core/Canvas').default} Canvas + * @typedef {import('../../core/ElementRegistry').default} ElementRegistry + * @typedef {import('../../core/EventBus').default} EventBus + * @typedef {import('../../draw/Styles').default} Styles + */ + +var MARKER_TYPES = [ + 'marker-start', + 'marker-mid', + 'marker-end' +]; + +var NODES_CAN_HAVE_MARKER = [ + 'circle', + 'ellipse', + 'line', + 'path', + 'polygon', + 'polyline', + 'path', + 'rect' +]; + + +/** + * Adds support for previews of moving/resizing elements. + * + * @param {ElementRegistry} elementRegistry + * @param {EventBus} eventBus + * @param {Canvas} canvas + * @param {Styles} styles + */ +function PreviewSupport(elementRegistry, eventBus, canvas, styles) { + this._elementRegistry = elementRegistry; + this._canvas = canvas; + this._styles = styles; + + this._clonedMarkers = {}; + + var self = this; + + eventBus.on('drag.cleanup', function() { + forEach$2(self._clonedMarkers, function(clonedMarker) { + remove(clonedMarker); + }); + + self._clonedMarkers = {}; + }); +} + +PreviewSupport.$inject = [ + 'elementRegistry', + 'eventBus', + 'canvas', + 'styles' +]; + + +/** + * Returns graphics of an element. + * + * @param {Element} element + * + * @return {SVGElement} + */ +PreviewSupport.prototype.getGfx = function(element) { + return this._elementRegistry.getGraphics(element); +}; + +/** + * Adds a move preview of a given shape to a given SVG group. + * + * @param {Element} element The element to be moved. + * @param {SVGElement} group The SVG group to add the preview to. + * @param {SVGElement} [gfx] The optional graphical element of the element. + * + * @return {SVGElement} The preview. + */ +PreviewSupport.prototype.addDragger = function(element, group, gfx) { + gfx = gfx || this.getGfx(element); + + var dragger = clone(gfx); + var bbox = gfx.getBoundingClientRect(); + + this._cloneMarkers(getVisual(dragger)); + + attr$1(dragger, this._styles.cls('djs-dragger', [], { + x: bbox.top, + y: bbox.left + })); + + append(group, dragger); + + return dragger; +}; + +/** + * Adds a resize preview of a given shape to a given SVG group. + * + * @param {Shape} shape The element to be resized. + * @param {SVGElement} group The SVG group to add the preview to. + * + * @return {SVGElement} The preview. + */ +PreviewSupport.prototype.addFrame = function(shape, group) { + + var frame = create$2('rect', { + class: 'djs-resize-overlay', + width: shape.width, + height: shape.height, + x: shape.x, + y: shape.y + }); + + append(group, frame); + + return frame; +}; + +/** + * Clone all markers referenced by a node and its child nodes. + * + * @param {SVGElement} gfx + */ +PreviewSupport.prototype._cloneMarkers = function(gfx) { + var self = this; + + if (gfx.childNodes) { + + // TODO: use forEach once we drop PhantomJS + for (var i = 0; i < gfx.childNodes.length; i++) { + + // recursively clone markers of child nodes + self._cloneMarkers(gfx.childNodes[ i ]); + } + } + + if (!canHaveMarker(gfx)) { + return; + } + + MARKER_TYPES.forEach(function(markerType) { + if (attr$1(gfx, markerType)) { + var marker = getMarker(gfx, markerType, self._canvas.getContainer()); + + self._cloneMarker(gfx, marker, markerType); + } + }); +}; + +/** + * Clone marker referenced by an element. + * + * @param {SVGElement} gfx + * @param {SVGElement} marker + * @param {string} markerType + */ +PreviewSupport.prototype._cloneMarker = function(gfx, marker, markerType) { + var markerId = marker.id; + + var clonedMarker = this._clonedMarkers[ markerId ]; + + if (!clonedMarker) { + clonedMarker = clone(marker); + + var clonedMarkerId = markerId + '-clone'; + + clonedMarker.id = clonedMarkerId; + + classes(clonedMarker) + .add('djs-dragger') + .add('djs-dragger-marker'); + + this._clonedMarkers[ markerId ] = clonedMarker; + + var defs = query('defs', this._canvas._svg); + + if (!defs) { + defs = create$2('defs'); + + append(this._canvas._svg, defs); + } + + append(defs, clonedMarker); + } + + var reference = idToReference(this._clonedMarkers[ markerId ].id); + + attr$1(gfx, markerType, reference); +}; + +// helpers ////////// + +/** + * Get marker of given type referenced by node. + * + * @param {HTMLElement} node + * @param {string} markerType + * @param {HTMLElement} [parentNode] + * + * @param {HTMLElement} + */ +function getMarker(node, markerType, parentNode) { + var id = referenceToId(attr$1(node, markerType)); + + return query('marker#' + id, parentNode || document); +} + +/** + * Get ID of fragment within current document from its functional IRI reference. + * References may use single or double quotes. + * + * @param {string} reference + * + * @return {string} + */ +function referenceToId(reference) { + return reference.match(/url\(['"]?#([^'"]*)['"]?\)/)[1]; +} + +/** + * Get functional IRI reference for given ID of fragment within current document. + * + * @param {string} id + * + * @return {string} + */ +function idToReference(id) { + return 'url(#' + id + ')'; +} + +/** + * Check wether node type can have marker attributes. + * + * @param {HTMLElement} node + * + * @return {boolean} + */ +function canHaveMarker(node) { + return NODES_CAN_HAVE_MARKER.indexOf(node.nodeName) !== -1; +} + +/** + * @type { import('didi').ModuleDeclaration } + */ +var PreviewSupportModule = { + __init__: [ 'previewSupport' ], + previewSupport: [ 'type', PreviewSupport ] +}; + +var MARKER_OK = 'drop-ok', + MARKER_NOT_OK = 'drop-not-ok', + MARKER_ATTACH$1 = 'attach-ok', + MARKER_NEW_PARENT = 'new-parent'; + +/** + * @typedef {import('../../core/Types').ElementLike} Element + * @typedef {import('../../core/Types').ShapeLike} Shape + * + * @typedef {import('../../util/Types').Point} Point + * + * @typedef {import('../../core/Canvas').default} Canvas + * @typedef {import('../dragging/Dragging').default} Dragging + * @typedef {import('../../core/EventBus').default} EventBus + * @typedef {import('../modeling/Modeling').default} Modeling + * @typedef {import('../rules/Rules').default} Rules + */ + +var PREFIX = 'create'; + +var HIGH_PRIORITY$7 = 2000; + + +/** + * Create new elements through drag and drop. + * + * @param {Canvas} canvas + * @param {Dragging} dragging + * @param {EventBus} eventBus + * @param {Modeling} modeling + * @param {Rules} rules + */ +function Create( + canvas, + dragging, + eventBus, + modeling, + rules +) { + + // rules ////////// + + /** + * Check wether elements can be created. + * + * @param {Element[]} elements + * @param {Shape} target + * @param {Point} position + * @param {Element} [source] + * + * @return {boolean|null|Object} + */ + function canCreate(elements, target, position, source, hints) { + if (!target) { + return false; + } + + // ignore child elements and external labels + elements = filter(elements, function(element) { + var labelTarget = element.labelTarget; + + return !element.parent && !(isLabel(element) && elements.indexOf(labelTarget) !== -1); + }); + + var shape = find(elements, function(element) { + return !isConnection(element); + }); + + var attach = false, + connect = false, + create = false; + + // (1) attaching single shapes + if (isSingleShape(elements)) { + attach = rules.allowed('shape.attach', { + position: position, + shape: shape, + target: target + }); + } + + if (!attach) { + + // (2) creating elements + if (isSingleShape(elements)) { + create = rules.allowed('shape.create', { + position: position, + shape: shape, + source: source, + target: target + }); + } else { + create = rules.allowed('elements.create', { + elements: elements, + position: position, + target: target + }); + } + + } + + var connectionTarget = hints.connectionTarget; + + // (3) appending single shapes + if (create || attach) { + if (shape && source) { + connect = rules.allowed('connection.create', { + source: connectionTarget === source ? shape : source, + target: connectionTarget === source ? source : shape, + hints: { + targetParent: target, + targetAttach: attach + } + }); + } + + return { + attach: attach, + connect: connect + }; + } + + // ignore wether or not elements can be created + if (create === null || attach === null) { + return null; + } + + return false; + } + + function setMarker(element, marker) { + [ MARKER_ATTACH$1, MARKER_OK, MARKER_NOT_OK, MARKER_NEW_PARENT ].forEach(function(m) { + + if (m === marker) { + canvas.addMarker(element, m); + } else { + canvas.removeMarker(element, m); + } + }); + } + + // event handling ////////// + + eventBus.on([ 'create.move', 'create.hover' ], function(event) { + var context = event.context, + elements = context.elements, + hover = event.hover, + source = context.source, + hints = context.hints || {}; + + if (!hover) { + context.canExecute = false; + context.target = null; + + return; + } + + ensureConstraints$1(event); + + var position = { + x: event.x, + y: event.y + }; + + var canExecute = context.canExecute = hover && canCreate(elements, hover, position, source, hints); + + if (hover && canExecute !== null) { + context.target = hover; + + if (canExecute && canExecute.attach) { + setMarker(hover, MARKER_ATTACH$1); + } else { + setMarker(hover, canExecute ? MARKER_NEW_PARENT : MARKER_NOT_OK); + } + } + }); + + eventBus.on([ 'create.end', 'create.out', 'create.cleanup' ], function(event) { + var hover = event.hover; + + if (hover) { + setMarker(hover, null); + } + }); + + eventBus.on('create.end', function(event) { + var context = event.context, + source = context.source, + shape = context.shape, + elements = context.elements, + target = context.target, + canExecute = context.canExecute, + attach = canExecute && canExecute.attach, + connect = canExecute && canExecute.connect, + hints = context.hints || {}; + + if (canExecute === false || !target) { + return false; + } + + ensureConstraints$1(event); + + var position = { + x: event.x, + y: event.y + }; + + if (connect) { + shape = modeling.appendShape(source, shape, position, target, { + attach: attach, + connection: connect === true ? {} : connect, + connectionTarget: hints.connectionTarget + }); + } else { + elements = modeling.createElements(elements, position, target, assign$3({}, hints, { + attach: attach + })); + + // update shape + shape = find(elements, function(element) { + return !isConnection(element); + }); + } + + // update elements and shape + assign$3(context, { + elements: elements, + shape: shape + }); + + assign$3(event, { + elements: elements, + shape: shape + }); + }); + + function cancel() { + var context = dragging.context(); + + if (context && context.prefix === PREFIX) { + dragging.cancel(); + } + } + + // cancel on that is not result of + eventBus.on('create.init', function() { + eventBus.on('elements.changed', cancel); + + eventBus.once([ 'create.cancel', 'create.end' ], HIGH_PRIORITY$7, function() { + eventBus.off('elements.changed', cancel); + }); + }); + + // API ////////// + + this.start = function(event, elements, context) { + if (!isArray$4(elements)) { + elements = [ elements ]; + } + + var shape = find(elements, function(element) { + return !isConnection(element); + }); + + if (!shape) { + + // at least one shape is required + return; + } + + context = assign$3({ + elements: elements, + hints: {}, + shape: shape + }, context || {}); + + // make sure each element has x and y + forEach$2(elements, function(element) { + if (!isNumber(element.x)) { + element.x = 0; + } + + if (!isNumber(element.y)) { + element.y = 0; + } + }); + + var visibleElements = filter(elements, function(element) { + return !element.hidden; + }); + + var bbox = getBBox(visibleElements); + + // center elements around cursor + forEach$2(elements, function(element) { + if (isConnection(element)) { + element.waypoints = map$2(element.waypoints, function(waypoint) { + return { + x: waypoint.x - bbox.x - bbox.width / 2, + y: waypoint.y - bbox.y - bbox.height / 2 + }; + }); + } + + assign$3(element, { + x: element.x - bbox.x - bbox.width / 2, + y: element.y - bbox.y - bbox.height / 2 + }); + }); + + dragging.init(event, PREFIX, { + cursor: 'grabbing', + autoActivate: true, + data: { + shape: shape, + elements: elements, + context: context + } + }); + }; +} + +Create.$inject = [ + 'canvas', + 'dragging', + 'eventBus', + 'modeling', + 'rules' +]; + +// helpers ////////// + +function ensureConstraints$1(event) { + var context = event.context, + createConstraints = context.createConstraints; + + if (!createConstraints) { + return; + } + + if (createConstraints.left) { + event.x = Math.max(event.x, createConstraints.left); + } + + if (createConstraints.right) { + event.x = Math.min(event.x, createConstraints.right); + } + + if (createConstraints.top) { + event.y = Math.max(event.y, createConstraints.top); + } + + if (createConstraints.bottom) { + event.y = Math.min(event.y, createConstraints.bottom); + } +} + +function isSingleShape(elements) { + return elements && elements.length === 1 && !isConnection(elements[ 0 ]); +} + +/** + * @param {SVGElement} gfx + * @param {number} x + * @param {number} y + * @param {number} [angle] + * @param {number} [amount] + */ +function transform(gfx, x, y, angle, amount) { + var translate = createTransform(); + translate.setTranslate(x, y); + + var rotate = createTransform(); + rotate.setRotate(angle || 0, 0, 0); + + var scale = createTransform(); + scale.setScale(amount || 1, amount || 1); + + transform$1(gfx, [ translate, rotate, scale ]); +} + + +/** + * @param {SVGElement} gfx + * @param {number} x + * @param {number} y + */ +function translate(gfx, x, y) { + var translate = createTransform(); + translate.setTranslate(x, y); + + transform$1(gfx, translate); +} + + +/** + * @param {SVGElement} gfx + * @param {number} angle + */ +function rotate(gfx, angle) { + var rotate = createTransform(); + rotate.setRotate(angle, 0, 0); + + transform$1(gfx, rotate); +} + +/** + * @typedef {import('../../core/Canvas').default} Canvas + * @typedef {import('../../core/EventBus').default} EventBus + * @typedef {import('../../core/GraphicsFactory').default} GraphicsFactory + * @typedef {import('../preview-support/PreviewSupport').default} PreviewSupport + * @typedef {import('../../draw/Styles').default} Styles + */ + +var LOW_PRIORITY$b = 750; + +/** + * @param {Canvas} canvas + * @param {EventBus} eventBus + * @param {GraphicsFactory} graphicsFactory + * @param {PreviewSupport} previewSupport + * @param {Styles} styles + */ +function CreatePreview( + canvas, + eventBus, + graphicsFactory, + previewSupport, + styles +) { + function createDragGroup(elements) { + var dragGroup = create$2('g'); + + attr$1(dragGroup, styles.cls('djs-drag-group', [ 'no-events' ])); + + var childrenGfx = create$2('g'); + + elements.forEach(function(element) { + + // create graphics + var gfx; + + if (element.hidden) { + return; + } + + if (element.waypoints) { + gfx = graphicsFactory._createContainer('connection', childrenGfx); + + graphicsFactory.drawConnection(getVisual(gfx), element); + } else { + gfx = graphicsFactory._createContainer('shape', childrenGfx); + + graphicsFactory.drawShape(getVisual(gfx), element); + + translate(gfx, element.x, element.y); + } + + // add preview + previewSupport.addDragger(element, dragGroup, gfx); + }); + + return dragGroup; + } + + eventBus.on('create.move', LOW_PRIORITY$b, function(event) { + + var hover = event.hover, + context = event.context, + elements = context.elements, + dragGroup = context.dragGroup; + + // lazily create previews + if (!dragGroup) { + dragGroup = context.dragGroup = createDragGroup(elements); + } + + var activeLayer; + + if (hover) { + if (!dragGroup.parentNode) { + activeLayer = canvas.getActiveLayer(); + + append(activeLayer, dragGroup); + } + + translate(dragGroup, event.x, event.y); + } else { + remove(dragGroup); + } + }); + + eventBus.on('create.cleanup', function(event) { + var context = event.context, + dragGroup = context.dragGroup; + + if (dragGroup) { + remove(dragGroup); + } + }); +} + +CreatePreview.$inject = [ + 'canvas', + 'eventBus', + 'graphicsFactory', + 'previewSupport', + 'styles' +]; + +/** + * @type { import('didi').ModuleDeclaration } + */ +var CreateModule = { + __depends__: [ + DraggingModule, + PreviewSupportModule, + RulesModule$1, + SelectionModule + ], + __init__: [ + 'create', + 'createPreview' + ], + create: [ 'type', Create ], + createPreview: [ 'type', CreatePreview ] +}; + +/** + * @typedef {import('../../core/EventBus').default} EventBus + */ + +/** + * @param {EventBus} eventBus + */ +function Mouse(eventBus) { + var self = this; + + this._lastMoveEvent = null; + + function setLastMoveEvent(mousemoveEvent) { + self._lastMoveEvent = mousemoveEvent; + } + + eventBus.on('canvas.init', function(context) { + var svg = self._svg = context.svg; + + svg.addEventListener('mousemove', setLastMoveEvent); + }); + + eventBus.on('canvas.destroy', function() { + self._lastMouseEvent = null; + + self._svg.removeEventListener('mousemove', setLastMoveEvent); + }); +} + +Mouse.$inject = [ 'eventBus' ]; + +Mouse.prototype.getLastMoveEvent = function() { + return this._lastMoveEvent || createMoveEvent(0, 0); +}; + +// helpers ////////// + +function createMoveEvent(x, y) { + var event = document.createEvent('MouseEvent'); + + var screenX = x, + screenY = y, + clientX = x, + clientY = y; + + if (event.initMouseEvent) { + event.initMouseEvent( + 'mousemove', + true, + true, + window, + 0, + screenX, + screenY, + clientX, + clientY, + false, + false, + false, + false, + 0, + null + ); + } + + return event; +} + +/** + * @type { import('didi').ModuleDeclaration } + */ +var MouseModule = { + __init__: [ 'mouse' ], + mouse: [ 'type', Mouse ] +}; + +/** + * @typedef {import('../../core/Types').ElementLike} Element + * @typedef {import('../../core/Types').ShapeLike} Shape + * + * @typedef {import('../../util/Types').Point} Point + * + * @typedef {import('../../core/Canvas').default} Canvas + * @typedef {import('../clipboard/Clipboard').default} Clipboard + * @typedef {import('../create/Create').default} Create + * @typedef {import('../../core/ElementFactory').default} ElementFactory + * @typedef {import('../../core/EventBus').default} EventBus + * @typedef {import('../modeling/Modeling').default} Modeling + * @typedef {import('../mouse/Mouse').default} Mouse + * @typedef {import('../rules/Rules').default} Rules + */ + +/** + * @typedef { (event: { elements: Element[] }) => Element[]|boolean } CopyPasteCanCopyElementsListener + */ + +/** + * @typedef { (event: { descriptor: any, element: Element, elements: Element[] }) => void } CopyPasteCopyElementListener + */ + +/** + * @typedef { (event: { element: Element, children: Element[] }) => void } CopyPasteCreateTreeListener + */ + +/** + * @typedef { (event: { elements: any, tree: any }) => void } CopyPasteElementsCopiedListener + */ + +/** + * @typedef { (event: { cache: any, descriptor: any }) => void } CopyPastePasteElementListener + */ + +/** + * @typedef { (event: { hints: any }) => void } CopyPastePasteElementsListener + */ + +/** + * Copy and paste elements. + * + * @param {Canvas} canvas + * @param {Create} create + * @param {Clipboard} clipboard + * @param {ElementFactory} elementFactory + * @param {EventBus} eventBus + * @param {Modeling} modeling + * @param {Mouse} mouse + * @param {Rules} rules + */ +function CopyPaste( + canvas, + create, + clipboard, + elementFactory, + eventBus, + modeling, + mouse, + rules +) { + + this._canvas = canvas; + this._create = create; + this._clipboard = clipboard; + this._elementFactory = elementFactory; + this._eventBus = eventBus; + this._modeling = modeling; + this._mouse = mouse; + this._rules = rules; + + eventBus.on('copyPaste.copyElement', function(context) { + var descriptor = context.descriptor, + element = context.element, + elements = context.elements; + + // default priority (priority = 1) + descriptor.priority = 1; + + descriptor.id = element.id; + + var parentCopied = find(elements, function(e) { + return e === element.parent; + }); + + // do NOT reference parent if parent wasn't copied + if (parentCopied) { + descriptor.parent = element.parent.id; + } + + // attachers (priority = 2) + if (isAttacher$2(element)) { + descriptor.priority = 2; + + descriptor.host = element.host.id; + } + + // connections (priority = 3) + if (isConnection(element)) { + descriptor.priority = 3; + + descriptor.source = element.source.id; + descriptor.target = element.target.id; + + descriptor.waypoints = copyWaypoints$1(element); + } + + // labels (priority = 4) + if (isLabel(element)) { + descriptor.priority = 4; + + descriptor.labelTarget = element.labelTarget.id; + } + + forEach$2([ 'x', 'y', 'width', 'height' ], function(property) { + if (isNumber(element[ property ])) { + descriptor[ property ] = element[ property ]; + } + }); + + descriptor.hidden = element.hidden; + descriptor.collapsed = element.collapsed; + + }); + + eventBus.on('copyPaste.pasteElements', function(context) { + var hints = context.hints; + + assign$3(hints, { + createElementsBehavior: false + }); + }); +} + +CopyPaste.$inject = [ + 'canvas', + 'create', + 'clipboard', + 'elementFactory', + 'eventBus', + 'modeling', + 'mouse', + 'rules' +]; + + +/** + * Copy elements. + * + * @param {Element[]} elements + * + * @return {Object} + */ +CopyPaste.prototype.copy = function(elements) { + var allowed, + tree; + + if (!isArray$4(elements)) { + elements = elements ? [ elements ] : []; + } + + allowed = this._eventBus.fire('copyPaste.canCopyElements', { + elements: elements + }); + + if (allowed === false) { + tree = {}; + } else { + tree = this.createTree(isArray$4(allowed) ? allowed : elements); + } + + // we set an empty tree, selection of elements + // to copy was empty. + this._clipboard.set(tree); + + this._eventBus.fire('copyPaste.elementsCopied', { + elements: elements, + tree: tree + }); + + return tree; +}; + +/** + * Paste elements. + * + * @param {Object} [context] + * @param {Shape} [context.element] The optional parent. + * @param {Point} [context.point] The optional osition. + * @param {Object} [context.hints] The optional hints. + */ +CopyPaste.prototype.paste = function(context) { + var tree = this._clipboard.get(); + + if (this._clipboard.isEmpty()) { + return; + } + + var hints = context && context.hints || {}; + + this._eventBus.fire('copyPaste.pasteElements', { + hints: hints + }); + + var elements = this._createElements(tree); + + // paste directly + if (context && context.element && context.point) { + return this._paste(elements, context.element, context.point, hints); + } + + this._create.start(this._mouse.getLastMoveEvent(), elements, { + hints: hints || {} + }); +}; + +/** + * Paste elements directly. + * + * @param {Element[]} elements + * @param {Shape} target + * @param {Point} position + * @param {Object} [hints] + */ +CopyPaste.prototype._paste = function(elements, target, position, hints) { + + // make sure each element has x and y + forEach$2(elements, function(element) { + if (!isNumber(element.x)) { + element.x = 0; + } + + if (!isNumber(element.y)) { + element.y = 0; + } + }); + + var bbox = getBBox(elements); + + // center elements around cursor + forEach$2(elements, function(element) { + if (isConnection(element)) { + element.waypoints = map$2(element.waypoints, function(waypoint) { + return { + x: waypoint.x - bbox.x - bbox.width / 2, + y: waypoint.y - bbox.y - bbox.height / 2 + }; + }); + } + + assign$3(element, { + x: element.x - bbox.x - bbox.width / 2, + y: element.y - bbox.y - bbox.height / 2 + }); + }); + + return this._modeling.createElements(elements, position, target, assign$3({}, hints)); +}; + +/** + * Create elements from tree. + */ +CopyPaste.prototype._createElements = function(tree) { + var self = this; + + var eventBus = this._eventBus; + + var cache = {}; + + var elements = []; + + forEach$2(tree, function(branch, depth) { + + // sort by priority + branch = sortBy(branch, 'priority'); + + forEach$2(branch, function(descriptor) { + + // remove priority + var attrs = assign$3({}, omit(descriptor, [ 'priority' ])); + + if (cache[ descriptor.parent ]) { + attrs.parent = cache[ descriptor.parent ]; + } else { + delete attrs.parent; + } + + eventBus.fire('copyPaste.pasteElement', { + cache: cache, + descriptor: attrs + }); + + var element; + + if (isConnection(attrs)) { + attrs.source = cache[ descriptor.source ]; + attrs.target = cache[ descriptor.target ]; + + element = cache[ descriptor.id ] = self.createConnection(attrs); + + elements.push(element); + + return; + } + + if (isLabel(attrs)) { + attrs.labelTarget = cache[ attrs.labelTarget ]; + + element = cache[ descriptor.id ] = self.createLabel(attrs); + + elements.push(element); + + return; + } + + if (attrs.host) { + attrs.host = cache[ attrs.host ]; + } + + element = cache[ descriptor.id ] = self.createShape(attrs); + + elements.push(element); + }); + + }); + + return elements; +}; + +CopyPaste.prototype.createConnection = function(attrs) { + var connection = this._elementFactory.createConnection(omit(attrs, [ 'id' ])); + + return connection; +}; + +CopyPaste.prototype.createLabel = function(attrs) { + var label = this._elementFactory.createLabel(omit(attrs, [ 'id' ])); + + return label; +}; + +CopyPaste.prototype.createShape = function(attrs) { + var shape = this._elementFactory.createShape(omit(attrs, [ 'id' ])); + + return shape; +}; + +/** + * Check wether element has relations to other elements e.g. attachers, labels and connections. + * + * @param {Object} element + * @param {Element[]} elements + * + * @return {boolean} + */ +CopyPaste.prototype.hasRelations = function(element, elements) { + var labelTarget, + source, + target; + + if (isConnection(element)) { + source = find(elements, matchPattern({ id: element.source.id })); + target = find(elements, matchPattern({ id: element.target.id })); + + if (!source || !target) { + return false; + } + } + + if (isLabel(element)) { + labelTarget = find(elements, matchPattern({ id: element.labelTarget.id })); + + if (!labelTarget) { + return false; + } + } + + return true; +}; + +/** + * Create a tree-like structure from elements. + * + * @example + * + * ```javascript + * tree: { + * 0: [ + * { id: 'Shape_1', priority: 1, ... }, + * { id: 'Shape_2', priority: 1, ... }, + * { id: 'Connection_1', source: 'Shape_1', target: 'Shape_2', priority: 3, ... }, + * ... + * ], + * 1: [ + * { id: 'Shape_3', parent: 'Shape1', priority: 1, ... }, + * ... + * ] + * }; + * ``` + * + * @param {Element[]} elements + * + * @return {Object} + */ +CopyPaste.prototype.createTree = function(elements) { + var rules = this._rules, + self = this; + + var tree = {}, + elementsData = []; + + var parents = getParents$1(elements); + + function canCopy(element, elements) { + return rules.allowed('element.copy', { + element: element, + elements: elements + }); + } + + function addElementData(element, depth) { + + // (1) check wether element has already been added + var foundElementData = find(elementsData, function(elementsData) { + return element === elementsData.element; + }); + + // (2) add element if not already added + if (!foundElementData) { + elementsData.push({ + element: element, + depth: depth + }); + + return; + } + + // (3) update depth + if (foundElementData.depth < depth) { + elementsData = removeElementData(foundElementData, elementsData); + + elementsData.push({ + element: foundElementData.element, + depth: depth + }); + } + } + + function removeElementData(elementData, elementsData) { + var index = elementsData.indexOf(elementData); + + if (index !== -1) { + elementsData.splice(index, 1); + } + + return elementsData; + } + + // (1) add elements + eachElement(parents, function(element, _index, depth) { + + // do NOT add external labels directly + if (isLabel(element)) { + return; + } + + // always copy external labels + forEach$2(element.labels, function(label) { + addElementData(label, depth); + }); + + function addRelatedElements(elements) { + elements && elements.length && forEach$2(elements, function(element) { + + // add external labels + forEach$2(element.labels, function(label) { + addElementData(label, depth); + }); + + addElementData(element, depth); + }); + } + + forEach$2([ element.attachers, element.incoming, element.outgoing ], addRelatedElements); + + addElementData(element, depth); + + var children = []; + + if (element.children) { + children = element.children.slice(); + } + + // allow others to add children to tree + self._eventBus.fire('copyPaste.createTree', { + element: element, + children: children + }); + + return children; + }); + + elements = map$2(elementsData, function(elementData) { + return elementData.element; + }); + + // (2) copy elements + elementsData = map$2(elementsData, function(elementData) { + elementData.descriptor = {}; + + self._eventBus.fire('copyPaste.copyElement', { + descriptor: elementData.descriptor, + element: elementData.element, + elements: elements + }); + + return elementData; + }); + + // (3) sort elements by priority + elementsData = sortBy(elementsData, function(elementData) { + return elementData.descriptor.priority; + }); + + elements = map$2(elementsData, function(elementData) { + return elementData.element; + }); + + // (4) create tree + forEach$2(elementsData, function(elementData) { + var depth = elementData.depth; + + if (!self.hasRelations(elementData.element, elements)) { + removeElement(elementData.element, elements); + + return; + } + + if (!canCopy(elementData.element, elements)) { + removeElement(elementData.element, elements); + + return; + } + + if (!tree[depth]) { + tree[depth] = []; + } + + tree[depth].push(elementData.descriptor); + }); + + return tree; +}; + +// helpers ////////// + +function isAttacher$2(element) { + return !!element.host; +} + +function copyWaypoints$1(element) { + return map$2(element.waypoints, function(waypoint) { + + waypoint = copyWaypoint$1(waypoint); + + if (waypoint.original) { + waypoint.original = copyWaypoint$1(waypoint.original); + } + + return waypoint; + }); +} + +function copyWaypoint$1(waypoint) { + return assign$3({}, waypoint); +} + +function removeElement(element, elements) { + var index = elements.indexOf(element); + + if (index === -1) { + return elements; + } + + return elements.splice(index, 1); +} + +/** + * @type { import('didi').ModuleDeclaration } + */ +var CopyPasteModule$1 = { + __depends__: [ + ClipboardModule, + CreateModule, + MouseModule, + RulesModule$1 + ], + __init__: [ 'copyPaste' ], + copyPaste: [ 'type', CopyPaste ] +}; + +/** + * @typedef {import('../modeling/BpmnFactory').default} BpmnFactory + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * @typedef {import('./ModdleCopy').default} ModdleCopy + */ + +function copyProperties$1(source, target, properties) { + if (!isArray$4(properties)) { + properties = [ properties ]; + } + + forEach$2(properties, function(property) { + if (!isUndefined$3(source[property])) { + target[property] = source[property]; + } + }); +} + +var LOW_PRIORITY$a = 750; + +/** + * BPMN-specific copy & paste. + * + * @param {BpmnFactory} bpmnFactory + * @param {EventBus} eventBus + * @param {ModdleCopy} moddleCopy + */ +function BpmnCopyPaste(bpmnFactory, eventBus, moddleCopy) { + + function copy(bo, clone) { + var targetBo = bpmnFactory.create(bo.$type); + + return moddleCopy.copyElement(bo, targetBo, null, clone); + } + + eventBus.on('copyPaste.copyElement', LOW_PRIORITY$a, function(context) { + var descriptor = context.descriptor, + element = context.element, + businessObject = getBusinessObject(element); + + // do not copy business object + di for labels; + // will be pulled from the referenced label target + if (isLabel(element)) { + return descriptor; + } + + var businessObjectCopy = descriptor.businessObject = copy(businessObject, true); + var diCopy = descriptor.di = copy(getDi(element), true); + diCopy.bpmnElement = businessObjectCopy; + + copyProperties$1(businessObjectCopy, descriptor, 'name'); + copyProperties$1(diCopy, descriptor, 'isExpanded'); + + // default sequence flow + if (businessObject.default) { + descriptor.default = businessObject.default.id; + } + }); + + var referencesKey = '-bpmn-js-refs'; + + function getReferences(cache) { + return (cache[referencesKey] = cache[referencesKey] || {}); + } + + function setReferences(cache, references) { + cache[referencesKey] = references; + } + + function resolveReferences(descriptor, cache, references) { + var businessObject = getBusinessObject(descriptor); + + // default sequence flows + if (descriptor.default) { + + // relationship cannot be resolved immediately + references[ descriptor.default ] = { + element: businessObject, + property: 'default' + }; + } + + // boundary events + if (descriptor.host) { + + // relationship can be resolved immediately + getBusinessObject(descriptor).attachedToRef = getBusinessObject(cache[ descriptor.host ]); + } + + return omit(references, reduce(references, function(array, reference, key) { + var element = reference.element, + property = reference.property; + + if (key === descriptor.id) { + element[ property ] = businessObject; + + array.push(descriptor.id); + } + + return array; + }, [])); + } + + eventBus.on('copyPaste.pasteElement', function(context) { + var cache = context.cache, + descriptor = context.descriptor, + businessObject = descriptor.businessObject, + di = descriptor.di; + + // wire existing di + businessObject for external label + if (isLabel(descriptor)) { + descriptor.businessObject = getBusinessObject(cache[ descriptor.labelTarget ]); + descriptor.di = getDi(cache[ descriptor.labelTarget ]); + + return; + } + + businessObject = descriptor.businessObject = copy(businessObject); + + di = descriptor.di = copy(di); + di.bpmnElement = businessObject; + + copyProperties$1(descriptor, businessObject, [ + 'isExpanded', + 'name' + ]); + + descriptor.type = businessObject.$type; + }); + + // copy + paste processRef with participant + + eventBus.on('copyPaste.copyElement', LOW_PRIORITY$a, function(context) { + var descriptor = context.descriptor, + element = context.element; + + if (!is$2(element, 'bpmn:Participant')) { + return; + } + + var participantBo = getBusinessObject(element); + + if (participantBo.processRef) { + descriptor.processRef = copy(participantBo.processRef, true); + } + }); + + eventBus.on('copyPaste.pasteElement', function(context) { + var descriptor = context.descriptor, + processRef = descriptor.processRef; + + if (processRef) { + descriptor.processRef = copy(processRef); + } + }); + + // resolve references + + eventBus.on('copyPaste.pasteElement', LOW_PRIORITY$a, function(context) { + var cache = context.cache, + descriptor = context.descriptor; + + // resolve references e.g. default sequence flow + setReferences( + cache, + resolveReferences(descriptor, cache, getReferences(cache)) + ); + }); + +} + + +BpmnCopyPaste.$inject = [ + 'bpmnFactory', + 'eventBus', + 'moddleCopy' +]; + +var DISALLOWED_PROPERTIES = [ + 'artifacts', + 'dataInputAssociations', + 'dataOutputAssociations', + 'default', + 'flowElements', + 'lanes', + 'incoming', + 'outgoing', + 'categoryValue' +]; + +/** + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * @typedef {import('../modeling/BpmnFactory').default} BpmnFactory + * @typedef {import('../../model/Types').Moddle} Moddle + * + * @typedef {import('../../model/Types').ModdleElement} ModdleElement + */ + +/** + * Utility for copying model properties from source element to target element. + * + * @param {EventBus} eventBus + * @param {BpmnFactory} bpmnFactory + * @param {Moddle} moddle + */ +function ModdleCopy(eventBus, bpmnFactory, moddle) { + this._bpmnFactory = bpmnFactory; + this._eventBus = eventBus; + this._moddle = moddle; + + // copy extension elements last + eventBus.on('moddleCopy.canCopyProperties', function(context) { + var propertyNames = context.propertyNames; + + if (!propertyNames || !propertyNames.length) { + return; + } + + return sortBy(propertyNames, function(propertyName) { + return propertyName === 'extensionElements'; + }); + }); + + // default check whether property can be copied + eventBus.on('moddleCopy.canCopyProperty', function(context) { + var parent = context.parent, + parentDescriptor = isObject(parent) && parent.$descriptor, + propertyName = context.propertyName; + + if (propertyName && DISALLOWED_PROPERTIES.indexOf(propertyName) !== -1) { + + // disallow copying property + return false; + } + + if (propertyName && + parentDescriptor && + !find(parentDescriptor.properties, matchPattern({ name: propertyName }))) { + + // disallow copying property + return false; + } + }); + + // do NOT allow to copy empty extension elements + eventBus.on('moddleCopy.canSetCopiedProperty', function(context) { + var property = context.property; + + if (is$1(property, 'bpmn:ExtensionElements') && (!property.values || !property.values.length)) { + + // disallow setting copied property + return false; + } + }); +} + +ModdleCopy.$inject = [ + 'eventBus', + 'bpmnFactory', + 'moddle' +]; + +/** + * Copy model properties of source element to target element. + * + * @param {ModdleElement} sourceElement + * @param {ModdleElement} targetElement + * @param {string[]} [propertyNames] + * @param {boolean} [clone=false] + * + * @return {ModdleElement} + */ +ModdleCopy.prototype.copyElement = function(sourceElement, targetElement, propertyNames, clone = false) { + var self = this; + + if (propertyNames && !isArray$4(propertyNames)) { + propertyNames = [ propertyNames ]; + } + + propertyNames = propertyNames || getPropertyNames(sourceElement.$descriptor); + + var canCopyProperties = this._eventBus.fire('moddleCopy.canCopyProperties', { + propertyNames: propertyNames, + sourceElement: sourceElement, + targetElement: targetElement, + clone: clone + }); + + if (canCopyProperties === false) { + return targetElement; + } + + if (isArray$4(canCopyProperties)) { + propertyNames = canCopyProperties; + } + + // copy properties + forEach$2(propertyNames, function(propertyName) { + var sourceProperty; + + if (has$2(sourceElement, propertyName)) { + sourceProperty = sourceElement.get(propertyName); + } + + var copiedProperty = self.copyProperty(sourceProperty, targetElement, propertyName, clone); + + if (!isDefined(copiedProperty)) { + return; + } + + var canSetProperty = self._eventBus.fire('moddleCopy.canSetCopiedProperty', { + parent: targetElement, + property: copiedProperty, + propertyName: propertyName + }); + + if (canSetProperty === false) { + return; + } + + // TODO(nikku): unclaim old IDs if ID property is copied over + // this._moddle.getPropertyDescriptor(parent, propertyName) + targetElement.set(propertyName, copiedProperty); + }); + + return targetElement; +}; + +/** + * Copy model property. + * + * @param {any} property + * @param {ModdleElement} parent + * @param {string} propertyName + * @param {boolean} [clone=false] + * + * @return {any} + */ +ModdleCopy.prototype.copyProperty = function(property, parent, propertyName, clone = false) { + var self = this; + + // allow others to copy property + var copiedProperty = this._eventBus.fire('moddleCopy.canCopyProperty', { + parent: parent, + property: property, + propertyName: propertyName, + clone: clone + }); + + // return if copying is NOT allowed + if (copiedProperty === false) { + return; + } + + if (copiedProperty) { + if (isObject(copiedProperty) && copiedProperty.$type && !copiedProperty.$parent) { + copiedProperty.$parent = parent; + } + + return copiedProperty; + } + + var propertyDescriptor = this._moddle.getPropertyDescriptor(parent, propertyName); + + // do NOT copy references + if (propertyDescriptor.isReference) { + return; + } + + // copy id + if (propertyDescriptor.isId) { + return property && this._copyId(property, parent, clone); + } + + // copy arrays + if (isArray$4(property)) { + return reduce(property, function(childProperties, childProperty) { + + // recursion + copiedProperty = self.copyProperty(childProperty, parent, propertyName, clone); + + // copying might NOT be allowed + if (copiedProperty) { + return childProperties.concat(copiedProperty); + } + + return childProperties; + }, []); + } + + // copy model elements + if (isObject(property) && property.$type) { + if (this._moddle.getElementDescriptor(property).isGeneric) { + return; + } + + copiedProperty = self._bpmnFactory.create(property.$type); + + copiedProperty.$parent = parent; + + // recursion + copiedProperty = self.copyElement(property, copiedProperty, null, clone); + + return copiedProperty; + } + + // copy primitive properties + return property; +}; + +ModdleCopy.prototype._copyId = function(id, element, clone = false) { + if (clone) { + return id; + } + + // disallow if already taken + if (this._moddle.ids.assigned(id)) { + return; + } else { + + this._moddle.ids.claim(id, element); + return id; + } +}; + +// helpers ////////// + +function getPropertyNames(descriptor, keepDefaultProperties) { + return reduce(descriptor.properties, function(properties, property) { + + if (keepDefaultProperties && property.default) { + return properties; + } + + return properties.concat(property.name); + }, []); +} + +function is$1(element, type) { + return element && isFunction(element.$instanceOf) && element.$instanceOf(type); +} + +var CopyPasteModule = { + __depends__: [ + CopyPasteModule$1 + ], + __init__: [ 'bpmnCopyPaste', 'moddleCopy' ], + bpmnCopyPaste: [ 'type', BpmnCopyPaste ], + moddleCopy: [ 'type', ModdleCopy ] +}; + +/** + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * @typedef {import('../modeling/Modeling').default} Modeling + * + * @typedef {import('../../core/Types').ShapeLike} Shape + */ + +var round$6 = Math.round; + +/** + * Service that allows replacing of elements. + * + * @param {Modeling} modeling + * @param {EventBus} eventBus + */ +function Replace(modeling, eventBus) { + this._modeling = modeling; + this._eventBus = eventBus; +} + +Replace.$inject = [ 'modeling', 'eventBus' ]; + +/** + * Replace an element. + * + * @param {Shape} oldElement The element to be replaced. + * @param {Object} attrs Containing information about the new element, for + * example the new bounds and type. + * @param {Object} hints Custom hints that will be attached to the context. It + * can be used to inject data that is needed in the command chain. For example + * it could be used in eventbus.on('commandStack.shape.replace.postExecute') to + * change shape attributes after shape creation. + * + * @return {Shape} + */ +Replace.prototype.replaceElement = function(oldElement, attrs, hints) { + + if (oldElement.waypoints) { + + // TODO(nikku): we do not replace connections, yet + return null; + } + + var modeling = this._modeling; + var eventBus = this._eventBus; + + eventBus.fire('replace.start', { + element: oldElement, + attrs, + hints + }); + + var width = attrs.width || oldElement.width, + height = attrs.height || oldElement.height, + x = attrs.x || oldElement.x, + y = attrs.y || oldElement.y, + centerX = round$6(x + width / 2), + centerY = round$6(y + height / 2); + + // modeling API requires center coordinates, + // account for that when handling shape bounds + + var newElement = modeling.replaceShape( + oldElement, + assign$3( + {}, + attrs, + { + x: centerX, + y: centerY, + width: width, + height: height + } + ), + hints + ); + + eventBus.fire('replace.end', { + element: oldElement, + newElement, + hints + }); + + return newElement; +}; + +function ReplaceSelectionBehavior(selection, eventBus) { + + eventBus.on('replace.end', 500, function(event) { + const { + newElement, + hints = {} + } = event; + + if (hints.select === false) { + return; + } + + selection.select(newElement); + }); + +} + +ReplaceSelectionBehavior.$inject = [ 'selection', 'eventBus' ]; + +/** + * @type { import('didi').ModuleDeclaration } + */ +var ReplaceModule$1 = { + __init__: [ 'replace', 'replaceSelectionBehavior' ], + replaceSelectionBehavior: [ 'type', ReplaceSelectionBehavior ], + replace: [ 'type', Replace ] +}; + +/** + * @typedef {import('../modeling/BpmnFactory').default} BpmnFactory + * @typedef {import('../modeling/ElementFactory').default} ElementFactory + * @typedef {import('../copy-paste/ModdleCopy').default} ModdleCopy + * @typedef {import('../modeling/Modeling').default} Modeling + * @typedef {import('diagram-js/lib/features/replace/Replace').default} Replace + * @typedef {import('diagram-js/lib/features/rules/Rules').default} Rules + * + * @typedef {import('../../model/Types').Element} Element + * @typedef {import('../../model/Types').Shape} Shape + * @typedef {import('../../model/Types').ModdleElement} ModdleElement + * + * @typedef { { + * type: string; + * cancelActivity: boolean; + * instantiate: boolean; + * eventGatewayType: string; + * triggeredByEvent: boolean; + * isInterrupting: boolean; + * collapsed: boolean; + * isExpanded: boolean; + * eventDefinitionType: string; + * eventDefinitionAttrs: Object; + * host: Shape; + * } } TargetElement + * + * @typedef { { + * moveChildren: boolean; + * } & Record } Hints + */ + +function copyProperties(source, target, properties) { + if (!isArray$4(properties)) { + properties = [ properties ]; + } + + forEach$2(properties, function(property) { + if (!isUndefined$3(source[property])) { + target[property] = source[property]; + } + }); +} + + +var CUSTOM_PROPERTIES = [ + 'cancelActivity', + 'instantiate', + 'eventGatewayType', + 'triggeredByEvent', + 'isInterrupting' +]; + +/** + * Check if element should be collapsed or expanded. + */ +function shouldToggleCollapsed(element, targetElement) { + + var oldCollapsed = ( + element && has$2(element, 'collapsed') ? element.collapsed : !isExpanded(element) + ); + + var targetCollapsed; + + if (targetElement && (has$2(targetElement, 'collapsed') || has$2(targetElement, 'isExpanded'))) { + + // property is explicitly set so use it + targetCollapsed = ( + has$2(targetElement, 'collapsed') ? targetElement.collapsed : !targetElement.isExpanded + ); + } else { + + // keep old state + targetCollapsed = oldCollapsed; + } + + if (oldCollapsed !== targetCollapsed) { + return true; + } + + return false; +} + + +/** + * BPMN-specific replace. + * + * @param {BpmnFactory} bpmnFactory + * @param {ElementFactory} elementFactory + * @param {ModdleCopy} moddleCopy + * @param {Modeling} modeling + * @param {Replace} replace + * @param {Rules} rules + */ +function BpmnReplace( + bpmnFactory, + elementFactory, + moddleCopy, + modeling, + replace, + rules +) { + + /** + * Prepares a new business object for the replacement element + * and triggers the replace operation. + * + * @param {Element} element + * @param {TargetElement} targetElement + * @param {Hints} [hints] + * + * @return {Element} + */ + function replaceElement(element, targetElement, hints) { + + hints = hints || {}; + + var type = targetElement.type, + oldBusinessObject = element.businessObject; + + if (isSubProcess(oldBusinessObject) && type === 'bpmn:SubProcess') { + if (shouldToggleCollapsed(element, targetElement)) { + + // expanding or collapsing process + modeling.toggleCollapse(element); + + return element; + } + } + + var newBusinessObject = bpmnFactory.create(type); + + var newElement = { + type: type, + businessObject: newBusinessObject, + }; + + newElement.di = {}; + + // colors will be set to DI + copyProperties(element.di, newElement.di, [ + 'fill', + 'stroke', + 'background-color', + 'border-color', + 'color' + ]); + + var elementProps = getPropertyNames(oldBusinessObject.$descriptor), + newElementProps = getPropertyNames(newBusinessObject.$descriptor, true), + copyProps = intersection(elementProps, newElementProps); + + // initialize special properties defined in target definition + assign$3(newBusinessObject, pick(targetElement, CUSTOM_PROPERTIES)); + + var properties = filter(copyProps, function(propertyName) { + + // copying event definitions, unless we replace + if (propertyName === 'eventDefinitions') { + return hasEventDefinition(element, targetElement.eventDefinitionType); + } + + // retain loop characteristics if the target element + // is not an event sub process + if (propertyName === 'loopCharacteristics') { + return !isEventSubProcess(newBusinessObject); + } + + // so the applied properties from 'target' don't get lost + if (has$2(newBusinessObject, propertyName)) { + return false; + } + + if (propertyName === 'processRef' && targetElement.isExpanded === false) { + return false; + } + + if (propertyName === 'triggeredByEvent') { + return false; + } + + return true; + }); + + newBusinessObject = moddleCopy.copyElement( + oldBusinessObject, + newBusinessObject, + properties + ); + + // initialize custom BPMN extensions + if (targetElement.eventDefinitionType) { + + // only initialize with new eventDefinition + // if we did not set an event definition yet, + // i.e. because we copied it + if (!hasEventDefinition(newBusinessObject, targetElement.eventDefinitionType)) { + newElement.eventDefinitionType = targetElement.eventDefinitionType; + newElement.eventDefinitionAttrs = targetElement.eventDefinitionAttrs; + } + } + + if (is$2(oldBusinessObject, 'bpmn:Activity')) { + + if (isSubProcess(oldBusinessObject)) { + + // no toggeling, so keep old state + newElement.isExpanded = isExpanded(element); + } + + // else if property is explicitly set, use it + else if (targetElement && has$2(targetElement, 'isExpanded')) { + newElement.isExpanded = targetElement.isExpanded; + + // assign default size of new expanded element + var defaultSize = elementFactory.getDefaultSize(newBusinessObject, { + isExpanded: newElement.isExpanded + }); + + newElement.width = defaultSize.width; + newElement.height = defaultSize.height; + + // keep element centered + newElement.x = element.x - (newElement.width - element.width) / 2; + newElement.y = element.y - (newElement.height - element.height) / 2; + } + + // TODO: need also to respect min/max Size + // copy size, from an expanded subprocess to an expanded alternative subprocess + // except bpmn:Task, because Task is always expanded + if ((isExpanded(element) && !is$2(oldBusinessObject, 'bpmn:Task')) && newElement.isExpanded) { + newElement.width = element.width; + newElement.height = element.height; + } + } + + // remove children if not expanding sub process + if (isSubProcess(oldBusinessObject) && !isSubProcess(newBusinessObject)) { + hints.moveChildren = false; + } + + // transform collapsed/expanded pools + if (is$2(oldBusinessObject, 'bpmn:Participant')) { + + // create expanded pool + if (targetElement.isExpanded === true) { + newBusinessObject.processRef = bpmnFactory.create('bpmn:Process'); + } else { + + // remove children when transforming to collapsed pool + hints.moveChildren = false; + } + + // apply same width and default height + newElement.width = element.width; + newElement.height = elementFactory.getDefaultSize(newElement).height; + } + + if (!rules.allowed('shape.resize', { shape: newBusinessObject })) { + newElement.height = elementFactory.getDefaultSize(newElement).height; + newElement.width = elementFactory.getDefaultSize(newElement).width; + } + + newBusinessObject.name = oldBusinessObject.name; + + // retain default flow's reference between inclusive <-> exclusive gateways and activities + if ( + isAny(oldBusinessObject, [ + 'bpmn:ExclusiveGateway', + 'bpmn:InclusiveGateway', + 'bpmn:Activity' + ]) && + isAny(newBusinessObject, [ + 'bpmn:ExclusiveGateway', + 'bpmn:InclusiveGateway', + 'bpmn:Activity' + ]) + ) { + newBusinessObject.default = oldBusinessObject.default; + } + + if ( + targetElement.host && + !is$2(oldBusinessObject, 'bpmn:BoundaryEvent') && + is$2(newBusinessObject, 'bpmn:BoundaryEvent') + ) { + newElement.host = targetElement.host; + } + + // The DataStoreReference element is 14px wider than the DataObjectReference element + // This ensures that they stay centered on the x axis when replaced + if ( + newElement.type === 'bpmn:DataStoreReference' || + newElement.type === 'bpmn:DataObjectReference' + ) { + newElement.x = element.x + (element.width - newElement.width) / 2; + } + + return replace.replaceElement(element, newElement, hints); + } + + this.replaceElement = replaceElement; +} + +BpmnReplace.$inject = [ + 'bpmnFactory', + 'elementFactory', + 'moddleCopy', + 'modeling', + 'replace', + 'rules' +]; + +/** + * @param {ModdleElement} businessObject + * + * @return {boolean} + */ +function isSubProcess(businessObject) { + return is$2(businessObject, 'bpmn:SubProcess'); +} + +/** + * @param {Element|ModdleElement} element + * @param {string} type + * + * @return {boolean} + */ +function hasEventDefinition(element, type) { + var businessObject = getBusinessObject(element); + + return type && businessObject.get('eventDefinitions').some(function(definition) { + return is$2(definition, type); + }); +} + +/** + * Compute intersection between two arrays. + * + * @param {Array} a + * @param {Array} b + * + * @return {Array} + */ +function intersection(a, b) { + return a.filter(function(item) { + return b.includes(item); + }); +} + +var ReplaceModule = { + __depends__: [ + CopyPasteModule, + ReplaceModule$1, + SelectionModule + ], + bpmnReplace: [ 'type', BpmnReplace ] +}; + +/** + * @typedef {import('../dragging/Dragging').default} Dragging + * @typedef {import('../../core/EventBus').default} EventBus + * + * @typedef {import('../../core/EventBus').Event} Event + */ + +var LOW_PRIORITY$9 = 250; + +/** + * The tool manager acts as middle-man between the available tool's and the Palette, + * it takes care of making sure that the correct active state is set. + * + * @param {EventBus} eventBus + * @param {Dragging} dragging + */ +function ToolManager(eventBus, dragging) { + this._eventBus = eventBus; + this._dragging = dragging; + + this._tools = []; + this._active = null; +} + +ToolManager.$inject = [ 'eventBus', 'dragging' ]; + +/** + * Register a tool. + * + * @param {string} name + * @param { { + * dragging: string; + * tool: string; + * } } events + */ +ToolManager.prototype.registerTool = function(name, events) { + var tools = this._tools; + + if (!events) { + throw new Error('A tool has to be registered with it\'s "events"'); + } + + tools.push(name); + + this.bindEvents(name, events); +}; + +ToolManager.prototype.isActive = function(tool) { + return tool && this._active === tool; +}; + +ToolManager.prototype.length = function(tool) { + return this._tools.length; +}; + +ToolManager.prototype.setActive = function(tool) { + var eventBus = this._eventBus; + + if (this._active !== tool) { + this._active = tool; + + eventBus.fire('tool-manager.update', { tool: tool }); + } +}; + +ToolManager.prototype.bindEvents = function(name, events) { + var eventBus = this._eventBus, + dragging = this._dragging; + + var eventsToRegister = []; + + eventBus.on(events.tool + '.init', function(event) { + var context = event.context; + + // Active tools that want to reactivate themselves must do this explicitly + if (!context.reactivate && this.isActive(name)) { + this.setActive(null); + + dragging.cancel(); + return; + } + + this.setActive(name); + + }, this); + + // TODO: add test cases + forEach$2(events, function(event) { + eventsToRegister.push(event + '.ended'); + eventsToRegister.push(event + '.canceled'); + }); + + eventBus.on(eventsToRegister, LOW_PRIORITY$9, function(event) { + + // We defer the de-activation of the tool to the .activate phase, + // so we're able to check if we want to toggle off the current + // active tool or switch to a new one + if (!this._active) { + return; + } + + if (isPaletteClick(event)) { + return; + } + + this.setActive(null); + }, this); + +}; + + +// helpers /////////////// + +/** + * Check if a given event is a palette click event. + * + * @param {Event} event + * + * @return {boolean} + */ +function isPaletteClick(event) { + var target = event.originalEvent && event.originalEvent.target; + + return target && closest(target, '.group[data-group="tools"]'); +} + +/** + * @type { import('didi').ModuleDeclaration } + */ +var ToolManagerModule = { + __depends__: [ + DraggingModule + ], + __init__: [ 'toolManager' ], + toolManager: [ 'type', ToolManager ] +}; + +/** + * @typedef {import('../../core/Types').ConnectionLike} Connection + * @typedef {import('../../core/Types').ShapeLike} Shape + * + * @typedef {import('../../util/Types').Axis} Axis + * @typedef {import('../../util/Types').Direction} Direction + * @typedef {import('../../util/Types').Point} Point + * @typedef {import('../../util/Types').Rect} Rect + */ + + +/** + * Return direction given axis and delta. + * + * @param {Axis} axis + * @param {number} delta + * + * @return {Direction} + */ +function getDirection(axis, delta) { + + if (axis === 'x') { + if (delta > 0) { + return 'e'; + } + + if (delta < 0) { + return 'w'; + } + } + + if (axis === 'y') { + if (delta > 0) { + return 's'; + } + + if (delta < 0) { + return 'n'; + } + } + + return null; +} + +/** + * Returns connections whose waypoints are to be updated. Waypoints are to be updated if start + * or end is to be moved or resized. + * + * @param {Array} movingShapes + * @param {Array} resizingShapes + * + * @return {Array} + */ +function getWaypointsUpdatingConnections(movingShapes, resizingShapes) { + var waypointsUpdatingConnections = []; + + forEach$2(movingShapes.concat(resizingShapes), function(shape) { + var incoming = shape.incoming, + outgoing = shape.outgoing; + + forEach$2(incoming.concat(outgoing), function(connection) { + var source = connection.source, + target = connection.target; + + if (includes$3(movingShapes, source) || + includes$3(movingShapes, target) || + includes$3(resizingShapes, source) || + includes$3(resizingShapes, target)) { + + if (!includes$3(waypointsUpdatingConnections, connection)) { + waypointsUpdatingConnections.push(connection); + } + } + }); + }); + + return waypointsUpdatingConnections; +} + +function includes$3(array, item) { + return array.indexOf(item) !== -1; +} + +/** + * Resize bounds. + * + * @param {Rect} bounds + * @param {Direction} direction + * @param {Point} delta + * + * @return {Rect} + */ +function resizeBounds(bounds, direction, delta) { + var x = bounds.x, + y = bounds.y, + width = bounds.width, + height = bounds.height, + dx = delta.x, + dy = delta.y; + + switch (direction) { + case 'n': + return { + x: x, + y: y + dy, + width: width, + height: height - dy + }; + case 's': + return { + x: x, + y: y, + width: width, + height: height + dy + }; + case 'w': + return { + x: x + dx, + y: y, + width: width - dx, + height: height + }; + case 'e': + return { + x: x, + y: y, + width: width + dx, + height: height + }; + default: + throw new Error('unknown direction: ' + direction); + } +} + +/** + * @typedef {import('../../core/Types').ShapeLike} Shape + * + * @typedef {import('../../core/Canvas').default} Canvas + * @typedef {import('../dragging/Dragging').default} Dragging + * @typedef {import('../../core/EventBus').default} EventBus + * @typedef {import('../modeling/Modeling').default} Modeling + * @typedef {import('../mouse/Mouse').default} Mouse + * @typedef {import('../rules/Rules').default} Rules + * @typedef {import('../tool-manager/ToolManager').default} ToolManager + * + * @typedef {import('../../util/Types').Axis} Axis + * @typedef {import('../../util/Types').Direction} Direction + * @typedef {import('../../util/Types').Point} Point + */ + +var abs = Math.abs, + round$5 = Math.round; + +var AXIS_TO_DIMENSION = { + x: 'width', + y: 'height' +}; + +var CURSOR_CROSSHAIR = 'crosshair'; + +var DIRECTION_TO_TRBL = { + n: 'top', + w: 'left', + s: 'bottom', + e: 'right' +}; + +var HIGH_PRIORITY$6 = 1500; + +var DIRECTION_TO_OPPOSITE = { + n: 's', + w: 'e', + s: 'n', + e: 'w' +}; + +var PADDING = 20; + + +/** + * Add or remove space by moving and resizing elements. + * + * @param {Canvas} canvas + * @param {Dragging} dragging + * @param {EventBus} eventBus + * @param {Modeling} modeling + * @param {Rules} rules + * @param {ToolManager} toolManager + * @param {Mouse} mouse + */ +function SpaceTool( + canvas, dragging, eventBus, + modeling, rules, toolManager, + mouse) { + + this._canvas = canvas; + this._dragging = dragging; + this._eventBus = eventBus; + this._modeling = modeling; + this._rules = rules; + this._toolManager = toolManager; + this._mouse = mouse; + + var self = this; + + toolManager.registerTool('space', { + tool: 'spaceTool.selection', + dragging: 'spaceTool' + }); + + eventBus.on('spaceTool.selection.end', function(event) { + eventBus.once('spaceTool.selection.ended', function() { + self.activateMakeSpace(event.originalEvent); + }); + }); + + eventBus.on('spaceTool.move', HIGH_PRIORITY$6 , function(event) { + var context = event.context, + initialized = context.initialized; + + if (!initialized) { + initialized = context.initialized = self.init(event, context); + } + + if (initialized) { + ensureConstraints(event); + } + }); + + eventBus.on('spaceTool.end', function(event) { + var context = event.context, + axis = context.axis, + direction = context.direction, + movingShapes = context.movingShapes, + resizingShapes = context.resizingShapes, + start = context.start; + + if (!context.initialized) { + return; + } + + ensureConstraints(event); + + var delta = { + x: 0, + y: 0 + }; + + delta[ axis ] = round$5(event[ 'd' + axis ]); + + self.makeSpace(movingShapes, resizingShapes, delta, direction, start); + + eventBus.once('spaceTool.ended', function(event) { + + // activate space tool selection after make space + self.activateSelection(event.originalEvent, true, true); + }); + }); +} + +SpaceTool.$inject = [ + 'canvas', + 'dragging', + 'eventBus', + 'modeling', + 'rules', + 'toolManager', + 'mouse' +]; + +/** + * Activate space tool selection. + * + * @param {MouseEvent|TouchEvent} event + * @param {boolean} autoActivate + * @param {boolean} reactivate + */ +SpaceTool.prototype.activateSelection = function(event, autoActivate, reactivate) { + this._dragging.init(event, 'spaceTool.selection', { + autoActivate: autoActivate, + cursor: CURSOR_CROSSHAIR, + data: { + context: { + reactivate: reactivate + } + }, + trapClick: false + }); +}; + +/** + * Activate space tool make space. + * + * @param {MouseEvent|TouchEvent} event + */ +SpaceTool.prototype.activateMakeSpace = function(event) { + this._dragging.init(event, 'spaceTool', { + autoActivate: true, + cursor: CURSOR_CROSSHAIR, + data: { + context: {} + } + }); +}; + +/** + * Make space. + * + * @param {Array} movingShapes + * @param {Array} resizingShapes + * @param {Point} delta + * @param {Direction} direction + * @param {number} start + */ +SpaceTool.prototype.makeSpace = function(movingShapes, resizingShapes, delta, direction, start) { + return this._modeling.createSpace(movingShapes, resizingShapes, delta, direction, start); +}; + +/** + * Initialize make space and return true if that was successful. + * + * @param {MouseEvent|TouchEvent} event + * @param {Object} context + * + * @return {boolean} + */ +SpaceTool.prototype.init = function(event, context) { + var axis = abs(event.dx) > abs(event.dy) ? 'x' : 'y', + delta = event[ 'd' + axis ], + start = event[ axis ] - delta; + + if (abs(delta) < 5) { + return false; + } + + // invert delta to remove space when moving left + if (delta < 0) { + delta *= -1; + } + + // invert delta to add/remove space when removing/adding space if modifier key is pressed + if (hasPrimaryModifier(event)) { + delta *= -1; + } + + var direction = getDirection(axis, delta); + + var root = this._canvas.getRootElement(); + + var children = selfAndAllChildren(root, true); + + var elements = this.calculateAdjustments(children, axis, delta, start); + + var minDimensions = this._eventBus.fire('spaceTool.getMinDimensions', { + axis: axis, + direction: direction, + shapes: elements.resizingShapes, + start: start + }); + + var spaceToolConstraints = getSpaceToolConstraints(elements, axis, direction, start, minDimensions); + + assign$3( + context, + elements, + { + axis: axis, + direction: direction, + spaceToolConstraints: spaceToolConstraints, + start: start + } + ); + + set$1('resize-' + (axis === 'x' ? 'ew' : 'ns')); + + return true; +}; + +/** + * Get elements to be moved and resized. + * + * @param {Array} elements + * @param {Axis} axis + * @param {Point} delta + * @param {number} start + * + * @return {Object} + */ +SpaceTool.prototype.calculateAdjustments = function(elements, axis, delta, start) { + var rules = this._rules; + + var movingShapes = [], + resizingShapes = []; + + var attachers = [], + connections = []; + + function moveShape(shape) { + if (!movingShapes.includes(shape)) { + movingShapes.push(shape); + } + + var label = shape.label; + + // move external label if its label target is moving + if (label && !movingShapes.includes(label)) { + movingShapes.push(label); + } + } + + function resizeShape(shape) { + if (!resizingShapes.includes(shape)) { + resizingShapes.push(shape); + } + } + + forEach$2(elements, function(element) { + if (!element.parent || isLabel(element)) { + return; + } + + // handle connections separately + if (isConnection(element)) { + connections.push(element); + + return; + } + + var shapeStart = element[ axis ], + shapeEnd = shapeStart + element[ AXIS_TO_DIMENSION[ axis ] ]; + + // handle attachers separately + if (isAttacher$1(element) + && ((delta > 0 && getMid$2(element)[ axis ] > start) + || (delta < 0 && getMid$2(element)[ axis ] < start))) { + attachers.push(element); + + return; + } + + // move shape if its start is after space tool + if ((delta > 0 && shapeStart > start) + || (delta < 0 && shapeEnd < start)) { + moveShape(element); + + return; + } + + // resize shape if it's resizable and its start is before and its end is after space tool + if (shapeStart < start + && shapeEnd > start + && rules.allowed('shape.resize', { shape: element }) + ) { + resizeShape(element); + + return; + } + }); + + // move attacher if its host is moving + forEach$2(movingShapes, function(shape) { + var attachers = shape.attachers; + + if (attachers) { + forEach$2(attachers, function(attacher) { + moveShape(attacher); + }); + } + }); + + var allShapes = movingShapes.concat(resizingShapes); + + // move attacher if its mid is after space tool and its host is moving or resizing + forEach$2(attachers, function(attacher) { + var host = attacher.host; + + if (includes$2(allShapes, host)) { + moveShape(attacher); + } + }); + + allShapes = movingShapes.concat(resizingShapes); + + // move external label if its label target's (connection) source and target are moving + forEach$2(connections, function(connection) { + var source = connection.source, + target = connection.target, + label = connection.label; + + if (includes$2(allShapes, source) + && includes$2(allShapes, target) + && label) { + moveShape(label); + } + }); + + return { + movingShapes: movingShapes, + resizingShapes: resizingShapes + }; +}; + +SpaceTool.prototype.toggle = function() { + + if (this.isActive()) { + return this._dragging.cancel(); + } + + var mouseEvent = this._mouse.getLastMoveEvent(); + + this.activateSelection(mouseEvent, !!mouseEvent); +}; + +SpaceTool.prototype.isActive = function() { + var context = this._dragging.context(); + + if (context) { + return /^spaceTool/.test(context.prefix); + } + + return false; +}; + +// helpers ////////// + +function addPadding(trbl) { + return { + top: trbl.top - PADDING, + right: trbl.right + PADDING, + bottom: trbl.bottom + PADDING, + left: trbl.left - PADDING + }; +} + +function ensureConstraints(event) { + var context = event.context, + spaceToolConstraints = context.spaceToolConstraints; + + if (!spaceToolConstraints) { + return; + } + + var x, y; + + if (isNumber(spaceToolConstraints.left)) { + x = Math.max(event.x, spaceToolConstraints.left); + + event.dx = event.dx + x - event.x; + event.x = x; + } + + if (isNumber(spaceToolConstraints.right)) { + x = Math.min(event.x, spaceToolConstraints.right); + + event.dx = event.dx + x - event.x; + event.x = x; + } + + if (isNumber(spaceToolConstraints.top)) { + y = Math.max(event.y, spaceToolConstraints.top); + + event.dy = event.dy + y - event.y; + event.y = y; + } + + if (isNumber(spaceToolConstraints.bottom)) { + y = Math.min(event.y, spaceToolConstraints.bottom); + + event.dy = event.dy + y - event.y; + event.y = y; + } +} + +function getSpaceToolConstraints(elements, axis, direction, start, minDimensions) { + var movingShapes = elements.movingShapes, + resizingShapes = elements.resizingShapes; + + if (!resizingShapes.length) { + return; + } + + var spaceToolConstraints = {}, + min, + max; + + forEach$2(resizingShapes, function(resizingShape) { + var attachers = resizingShape.attachers, + children = resizingShape.children; + + var resizingShapeBBox = asTRBL(resizingShape); + + // find children that are not moving or resizing + var nonMovingResizingChildren = filter(children, function(child) { + return !isConnection(child) && + !isLabel(child) && + !includes$2(movingShapes, child) && + !includes$2(resizingShapes, child); + }); + + // find children that are moving + var movingChildren = filter(children, function(child) { + return !isConnection(child) && !isLabel(child) && includes$2(movingShapes, child); + }); + + var minOrMax, + nonMovingResizingChildrenBBox, + movingChildrenBBox, + movingAttachers = [], + nonMovingAttachers = [], + movingAttachersBBox, + movingAttachersConstraint, + nonMovingAttachersBBox, + nonMovingAttachersConstraint; + + if (nonMovingResizingChildren.length) { + nonMovingResizingChildrenBBox = addPadding(asTRBL(getBBox(nonMovingResizingChildren))); + + minOrMax = start - + resizingShapeBBox[ DIRECTION_TO_TRBL[ direction ] ] + + nonMovingResizingChildrenBBox[ DIRECTION_TO_TRBL[ direction ] ]; + + if (direction === 'n') { + spaceToolConstraints.bottom = max = isNumber(max) ? Math.min(max, minOrMax) : minOrMax; + } else if (direction === 'w') { + spaceToolConstraints.right = max = isNumber(max) ? Math.min(max, minOrMax) : minOrMax; + } else if (direction === 's') { + spaceToolConstraints.top = min = isNumber(min) ? Math.max(min, minOrMax) : minOrMax; + } else if (direction === 'e') { + spaceToolConstraints.left = min = isNumber(min) ? Math.max(min, minOrMax) : minOrMax; + } + } + + if (movingChildren.length) { + movingChildrenBBox = addPadding(asTRBL(getBBox(movingChildren))); + + minOrMax = start - + movingChildrenBBox[ DIRECTION_TO_TRBL[ DIRECTION_TO_OPPOSITE[ direction ] ] ] + + resizingShapeBBox[ DIRECTION_TO_TRBL[ DIRECTION_TO_OPPOSITE[ direction ] ] ]; + + if (direction === 'n') { + spaceToolConstraints.bottom = max = isNumber(max) ? Math.min(max, minOrMax) : minOrMax; + } else if (direction === 'w') { + spaceToolConstraints.right = max = isNumber(max) ? Math.min(max, minOrMax) : minOrMax; + } else if (direction === 's') { + spaceToolConstraints.top = min = isNumber(min) ? Math.max(min, minOrMax) : minOrMax; + } else if (direction === 'e') { + spaceToolConstraints.left = min = isNumber(min) ? Math.max(min, minOrMax) : minOrMax; + } + } + + if (attachers && attachers.length) { + attachers.forEach(function(attacher) { + if (includes$2(movingShapes, attacher)) { + movingAttachers.push(attacher); + } else { + nonMovingAttachers.push(attacher); + } + }); + + if (movingAttachers.length) { + movingAttachersBBox = asTRBL(getBBox(movingAttachers.map(getMid$2))); + + movingAttachersConstraint = resizingShapeBBox[ DIRECTION_TO_TRBL[ DIRECTION_TO_OPPOSITE[ direction ] ] ] + - (movingAttachersBBox[ DIRECTION_TO_TRBL[ DIRECTION_TO_OPPOSITE[ direction ] ] ] - start); + } + + if (nonMovingAttachers.length) { + nonMovingAttachersBBox = asTRBL(getBBox(nonMovingAttachers.map(getMid$2))); + + nonMovingAttachersConstraint = nonMovingAttachersBBox[ DIRECTION_TO_TRBL[ direction ] ] + - (resizingShapeBBox[ DIRECTION_TO_TRBL[ direction ] ] - start); + } + + if (direction === 'n') { + minOrMax = Math.min(movingAttachersConstraint || Infinity, nonMovingAttachersConstraint || Infinity); + + spaceToolConstraints.bottom = max = isNumber(max) ? Math.min(max, minOrMax) : minOrMax; + } else if (direction === 'w') { + minOrMax = Math.min(movingAttachersConstraint || Infinity, nonMovingAttachersConstraint || Infinity); + + spaceToolConstraints.right = max = isNumber(max) ? Math.min(max, minOrMax) : minOrMax; + } else if (direction === 's') { + minOrMax = Math.max(movingAttachersConstraint || -Infinity, nonMovingAttachersConstraint || -Infinity); + + spaceToolConstraints.top = min = isNumber(min) ? Math.max(min, minOrMax) : minOrMax; + } else if (direction === 'e') { + minOrMax = Math.max(movingAttachersConstraint || -Infinity, nonMovingAttachersConstraint || -Infinity); + + spaceToolConstraints.left = min = isNumber(min) ? Math.max(min, minOrMax) : minOrMax; + } + } + + var resizingShapeMinDimensions = minDimensions && minDimensions[ resizingShape.id ]; + + if (resizingShapeMinDimensions) { + + if (direction === 'n') { + minOrMax = start + + resizingShape[ AXIS_TO_DIMENSION [ axis ] ] - + resizingShapeMinDimensions[ AXIS_TO_DIMENSION[ axis ] ]; + + spaceToolConstraints.bottom = max = isNumber(max) ? Math.min(max, minOrMax) : minOrMax; + } else if (direction === 'w') { + minOrMax = start + + resizingShape[ AXIS_TO_DIMENSION [ axis ] ] - + resizingShapeMinDimensions[ AXIS_TO_DIMENSION[ axis ] ]; + + spaceToolConstraints.right = max = isNumber(max) ? Math.min(max, minOrMax) : minOrMax; + } else if (direction === 's') { + minOrMax = start - + resizingShape[ AXIS_TO_DIMENSION [ axis ] ] + + resizingShapeMinDimensions[ AXIS_TO_DIMENSION[ axis ] ]; + + spaceToolConstraints.top = min = isNumber(min) ? Math.max(min, minOrMax) : minOrMax; + } else if (direction === 'e') { + minOrMax = start - + resizingShape[ AXIS_TO_DIMENSION [ axis ] ] + + resizingShapeMinDimensions[ AXIS_TO_DIMENSION[ axis ] ]; + + spaceToolConstraints.left = min = isNumber(min) ? Math.max(min, minOrMax) : minOrMax; + } + } + }); + + return spaceToolConstraints; +} + +function includes$2(array, item) { + return array.indexOf(item) !== -1; +} + +function isAttacher$1(element) { + return !!element.host; +} + +var MARKER_DRAGGING = 'djs-dragging', + MARKER_RESIZING = 'djs-resizing'; + +var LOW_PRIORITY$8 = 250; + +/** + * @typedef {import('../../core/Canvas').default} Canvas + * @typedef {import('../../core/ElementRegistry').default} ElementRegistry + * @typedef {import('../../core/EventBus').default} EventBus + * @typedef {import('../../draw/Styles').default} Styles + */ + +var max$2 = Math.max; + + +/** + * Provides previews for selecting/moving/resizing shapes when creating/removing space. + * + * @param {EventBus} eventBus + * @param {ElementRegistry} elementRegistry + * @param {Canvas} canvas + * @param {Styles} styles + */ +function SpaceToolPreview( + eventBus, elementRegistry, canvas, + styles, previewSupport) { + + function addPreviewGfx(collection, dragGroup) { + forEach$2(collection, function(element) { + previewSupport.addDragger(element, dragGroup); + + canvas.addMarker(element, MARKER_DRAGGING); + }); + } + + // add crosshair + eventBus.on('spaceTool.selection.start', function(event) { + var space = canvas.getLayer('space'), + context = event.context; + + var orientation = { + x: 'M 0,-10000 L 0,10000', + y: 'M -10000,0 L 10000,0' + }; + + var crosshairGroup = create$2('g'); + attr$1(crosshairGroup, styles.cls('djs-crosshair-group', [ 'no-events' ])); + + append(space, crosshairGroup); + + // horizontal path + var pathX = create$2('path'); + attr$1(pathX, 'd', orientation.x); + classes(pathX).add('djs-crosshair'); + + append(crosshairGroup, pathX); + + // vertical path + var pathY = create$2('path'); + attr$1(pathY, 'd', orientation.y); + classes(pathY).add('djs-crosshair'); + + append(crosshairGroup, pathY); + + context.crosshairGroup = crosshairGroup; + }); + + // update crosshair + eventBus.on('spaceTool.selection.move', function(event) { + var crosshairGroup = event.context.crosshairGroup; + + translate(crosshairGroup, event.x, event.y); + }); + + // remove crosshair + eventBus.on('spaceTool.selection.cleanup', function(event) { + var context = event.context, + crosshairGroup = context.crosshairGroup; + + if (crosshairGroup) { + remove(crosshairGroup); + } + }); + + // add and update move/resize previews + eventBus.on('spaceTool.move', LOW_PRIORITY$8, function(event) { + + var context = event.context, + line = context.line, + axis = context.axis, + movingShapes = context.movingShapes, + resizingShapes = context.resizingShapes; + + if (!context.initialized) { + return; + } + + if (!context.dragGroup) { + var spaceLayer = canvas.getLayer('space'); + + line = create$2('path'); + attr$1(line, 'd', 'M0,0 L0,0'); + classes(line).add('djs-crosshair'); + + append(spaceLayer, line); + + context.line = line; + + var dragGroup = create$2('g'); + attr$1(dragGroup, styles.cls('djs-drag-group', [ 'no-events' ])); + + append(canvas.getActiveLayer(), dragGroup); + + // shapes + addPreviewGfx(movingShapes, dragGroup); + + // connections + var movingConnections = context.movingConnections = elementRegistry.filter(function(element) { + var sourceIsMoving = false; + + forEach$2(movingShapes, function(shape) { + forEach$2(shape.outgoing, function(connection) { + if (element === connection) { + sourceIsMoving = true; + } + }); + }); + + var targetIsMoving = false; + + forEach$2(movingShapes, function(shape) { + forEach$2(shape.incoming, function(connection) { + if (element === connection) { + targetIsMoving = true; + } + }); + }); + + var sourceIsResizing = false; + + forEach$2(resizingShapes, function(shape) { + forEach$2(shape.outgoing, function(connection) { + if (element === connection) { + sourceIsResizing = true; + } + }); + }); + + var targetIsResizing = false; + + forEach$2(resizingShapes, function(shape) { + forEach$2(shape.incoming, function(connection) { + if (element === connection) { + targetIsResizing = true; + } + }); + }); + + return isConnection(element) + && (sourceIsMoving || sourceIsResizing) + && (targetIsMoving || targetIsResizing); + }); + + + addPreviewGfx(movingConnections, dragGroup); + + context.dragGroup = dragGroup; + } + + if (!context.frameGroup) { + var frameGroup = create$2('g'); + attr$1(frameGroup, styles.cls('djs-frame-group', [ 'no-events' ])); + + append(canvas.getActiveLayer(), frameGroup); + + var frames = []; + + forEach$2(resizingShapes, function(shape) { + var frame = previewSupport.addFrame(shape, frameGroup); + + var initialBounds = frame.getBBox(); + + frames.push({ + element: frame, + initialBounds: initialBounds + }); + + canvas.addMarker(shape, MARKER_RESIZING); + }); + + context.frameGroup = frameGroup; + context.frames = frames; + } + + var orientation = { + x: 'M' + event.x + ', -10000 L' + event.x + ', 10000', + y: 'M -10000, ' + event.y + ' L 10000, ' + event.y + }; + + attr$1(line, { d: orientation[ axis ] }); + + var opposite = { x: 'y', y: 'x' }; + var delta = { x: event.dx, y: event.dy }; + delta[ opposite[ context.axis ] ] = 0; + + // update move previews + translate(context.dragGroup, delta.x, delta.y); + + // update resize previews + forEach$2(context.frames, function(frame) { + var element = frame.element, + initialBounds = frame.initialBounds, + width, + height; + + if (context.direction === 'e') { + attr$1(element, { + width: max$2(initialBounds.width + delta.x, 5) + }); + } else { + width = max$2(initialBounds.width - delta.x, 5); + + attr$1(element, { + width: width, + x: initialBounds.x + initialBounds.width - width + }); + } + + if (context.direction === 's') { + attr$1(element, { + height: max$2(initialBounds.height + delta.y, 5) + }); + } else { + height = max$2(initialBounds.height - delta.y, 5); + + attr$1(element, { + height: height, + y: initialBounds.y + initialBounds.height - height + }); + } + }); + + }); + + // remove move/resize previews + eventBus.on('spaceTool.cleanup', function(event) { + + var context = event.context, + movingShapes = context.movingShapes, + movingConnections = context.movingConnections, + resizingShapes = context.resizingShapes, + line = context.line, + dragGroup = context.dragGroup, + frameGroup = context.frameGroup; + + // moving shapes + forEach$2(movingShapes, function(shape) { + canvas.removeMarker(shape, MARKER_DRAGGING); + }); + + // moving connections + forEach$2(movingConnections, function(connection) { + canvas.removeMarker(connection, MARKER_DRAGGING); + }); + + if (dragGroup) { + remove(line); + remove(dragGroup); + } + + forEach$2(resizingShapes, function(shape) { + canvas.removeMarker(shape, MARKER_RESIZING); + }); + + if (frameGroup) { + remove(frameGroup); + } + }); +} + +SpaceToolPreview.$inject = [ + 'eventBus', + 'elementRegistry', + 'canvas', + 'styles', + 'previewSupport' +]; + +/** + * @type { import('didi').ModuleDeclaration } + */ +var SpaceToolModule$1 = { + __init__: [ 'spaceToolPreview' ], + __depends__: [ + DraggingModule, + RulesModule$1, + ToolManagerModule, + PreviewSupportModule, + MouseModule + ], + spaceTool: [ 'type', SpaceTool ], + spaceToolPreview: [ 'type', SpaceToolPreview ] +}; + +/** + * @typedef {import('didi').Injector} Injector + * + * @typedef {import('../../model/Types').Shape} Shape + * + * @typedef {import('diagram-js/lib/util/Types').Axis} Axis + * @typedef {import('diagram-js/lib/util/Types').Point} Point + */ + +/** + * @param {Injector} injector + */ +function BpmnSpaceTool(injector) { + injector.invoke(SpaceTool, this); +} + +BpmnSpaceTool.$inject = [ + 'injector' +]; + +e(BpmnSpaceTool, SpaceTool); + +/** + * @param {Shape[]} elements + * @param {Axis} axis + * @param {Point} delta + * @param {number} start + * + * @return {Object} + */ +BpmnSpaceTool.prototype.calculateAdjustments = function(elements, axis, delta, start) { + var adjustments = SpaceTool.prototype.calculateAdjustments.call(this, elements, axis, delta, start); + + // do not resize text annotations + adjustments.resizingShapes = adjustments.resizingShapes.filter(function(shape) { + return !is$2(shape, 'bpmn:TextAnnotation'); + }); + + return adjustments; +}; + +var SpaceToolModule = { + __depends__: [ SpaceToolModule$1 ], + spaceTool: [ 'type', BpmnSpaceTool ] +}; + +/** + * @typedef {import('didi').Injector} Injector + * + * @typedef {import('../core/Types').ElementLike} ElementLike + * + * @typedef {import('../core/EventBus').default} EventBus + * @typedef {import('./CommandHandler').default} CommandHandler + * + * @typedef { any } CommandContext + * @typedef { { + * new (...args: any[]) : CommandHandler + * } } CommandHandlerConstructor + * @typedef { { + * [key: string]: CommandHandler; + * } } CommandHandlerMap + * @typedef { { + * command: string; + * context: any; + * id?: any; + * } } CommandStackAction + * @typedef { { + * actions: CommandStackAction[]; + * dirty: ElementLike[]; + * trigger: 'execute' | 'undo' | 'redo' | 'clear' | null; + * atomic?: boolean; + * } } CurrentExecution + */ + +/** + * A service that offers un- and redoable execution of commands. + * + * The command stack is responsible for executing modeling actions + * in a un- and redoable manner. To do this it delegates the actual + * command execution to {@link CommandHandler}s. + * + * Command handlers provide {@link CommandHandler#execute(ctx)} and + * {@link CommandHandler#revert(ctx)} methods to un- and redo a command + * identified by a command context. + * + * + * ## Life-Cycle events + * + * In the process the command stack fires a number of life-cycle events + * that other components to participate in the command execution. + * + * * preExecute + * * preExecuted + * * execute + * * executed + * * postExecute + * * postExecuted + * * revert + * * reverted + * + * A special event is used for validating, whether a command can be + * performed prior to its execution. + * + * * canExecute + * + * Each of the events is fired as `commandStack.{eventName}` and + * `commandStack.{commandName}.{eventName}`, respectively. This gives + * components fine grained control on where to hook into. + * + * The event object fired transports `command`, the name of the + * command and `context`, the command context. + * + * + * ## Creating Command Handlers + * + * Command handlers should provide the {@link CommandHandler#execute(ctx)} + * and {@link CommandHandler#revert(ctx)} methods to implement + * redoing and undoing of a command. + * + * A command handler _must_ ensure undo is performed properly in order + * not to break the undo chain. It must also return the shapes that + * got changed during the `execute` and `revert` operations. + * + * Command handlers may execute other modeling operations (and thus + * commands) in their `preExecute(d)` and `postExecute(d)` phases. The command + * stack will properly group all commands together into a logical unit + * that may be re- and undone atomically. + * + * Command handlers must not execute other commands from within their + * core implementation (`execute`, `revert`). + * + * + * ## Change Tracking + * + * During the execution of the CommandStack it will keep track of all + * elements that have been touched during the command's execution. + * + * At the end of the CommandStack execution it will notify interested + * components via an 'elements.changed' event with all the dirty + * elements. + * + * The event can be picked up by components that are interested in the fact + * that elements have been changed. One use case for this is updating + * their graphical representation after moving / resizing or deletion. + * + * @see CommandHandler + * + * @param {EventBus} eventBus + * @param {Injector} injector + */ +function CommandStack(eventBus, injector) { + + /** + * A map of all registered command handlers. + * + * @type {CommandHandlerMap} + */ + this._handlerMap = {}; + + /** + * A stack containing all re/undoable actions on the diagram + * + * @type {CommandStackAction[]} + */ + this._stack = []; + + /** + * The current index on the stack + * + * @type {number} + */ + this._stackIdx = -1; + + /** + * Current active commandStack execution + * + * @type {CurrentExecution} + */ + this._currentExecution = { + actions: [], + dirty: [], + trigger: null + }; + + /** + * @type {Injector} + */ + this._injector = injector; + + /** + * @type EventBus + */ + this._eventBus = eventBus; + + /** + * @type { number } + */ + this._uid = 1; + + eventBus.on([ + 'diagram.destroy', + 'diagram.clear' + ], function() { + this.clear(false); + }, this); +} + +CommandStack.$inject = [ 'eventBus', 'injector' ]; + + +/** + * Execute a command. + * + * @param {string} command The command to execute. + * @param {CommandContext} context The context with which to execute the command. + */ +CommandStack.prototype.execute = function(command, context) { + if (!command) { + throw new Error('command required'); + } + + this._currentExecution.trigger = 'execute'; + + const action = { command: command, context: context }; + + this._pushAction(action); + this._internalExecute(action); + this._popAction(); +}; + + +/** + * Check whether a command can be executed. + * + * Implementors may hook into the mechanism on two ways: + * + * * in event listeners: + * + * Users may prevent the execution via an event listener. + * It must prevent the default action for `commandStack.(.)canExecute` events. + * + * * in command handlers: + * + * If the method {@link CommandHandler#canExecute} is implemented in a handler + * it will be called to figure out whether the execution is allowed. + * + * @param {string} command The command to execute. + * @param {CommandContext} context The context with which to execute the command. + * + * @return {boolean} Whether the command can be executed with the given context. + */ +CommandStack.prototype.canExecute = function(command, context) { + + const action = { command: command, context: context }; + + const handler = this._getHandler(command); + + let result = this._fire(command, 'canExecute', action); + + // handler#canExecute will only be called if no listener + // decided on a result already + if (result === undefined) { + if (!handler) { + return false; + } + + if (handler.canExecute) { + result = handler.canExecute(context); + } + } + + return result; +}; + + +/** + * Clear the command stack, erasing all undo / redo history. + * + * @param {boolean} [emit=true] Whether to fire an event. Defaults to `true`. + */ +CommandStack.prototype.clear = function(emit) { + this._stack.length = 0; + this._stackIdx = -1; + + if (emit !== false) { + this._fire('changed', { trigger: 'clear' }); + } +}; + + +/** + * Undo last command(s) + */ +CommandStack.prototype.undo = function() { + let action = this._getUndoAction(), + next; + + if (action) { + this._currentExecution.trigger = 'undo'; + + this._pushAction(action); + + while (action) { + this._internalUndo(action); + next = this._getUndoAction(); + + if (!next || next.id !== action.id) { + break; + } + + action = next; + } + + this._popAction(); + } +}; + + +/** + * Redo last command(s) + */ +CommandStack.prototype.redo = function() { + let action = this._getRedoAction(), + next; + + if (action) { + this._currentExecution.trigger = 'redo'; + + this._pushAction(action); + + while (action) { + this._internalExecute(action, true); + next = this._getRedoAction(); + + if (!next || next.id !== action.id) { + break; + } + + action = next; + } + + this._popAction(); + } +}; + + +/** + * Register a handler instance with the command stack. + * + * @param {string} command Command to be executed. + * @param {CommandHandler} handler Handler to execute the command. + */ +CommandStack.prototype.register = function(command, handler) { + this._setHandler(command, handler); +}; + + +/** + * Register a handler type with the command stack by instantiating it and + * injecting its dependencies. + * + * @param {string} command Command to be executed. + * @param {CommandHandlerConstructor} handlerCls Constructor to instantiate a {@link CommandHandler}. + */ +CommandStack.prototype.registerHandler = function(command, handlerCls) { + + if (!command || !handlerCls) { + throw new Error('command and handlerCls must be defined'); + } + + const handler = this._injector.instantiate(handlerCls); + this.register(command, handler); +}; + +/** + * @return {boolean} + */ +CommandStack.prototype.canUndo = function() { + return !!this._getUndoAction(); +}; + +/** + * @return {boolean} + */ +CommandStack.prototype.canRedo = function() { + return !!this._getRedoAction(); +}; + +// stack access ////////////////////// + +CommandStack.prototype._getRedoAction = function() { + return this._stack[this._stackIdx + 1]; +}; + + +CommandStack.prototype._getUndoAction = function() { + return this._stack[this._stackIdx]; +}; + + +// internal functionality ////////////////////// + +CommandStack.prototype._internalUndo = function(action) { + const command = action.command, + context = action.context; + + const handler = this._getHandler(command); + + // guard against illegal nested command stack invocations + this._atomicDo(() => { + this._fire(command, 'revert', action); + + if (handler.revert) { + this._markDirty(handler.revert(context)); + } + + this._revertedAction(action); + + this._fire(command, 'reverted', action); + }); +}; + + +CommandStack.prototype._fire = function(command, qualifier, event) { + if (arguments.length < 3) { + event = qualifier; + qualifier = null; + } + + const names = qualifier ? [ command + '.' + qualifier, qualifier ] : [ command ]; + let result; + + event = this._eventBus.createEvent(event); + + for (const name of names) { + result = this._eventBus.fire('commandStack.' + name, event); + + if (event.cancelBubble) { + break; + } + } + + return result; +}; + +CommandStack.prototype._createId = function() { + return this._uid++; +}; + +CommandStack.prototype._atomicDo = function(fn) { + + const execution = this._currentExecution; + + execution.atomic = true; + + try { + fn(); + } finally { + execution.atomic = false; + } +}; + +CommandStack.prototype._internalExecute = function(action, redo) { + const command = action.command, + context = action.context; + + const handler = this._getHandler(command); + + if (!handler) { + throw new Error('no command handler registered for <' + command + '>'); + } + + this._pushAction(action); + + if (!redo) { + this._fire(command, 'preExecute', action); + + if (handler.preExecute) { + handler.preExecute(context); + } + + this._fire(command, 'preExecuted', action); + } + + // guard against illegal nested command stack invocations + this._atomicDo(() => { + + this._fire(command, 'execute', action); + + if (handler.execute) { + + // actual execute + mark return results as dirty + this._markDirty(handler.execute(context)); + } + + // log to stack + this._executedAction(action, redo); + + this._fire(command, 'executed', action); + }); + + if (!redo) { + this._fire(command, 'postExecute', action); + + if (handler.postExecute) { + handler.postExecute(context); + } + + this._fire(command, 'postExecuted', action); + } + + this._popAction(); +}; + + +CommandStack.prototype._pushAction = function(action) { + + const execution = this._currentExecution, + actions = execution.actions; + + const baseAction = actions[0]; + + if (execution.atomic) { + throw new Error('illegal invocation in or phase (action: ' + action.command + ')'); + } + + if (!action.id) { + action.id = (baseAction && baseAction.id) || this._createId(); + } + + actions.push(action); +}; + + +CommandStack.prototype._popAction = function() { + const execution = this._currentExecution, + trigger = execution.trigger, + actions = execution.actions, + dirty = execution.dirty; + + actions.pop(); + + if (!actions.length) { + this._eventBus.fire('elements.changed', { elements: uniqueBy('id', dirty.reverse()) }); + + dirty.length = 0; + + this._fire('changed', { trigger: trigger }); + + execution.trigger = null; + } +}; + + +CommandStack.prototype._markDirty = function(elements) { + const execution = this._currentExecution; + + if (!elements) { + return; + } + + elements = isArray$4(elements) ? elements : [ elements ]; + + execution.dirty = execution.dirty.concat(elements); +}; + + +CommandStack.prototype._executedAction = function(action, redo) { + const stackIdx = ++this._stackIdx; + + if (!redo) { + this._stack.splice(stackIdx, this._stack.length, action); + } +}; + + +CommandStack.prototype._revertedAction = function(action) { + this._stackIdx--; +}; + + +CommandStack.prototype._getHandler = function(command) { + return this._handlerMap[command]; +}; + +CommandStack.prototype._setHandler = function(command, handler) { + if (!command || !handler) { + throw new Error('command and handler required'); + } + + if (this._handlerMap[command]) { + throw new Error('overriding handler for command <' + command + '>'); + } + + this._handlerMap[command] = handler; +}; + +/** + * @type { import('didi').ModuleDeclaration } + */ +var CommandModule = { + commandStack: [ 'type', CommandStack ] +}; + +/** + * Util that provides unique IDs. + * + * @class + * @constructor + * + * The ids can be customized via a given prefix and contain a random value to avoid collisions. + * + * @param {string} [prefix] a prefix to prepend to generated ids (for better readability) + */ +function IdGenerator(prefix) { + + this._counter = 0; + this._prefix = (prefix ? prefix + '-' : '') + Math.floor(Math.random() * 1000000000) + '-'; +} + +/** + * Returns a next unique ID. + * + * @return {string} the id + */ +IdGenerator.prototype.next = function() { + return this._prefix + (++this._counter); +}; + +/** + * @typedef {import('../../core/Canvas').default} Canvas + * @typedef {import('../../core/EventBus').default} EventBus + * + * @typedef {import('../../util/Types').RectTRBL} RectTRBL + * + * @typedef { { + * html: string | HTMLElement; + * position: RectTRBL; + * show?: { + * minZoom?: number; + * maxZoom?: number; + * }; + * timeout?: number; + * } } Tooltip + */ + +// document wide unique tooltip ids +var ids$1 = new IdGenerator('tt'); + + +function createRoot$1(parentNode) { + var root = domify$1( + '
' + ); + + assign$2(root, { + position: 'absolute', + width: '0', + height: '0' + }); + + parentNode.insertBefore(root, parentNode.firstChild); + + return root; +} + + +function setPosition$1(el, x, y) { + assign$2(el, { left: x + 'px', top: y + 'px' }); +} + +function setVisible$1(el, visible) { + el.style.display = visible === false ? 'none' : ''; +} + + +var tooltipClass = 'djs-tooltip', + tooltipSelector = '.' + tooltipClass; + +/** + * A service that allows users to render tool tips on the diagram. + * + * The tooltip service will take care of updating the tooltip positioning + * during navigation + zooming. + * + * @example + * + * ```javascript + * + * // add a pink badge on the top left of the shape + * tooltips.add({ + * position: { + * x: 50, + * y: 100 + * }, + * html: '
0
' + * }); + * + * // or with optional life span + * tooltips.add({ + * position: { + * top: -5, + * left: -5 + * }, + * html: '
0
', + * ttl: 2000 + * }); + * + * // remove a tool tip + * var id = tooltips.add(...); + * + * tooltips.remove(id); + * ``` + * + * @param {EventBus} eventBus + * @param {Canvas} canvas + */ +function Tooltips(eventBus, canvas) { + + this._eventBus = eventBus; + this._canvas = canvas; + + this._ids = ids$1; + + this._tooltipDefaults = { + show: { + minZoom: 0.7, + maxZoom: 5.0 + } + }; + + /** + * @type {Record} + */ + this._tooltips = {}; + + // root html element for all tooltips + this._tooltipRoot = createRoot$1(canvas.getContainer()); + + + var self = this; + + delegate.bind(this._tooltipRoot, tooltipSelector, 'mousedown', function(event) { + event.stopPropagation(); + }); + + delegate.bind(this._tooltipRoot, tooltipSelector, 'mouseover', function(event) { + self.trigger('mouseover', event); + }); + + delegate.bind(this._tooltipRoot, tooltipSelector, 'mouseout', function(event) { + self.trigger('mouseout', event); + }); + + this._init(); +} + + +Tooltips.$inject = [ 'eventBus', 'canvas' ]; + + +/** + * Adds an HTML tooltip to the diagram. + * + * @param {Tooltip} tooltip + * + * @return {string} ID of the tooltip. + */ +Tooltips.prototype.add = function(tooltip) { + + if (!tooltip.position) { + throw new Error('must specifiy tooltip position'); + } + + if (!tooltip.html) { + throw new Error('must specifiy tooltip html'); + } + + var id = this._ids.next(); + + tooltip = assign$3({}, this._tooltipDefaults, tooltip, { + id: id + }); + + this._addTooltip(tooltip); + + if (tooltip.timeout) { + this.setTimeout(tooltip); + } + + return id; +}; + +/** + * @param {string} action + * @param {Event} event + */ +Tooltips.prototype.trigger = function(action, event) { + + var node = event.delegateTarget || event.target; + + var tooltip = this.get(attr$2(node, 'data-tooltip-id')); + + if (!tooltip) { + return; + } + + if (action === 'mouseover' && tooltip.timeout) { + this.clearTimeout(tooltip); + } + + if (action === 'mouseout' && tooltip.timeout) { + + // cut timeout after mouse out + tooltip.timeout = 1000; + + this.setTimeout(tooltip); + } +}; + +/** + * Get tooltip with given ID. + * + * @param {Tooltip|string} id + * + * @return {Tooltip|undefined} + */ +Tooltips.prototype.get = function(id) { + + if (typeof id !== 'string') { + id = id.id; + } + + return this._tooltips[id]; +}; + +/** + * @param {Tooltip} tooltip + */ +Tooltips.prototype.clearTimeout = function(tooltip) { + + tooltip = this.get(tooltip); + + if (!tooltip) { + return; + } + + var removeTimer = tooltip.removeTimer; + + if (removeTimer) { + clearTimeout(removeTimer); + tooltip.removeTimer = null; + } +}; + +/** + * @param {Tooltip} tooltip + */ +Tooltips.prototype.setTimeout = function(tooltip) { + + tooltip = this.get(tooltip); + + if (!tooltip) { + return; + } + + this.clearTimeout(tooltip); + + var self = this; + + tooltip.removeTimer = setTimeout(function() { + self.remove(tooltip); + }, tooltip.timeout); +}; + +/** + * Remove tooltip with given ID. + * + * @param {string | Tooltip} id + */ +Tooltips.prototype.remove = function(id) { + + var tooltip = this.get(id); + + if (tooltip) { + remove$1(tooltip.html); + remove$1(tooltip.htmlContainer); + + delete tooltip.htmlContainer; + + delete this._tooltips[tooltip.id]; + } +}; + + +Tooltips.prototype.show = function() { + setVisible$1(this._tooltipRoot); +}; + + +Tooltips.prototype.hide = function() { + setVisible$1(this._tooltipRoot, false); +}; + + +Tooltips.prototype._updateRoot = function(viewbox) { + var a = viewbox.scale || 1; + var d = viewbox.scale || 1; + + var matrix = 'matrix(' + a + ',0,0,' + d + ',' + (-1 * viewbox.x * a) + ',' + (-1 * viewbox.y * d) + ')'; + + this._tooltipRoot.style.transform = matrix; + this._tooltipRoot.style['-ms-transform'] = matrix; +}; + + +Tooltips.prototype._addTooltip = function(tooltip) { + + var id = tooltip.id, + html = tooltip.html, + htmlContainer, + tooltipRoot = this._tooltipRoot; + + // unwrap jquery (for those who need it) + if (html.get && html.constructor.prototype.jquery) { + html = html.get(0); + } + + // create proper html elements from + // tooltip HTML strings + if (isString(html)) { + html = domify$1(html); + } + + htmlContainer = domify$1('
'); + assign$2(htmlContainer, { position: 'absolute' }); + + htmlContainer.appendChild(html); + + if (tooltip.type) { + classes$1(htmlContainer).add('djs-tooltip-' + tooltip.type); + } + + if (tooltip.className) { + classes$1(htmlContainer).add(tooltip.className); + } + + tooltip.htmlContainer = htmlContainer; + + tooltipRoot.appendChild(htmlContainer); + + this._tooltips[id] = tooltip; + + this._updateTooltip(tooltip); +}; + + +Tooltips.prototype._updateTooltip = function(tooltip) { + + var position = tooltip.position, + htmlContainer = tooltip.htmlContainer; + + // update overlay html based on tooltip x, y + + setPosition$1(htmlContainer, position.x, position.y); +}; + + +Tooltips.prototype._updateTooltipVisibilty = function(viewbox) { + + forEach$2(this._tooltips, function(tooltip) { + var show = tooltip.show, + htmlContainer = tooltip.htmlContainer, + visible = true; + + if (show) { + if (show.minZoom > viewbox.scale || + show.maxZoom < viewbox.scale) { + visible = false; + } + + setVisible$1(htmlContainer, visible); + } + }); +}; + +Tooltips.prototype._init = function() { + + var self = this; + + // scroll/zoom integration + + function updateViewbox(viewbox) { + self._updateRoot(viewbox); + self._updateTooltipVisibilty(viewbox); + + self.show(); + } + + this._eventBus.on('canvas.viewbox.changing', function(event) { + self.hide(); + }); + + this._eventBus.on('canvas.viewbox.changed', function(event) { + updateViewbox(event.viewbox); + }); +}; + +/** + * @type { import('didi').ModuleDeclaration } + */ +var tooltips = { + __init__: [ 'tooltips' ], + tooltips: [ 'type', Tooltips ] +}; + +/** + * Remove from the beginning of a collection until it is empty. + * + * This is a null-safe operation that ensures elements + * are being removed from the given collection until the + * collection is empty. + * + * The implementation deals with the fact that a remove operation + * may touch, i.e. remove multiple elements in the collection + * at a time. + * + * @param {Object[]} [collection] + * @param {(element: Object) => void} removeFn + * + * @return {Object[]} the cleared collection + */ +function saveClear(collection, removeFn) { + + if (typeof removeFn !== 'function') { + throw new Error('removeFn iterator must be a function'); + } + + if (!collection) { + return; + } + + var e; + + while ((e = collection[0])) { + removeFn(e); + } + + return collection; +} + +var LOW_PRIORITY$7 = 250, + HIGH_PRIORITY$5 = 1400; + +/** + * @typedef {import('../../model/Types').Element} Element + * + * @typedef {import('didi').Injector} Injector + * + * @typedef {import('../../core/EventBus').default} EventBus + * @typedef {import('../modeling/Modeling').default} Modeling + */ + +/** + * A handler that makes sure labels are properly moved with + * their label targets. + * + * @param {Injector} injector + * @param {EventBus} eventBus + * @param {Modeling} modeling + */ +function LabelSupport(injector, eventBus, modeling) { + + CommandInterceptor.call(this, eventBus); + + var movePreview = injector.get('movePreview', false); + + // remove labels from the collection that are being + // moved with other elements anyway + eventBus.on('shape.move.start', HIGH_PRIORITY$5, function(e) { + + var context = e.context, + shapes = context.shapes, + validatedShapes = context.validatedShapes; + + context.shapes = removeLabels(shapes); + context.validatedShapes = removeLabels(validatedShapes); + }); + + // add labels to visual's group + movePreview && eventBus.on('shape.move.start', LOW_PRIORITY$7, function(e) { + + var context = e.context, + shapes = context.shapes; + + var labels = []; + + forEach$2(shapes, function(element) { + + forEach$2(element.labels, function(label) { + + if (!label.hidden && context.shapes.indexOf(label) === -1) { + labels.push(label); + } + + if (element.labelTarget) { + labels.push(element); + } + }); + }); + + forEach$2(labels, function(label) { + movePreview.makeDraggable(context, label, true); + }); + + }); + + // add all labels to move closure + this.preExecuted('elements.move', HIGH_PRIORITY$5, function(e) { + var context = e.context, + closure = context.closure, + enclosedElements = closure.enclosedElements; + + var enclosedLabels = []; + + // find labels that are not part of + // move closure yet and add them + forEach$2(enclosedElements, function(element) { + forEach$2(element.labels, function(label) { + + if (!enclosedElements[label.id]) { + enclosedLabels.push(label); + } + }); + }); + + closure.addAll(enclosedLabels); + }); + + + this.preExecute([ + 'connection.delete', + 'shape.delete' + ], function(e) { + + var context = e.context, + element = context.connection || context.shape; + + saveClear(element.labels, function(label) { + modeling.removeShape(label, { nested: true }); + }); + }); + + + this.execute('shape.delete', function(e) { + + var context = e.context, + shape = context.shape, + labelTarget = shape.labelTarget; + + // unset labelTarget + if (labelTarget) { + context.labelTargetIndex = indexOf(labelTarget.labels, shape); + context.labelTarget = labelTarget; + + shape.labelTarget = null; + } + }); + + this.revert('shape.delete', function(e) { + + var context = e.context, + shape = context.shape, + labelTarget = context.labelTarget, + labelTargetIndex = context.labelTargetIndex; + + // restore labelTarget + if (labelTarget) { + add(labelTarget.labels, shape, labelTargetIndex); + + shape.labelTarget = labelTarget; + } + }); + +} + +e(LabelSupport, CommandInterceptor); + +LabelSupport.$inject = [ + 'injector', + 'eventBus', + 'modeling' +]; + + +/** + * Return a filtered list of elements that do not + * contain attached elements with hosts being part + * of the selection. + * + * @param {Element[]} elements + * + * @return {Element[]} filtered + */ +function removeLabels(elements) { + + return filter(elements, function(element) { + + // filter out labels that are move together + // with their label targets + return elements.indexOf(element.labelTarget) === -1; + }); +} + +/** + * @type { import('didi').ModuleDeclaration } + */ +var LabelSupportModule = { + __init__: [ 'labelSupport' ], + labelSupport: [ 'type', LabelSupport ] +}; + +/** + * @typedef {import('didi').Injector} Injector + * + * @typedef {import('../../model/Types').Element} Element + * + * @typedef {import('../../core/Canvas').default} Canvas + * @typedef {import('../../core/EventBus').default} EventBus + * @typedef {import('../rules/Rules').default} Rules + * @typedef {import('../modeling/Modeling').default} Modeling + */ + +var LOW_PRIORITY$6 = 251, + HIGH_PRIORITY$4 = 1401; + +var MARKER_ATTACH = 'attach-ok'; + + +/** + * Adds the notion of attached elements to the modeler. + * + * Optionally depends on `diagram-js/lib/features/move` to render + * the attached elements during move preview. + * + * Optionally depends on `diagram-js/lib/features/label-support` + * to render attached labels during move preview. + * + * @param {Injector} injector + * @param {EventBus} eventBus + * @param {Canvas} canvas + * @param {Rules} rules + * @param {Modeling} modeling + */ +function AttachSupport(injector, eventBus, canvas, rules, modeling) { + + CommandInterceptor.call(this, eventBus); + + var movePreview = injector.get('movePreview', false); + + + // remove all the attached elements from the shapes to be validated + // add all the attached shapes to the overall list of moved shapes + eventBus.on('shape.move.start', HIGH_PRIORITY$4, function(e) { + + var context = e.context, + shapes = context.shapes, + validatedShapes = context.validatedShapes; + + context.shapes = addAttached(shapes); + + context.validatedShapes = removeAttached(validatedShapes); + }); + + // add attachers to the visual's group + movePreview && eventBus.on('shape.move.start', LOW_PRIORITY$6, function(e) { + + var context = e.context, + shapes = context.shapes, + attachers = getAttachers(shapes); + + forEach$2(attachers, function(attacher) { + movePreview.makeDraggable(context, attacher, true); + + forEach$2(attacher.labels, function(label) { + movePreview.makeDraggable(context, label, true); + }); + }); + }); + + // add attach-ok marker to current host + movePreview && eventBus.on('shape.move.start', function(event) { + var context = event.context, + shapes = context.shapes; + + if (shapes.length !== 1) { + return; + } + + var shape = shapes[0]; + + var host = shape.host; + + if (host) { + canvas.addMarker(host, MARKER_ATTACH); + + eventBus.once([ + 'shape.move.out', + 'shape.move.cleanup' + ], function() { + canvas.removeMarker(host, MARKER_ATTACH); + }); + } + }); + + // add all attachers to move closure + this.preExecuted('elements.move', HIGH_PRIORITY$4, function(e) { + var context = e.context, + closure = context.closure, + shapes = context.shapes, + attachers = getAttachers(shapes); + + forEach$2(attachers, function(attacher) { + closure.add(attacher, closure.topLevel[attacher.host.id]); + }); + }); + + // perform the attaching after shapes are done moving + this.postExecuted('elements.move', function(e) { + + var context = e.context, + shapes = context.shapes, + newHost = context.newHost, + attachers; + + // only single elements can be attached + // multiply elements can be detached + if (newHost && shapes.length !== 1) { + return; + } + + if (newHost) { + attachers = shapes; + } else { + + // find attachers moved without host + attachers = filter(shapes, function(shape) { + var host = shape.host; + + return isAttacher(shape) && !includes$1(shapes, host); + }); + } + + forEach$2(attachers, function(attacher) { + modeling.updateAttachment(attacher, newHost); + }); + }); + + // ensure invalid attachment connections are removed + this.postExecuted('elements.move', function(e) { + + var shapes = e.context.shapes; + + forEach$2(shapes, function(shape) { + + forEach$2(shape.attachers, function(attacher) { + + // remove invalid outgoing connections + forEach$2(attacher.outgoing.slice(), function(connection) { + var allowed = rules.allowed('connection.reconnect', { + connection: connection, + source: connection.source, + target: connection.target + }); + + if (!allowed) { + modeling.removeConnection(connection); + } + }); + + // remove invalid incoming connections + forEach$2(attacher.incoming.slice(), function(connection) { + var allowed = rules.allowed('connection.reconnect', { + connection: connection, + source: connection.source, + target: connection.target + }); + + if (!allowed) { + modeling.removeConnection(connection); + } + }); + }); + }); + }); + + this.postExecute('shape.create', function(e) { + var context = e.context, + shape = context.shape, + host = context.host; + + if (host) { + modeling.updateAttachment(shape, host); + } + }); + + // update attachments if the host is replaced + this.postExecute('shape.replace', function(e) { + + var context = e.context, + oldShape = context.oldShape, + newShape = context.newShape; + + // move the attachers to the new host + saveClear(oldShape.attachers, function(attacher) { + var allowed = rules.allowed('elements.move', { + target: newShape, + shapes: [ attacher ] + }); + + if (allowed === 'attach') { + modeling.updateAttachment(attacher, newShape); + } else { + modeling.removeShape(attacher); + } + }); + + // move attachers if new host has different size + if (newShape.attachers.length) { + + forEach$2(newShape.attachers, function(attacher) { + var delta = getNewAttachShapeDelta(attacher, oldShape, newShape); + modeling.moveShape(attacher, delta, attacher.parent); + }); + } + + }); + + // move shape on host resize + this.postExecute('shape.resize', function(event) { + var context = event.context, + shape = context.shape, + oldBounds = context.oldBounds, + newBounds = context.newBounds, + attachers = shape.attachers, + hints = context.hints || {}; + + if (hints.attachSupport === false) { + return; + } + + forEach$2(attachers, function(attacher) { + var delta = getNewAttachShapeDelta(attacher, oldBounds, newBounds); + + modeling.moveShape(attacher, delta, attacher.parent); + + forEach$2(attacher.labels, function(label) { + modeling.moveShape(label, delta, label.parent); + }); + }); + }); + + // remove attachments + this.preExecute('shape.delete', function(event) { + + var shape = event.context.shape; + + saveClear(shape.attachers, function(attacher) { + modeling.removeShape(attacher); + }); + + if (shape.host) { + modeling.updateAttachment(shape, null); + } + }); +} + +e(AttachSupport, CommandInterceptor); + +AttachSupport.$inject = [ + 'injector', + 'eventBus', + 'canvas', + 'rules', + 'modeling' +]; + + +/** + * Return attachers of the given shapes + * + * @param {Element[]} shapes + * @return {Element[]} + */ +function getAttachers(shapes) { + return flatten(map$2(shapes, function(s) { + return s.attachers || []; + })); +} + +/** + * Return a combined list of elements and + * attachers. + * + * @param {Element[]} elements + * @return {Element[]} filtered + */ +function addAttached(elements) { + var attachers = getAttachers(elements); + + return unionBy('id', elements, attachers); +} + +/** + * Return a filtered list of elements that do not + * contain attached elements with hosts being part + * of the selection. + * + * @param {Element[]} elements + * + * @return {Element[]} filtered + */ +function removeAttached(elements) { + + var ids = groupBy(elements, 'id'); + + return filter(elements, function(element) { + while (element) { + + // host in selection + if (element.host && ids[element.host.id]) { + return false; + } + + element = element.parent; + } + + return true; + }); +} + +function isAttacher(shape) { + return !!shape.host; +} + +function includes$1(array, item) { + return array.indexOf(item) !== -1; +} + +/** + * @type { import('didi').ModuleDeclaration } + */ +var AttachSupportModule = { + __depends__: [ + RulesModule$1 + ], + __init__: [ 'attachSupport' ], + attachSupport: [ 'type', AttachSupport ] +}; + +/** + * @typedef {import('../../core/Canvas').default} Canvas + * @typedef {import('../../core/ElementRegistry').default} ElementRegistry + * @typedef {import('../../core/EventBus').default} EventBus + * @typedef {import('../../core/GraphicsFactory').default} GraphicsFactory + */ + +/** + * Adds change support to the diagram, including + * + *
    + *
  • redrawing shapes and connections on change
  • + *
+ * + * @param {EventBus} eventBus + * @param {Canvas} canvas + * @param {ElementRegistry} elementRegistry + * @param {GraphicsFactory} graphicsFactory + */ +function ChangeSupport( + eventBus, canvas, elementRegistry, + graphicsFactory) { + + + // redraw shapes / connections on change + + eventBus.on('element.changed', function(event) { + + var element = event.element; + + // element might have been deleted and replaced by new element with same ID + // thus check for parent of element except for root element + if (element.parent || element === canvas.getRootElement()) { + event.gfx = elementRegistry.getGraphics(element); + } + + // shape + gfx may have been deleted + if (!event.gfx) { + return; + } + + eventBus.fire(getType(element) + '.changed', event); + }); + + eventBus.on('elements.changed', function(event) { + + var elements = event.elements; + + elements.forEach(function(e) { + eventBus.fire('element.changed', { element: e }); + }); + + graphicsFactory.updateContainments(elements); + }); + + eventBus.on('shape.changed', function(event) { + graphicsFactory.update('shape', event.element, event.gfx); + }); + + eventBus.on('connection.changed', function(event) { + graphicsFactory.update('connection', event.element, event.gfx); + }); +} + +ChangeSupport.$inject = [ + 'eventBus', + 'canvas', + 'elementRegistry', + 'graphicsFactory' +]; + +/** + * @type { import('didi').ModuleDeclaration } + */ +var ChangeSupportModule = { + __init__: [ 'changeSupport' ], + changeSupport: [ 'type', ChangeSupport ] +}; + +/** + * @typedef {import('../../model/Types').Moddle} Moddle + * @typedef {import('../../model/Types').ModdleElement} ModdleElement + * + * @typedef {import('diagram-js/lib/util/Types').Point} Point + */ + +/** + * A factory for BPMN elements. + * + * @param {Moddle} moddle + */ +function BpmnFactory(moddle) { + this._model = moddle; +} + +BpmnFactory.$inject = [ 'moddle' ]; + +/** + * @param {ModdleElement} element + * + * @return {boolean} + */ +BpmnFactory.prototype._needsId = function(element) { + return isAny(element, [ + 'bpmn:RootElement', + 'bpmn:FlowElement', + 'bpmn:MessageFlow', + 'bpmn:DataAssociation', + 'bpmn:Artifact', + 'bpmn:Participant', + 'bpmn:Lane', + 'bpmn:LaneSet', + 'bpmn:Process', + 'bpmn:Collaboration', + 'bpmndi:BPMNShape', + 'bpmndi:BPMNEdge', + 'bpmndi:BPMNDiagram', + 'bpmndi:BPMNPlane', + 'bpmn:Property', + 'bpmn:CategoryValue' + ]); +}; + +/** + * @param {ModdleElement} element + */ +BpmnFactory.prototype._ensureId = function(element) { + if (element.id) { + this._model.ids.claim(element.id, element); + return; + } + + // generate semantic ids for elements + // bpmn:SequenceFlow -> SequenceFlow_ID + var prefix; + + if (is$2(element, 'bpmn:Activity')) { + prefix = 'Activity'; + } else if (is$2(element, 'bpmn:Event')) { + prefix = 'Event'; + } else if (is$2(element, 'bpmn:Gateway')) { + prefix = 'Gateway'; + } else if (isAny(element, [ 'bpmn:SequenceFlow', 'bpmn:MessageFlow' ])) { + prefix = 'Flow'; + } else { + prefix = (element.$type || '').replace(/^[^:]*:/g, ''); + } + + prefix += '_'; + + if (!element.id && this._needsId(element)) { + element.id = this._model.ids.nextPrefixed(prefix, element); + } +}; + +/** + * Create BPMN element. + * + * @param {string} type + * @param {Object} [attrs] + * + * @return {ModdleElement} + */ +BpmnFactory.prototype.create = function(type, attrs) { + var element = this._model.create(type, attrs || {}); + + this._ensureId(element); + + return element; +}; + +/** + * @return {ModdleElement} + */ +BpmnFactory.prototype.createDiLabel = function() { + return this.create('bpmndi:BPMNLabel', { + bounds: this.createDiBounds() + }); +}; + +/** + * @param {ModdleElement} semantic + * @param {Object} [attrs] + * @return {ModdleElement} + */ +BpmnFactory.prototype.createDiShape = function(semantic, attrs) { + return this.create('bpmndi:BPMNShape', assign$3({ + bpmnElement: semantic, + bounds: this.createDiBounds() + }, attrs)); +}; + +/** + * @return {ModdleElement} + */ +BpmnFactory.prototype.createDiBounds = function(bounds) { + return this.create('dc:Bounds', bounds); +}; + +/** + * @param {Point[]} waypoints + * + * @return {ModdleElement[]} + */ +BpmnFactory.prototype.createDiWaypoints = function(waypoints) { + var self = this; + + return map$2(waypoints, function(pos) { + return self.createDiWaypoint(pos); + }); +}; + +/** + * @param {Point} point + * + * @return {ModdleElement} + */ +BpmnFactory.prototype.createDiWaypoint = function(point) { + return this.create('dc:Point', pick(point, [ 'x', 'y' ])); +}; + +/** + * @param {ModdleElement} semantic + * @param {Object} [attrs] + * + * @return {ModdleElement} + */ +BpmnFactory.prototype.createDiEdge = function(semantic, attrs) { + return this.create('bpmndi:BPMNEdge', assign$3({ + bpmnElement: semantic, + waypoint: this.createDiWaypoints([]) + }, attrs)); +}; + +/** + * @param {ModdleElement} semantic + * @param {Object} [attrs] + * + * @return {ModdleElement} + */ +BpmnFactory.prototype.createDiPlane = function(semantic, attrs) { + return this.create('bpmndi:BPMNPlane', assign$3({ + bpmnElement: semantic + }, attrs)); +}; + +/** + * @typedef {import('diagram-js/lib/core/EventBus').default} EventBus + * @typedef {import('./BpmnFactory').default} BpmnFactory + * @typedef {import('diagram-js/lib/layout/CroppingConnectionDocking').default} CroppingConnectionDocking + * @typedef {import('diagram-js/lib/i18n/translate/translate').default} Translate + * + * @typedef {import('../../model/Types').Connection} Connection + * @typedef {import('../../model/Types').Element} Element + * @typedef {import('../../model/Types').Shape} Shape + * @typedef {import('../../model/Types').Parent} Parent + * @typedef {import('../../model/Types').ModdleElement} ModdleElement + */ + +/** + * A handler responsible for updating the underlying BPMN 2.0 XML & DI + * once changes on the diagram happen. + * + * @param {EventBus} eventBus + * @param {BpmnFactory} bpmnFactory + * @param {CroppingConnectionDocking} connectionDocking + * @param {Translate} translate + */ +function BpmnUpdater( + eventBus, + bpmnFactory, + connectionDocking, + translate +) { + + CommandInterceptor.call(this, eventBus); + + this._bpmnFactory = bpmnFactory; + this._translate = translate; + + var self = this; + + + + // connection cropping ////////////////////// + + // crop connection ends during create/update + function cropConnection(e) { + var context = e.context, + hints = context.hints || {}, + connection; + + if (!context.cropped && hints.createElementsBehavior !== false) { + connection = context.connection; + connection.waypoints = connectionDocking.getCroppedWaypoints(connection); + context.cropped = true; + } + } + + this.executed([ + 'connection.layout', + 'connection.create' + ], cropConnection); + + this.reverted([ 'connection.layout' ], function(e) { + delete e.context.cropped; + }); + + + + // BPMN + DI update ////////////////////// + + + // update parent + function updateParent(e) { + var context = e.context; + + self.updateParent(context.shape || context.connection, context.oldParent); + } + + function reverseUpdateParent(e) { + var context = e.context; + + var element = context.shape || context.connection, + + // oldParent is the (old) new parent, because we are undoing + oldParent = context.parent || context.newParent; + + self.updateParent(element, oldParent); + } + + this.executed([ + 'shape.move', + 'shape.create', + 'shape.delete', + 'connection.create', + 'connection.move', + 'connection.delete' + ], ifBpmn(updateParent)); + + this.reverted([ + 'shape.move', + 'shape.create', + 'shape.delete', + 'connection.create', + 'connection.move', + 'connection.delete' + ], ifBpmn(reverseUpdateParent)); + + /* + * ## Updating Parent + * + * When morphing a Process into a Collaboration or vice-versa, + * make sure that both the *semantic* and *di* parent of each element + * is updated. + * + */ + function updateRoot(event) { + var context = event.context, + oldRoot = context.oldRoot, + children = oldRoot.children; + + forEach$2(children, function(child) { + if (is$2(child, 'bpmn:BaseElement')) { + self.updateParent(child); + } + }); + } + + this.executed([ 'canvas.updateRoot' ], updateRoot); + this.reverted([ 'canvas.updateRoot' ], updateRoot); + + + // update bounds + function updateBounds(e) { + var shape = e.context.shape; + + if (!is$2(shape, 'bpmn:BaseElement')) { + return; + } + + self.updateBounds(shape); + } + + this.executed([ 'shape.move', 'shape.create', 'shape.resize' ], ifBpmn(function(event) { + + // exclude labels because they're handled separately during shape.changed + if (event.context.shape.type === 'label') { + return; + } + + updateBounds(event); + })); + + this.reverted([ 'shape.move', 'shape.create', 'shape.resize' ], ifBpmn(function(event) { + + // exclude labels because they're handled separately during shape.changed + if (event.context.shape.type === 'label') { + return; + } + + updateBounds(event); + })); + + // Handle labels separately. This is necessary, because the label bounds have to be updated + // every time its shape changes, not only on move, create and resize. + eventBus.on('shape.changed', function(event) { + if (event.element.type === 'label') { + updateBounds({ context: { shape: event.element } }); + } + }); + + // attach / detach connection + function updateConnection(e) { + self.updateConnection(e.context); + } + + this.executed([ + 'connection.create', + 'connection.move', + 'connection.delete', + 'connection.reconnect' + ], ifBpmn(updateConnection)); + + this.reverted([ + 'connection.create', + 'connection.move', + 'connection.delete', + 'connection.reconnect' + ], ifBpmn(updateConnection)); + + + // update waypoints + function updateConnectionWaypoints(e) { + self.updateConnectionWaypoints(e.context.connection); + } + + this.executed([ + 'connection.layout', + 'connection.move', + 'connection.updateWaypoints', + ], ifBpmn(updateConnectionWaypoints)); + + this.reverted([ + 'connection.layout', + 'connection.move', + 'connection.updateWaypoints', + ], ifBpmn(updateConnectionWaypoints)); + + // update conditional/default flows + this.executed('connection.reconnect', ifBpmn(function(event) { + var context = event.context, + connection = context.connection, + oldSource = context.oldSource, + newSource = context.newSource, + connectionBo = getBusinessObject(connection), + oldSourceBo = getBusinessObject(oldSource), + newSourceBo = getBusinessObject(newSource); + + // remove condition from connection on reconnect to new source + // if new source can NOT have condional sequence flow + if (connectionBo.conditionExpression && !isAny(newSourceBo, [ + 'bpmn:Activity', + 'bpmn:ExclusiveGateway', + 'bpmn:InclusiveGateway' + ])) { + context.oldConditionExpression = connectionBo.conditionExpression; + + delete connectionBo.conditionExpression; + } + + // remove default from old source flow on reconnect to new source + // if source changed + if (oldSource !== newSource && oldSourceBo.default === connectionBo) { + context.oldDefault = oldSourceBo.default; + + delete oldSourceBo.default; + } + })); + + this.reverted('connection.reconnect', ifBpmn(function(event) { + var context = event.context, + connection = context.connection, + oldSource = context.oldSource, + newSource = context.newSource, + connectionBo = getBusinessObject(connection), + oldSourceBo = getBusinessObject(oldSource), + newSourceBo = getBusinessObject(newSource); + + // add condition to connection on revert reconnect to new source + if (context.oldConditionExpression) { + connectionBo.conditionExpression = context.oldConditionExpression; + } + + // add default to old source on revert reconnect to new source + if (context.oldDefault) { + oldSourceBo.default = context.oldDefault; + + delete newSourceBo.default; + } + })); + + // update attachments + function updateAttachment(e) { + self.updateAttachment(e.context); + } + + this.executed([ 'element.updateAttachment' ], ifBpmn(updateAttachment)); + this.reverted([ 'element.updateAttachment' ], ifBpmn(updateAttachment)); + + + // update BPMNLabel + this.executed('element.updateLabel', ifBpmn(updateBPMNLabel)); + this.reverted('element.updateLabel', ifBpmn(updateBPMNLabel)); + + function updateBPMNLabel(event) { + const { element } = event.context, + label = getLabel(element); + const di = getDi(element), + diLabel = di && di.get('label'); + + if (isLabelExternal(element)) { + return; + } + + if (label && !diLabel) { + di.set('label', bpmnFactory.create('bpmndi:BPMNLabel')); + } else if (!label && diLabel) { + di.set('label', undefined); + } + } +} + +e(BpmnUpdater, CommandInterceptor); + +BpmnUpdater.$inject = [ + 'eventBus', + 'bpmnFactory', + 'connectionDocking', + 'translate' +]; + + +// implementation ////////////////////// + +/** + * @param { { + * shape: Shape; + * host: Shape; + * } } context + */ +BpmnUpdater.prototype.updateAttachment = function(context) { + + var shape = context.shape, + businessObject = shape.businessObject, + host = shape.host; + + businessObject.attachedToRef = host && host.businessObject; +}; + +/** + * @param {Element} element + * @param {Parent} oldParent + */ +BpmnUpdater.prototype.updateParent = function(element, oldParent) { + + // do not update BPMN 2.0 label parent + if (isLabel(element)) { + return; + } + + // data stores in collaborations are handled separately by DataStoreBehavior + if (is$2(element, 'bpmn:DataStoreReference') && + element.parent && + is$2(element.parent, 'bpmn:Collaboration')) { + return; + } + + var parentShape = element.parent; + + var businessObject = element.businessObject, + di = getDi(element), + parentBusinessObject = parentShape && parentShape.businessObject, + parentDi = getDi(parentShape); + + if (is$2(element, 'bpmn:FlowNode')) { + this.updateFlowNodeRefs(businessObject, parentBusinessObject, oldParent && oldParent.businessObject); + } + + if (is$2(element, 'bpmn:DataOutputAssociation')) { + if (element.source) { + parentBusinessObject = element.source.businessObject; + } else { + parentBusinessObject = null; + } + } + + if (is$2(element, 'bpmn:DataInputAssociation')) { + if (element.target) { + parentBusinessObject = element.target.businessObject; + } else { + parentBusinessObject = null; + } + } + + this.updateSemanticParent(businessObject, parentBusinessObject); + + if (is$2(element, 'bpmn:DataObjectReference') && businessObject.dataObjectRef) { + this.updateSemanticParent(businessObject.dataObjectRef, parentBusinessObject); + } + + this.updateDiParent(di, parentDi); +}; + +/** + * @param {Shape} shape + */ +BpmnUpdater.prototype.updateBounds = function(shape) { + + var di = getDi(shape), + embeddedLabelBounds = getEmbeddedLabelBounds(shape); + + // update embedded label bounds if possible + if (embeddedLabelBounds) { + var embeddedLabelBoundsDelta = delta(embeddedLabelBounds, di.get('bounds')); + + assign$3(embeddedLabelBounds, { + x: shape.x + embeddedLabelBoundsDelta.x, + y: shape.y + embeddedLabelBoundsDelta.y + }); + } + + var target = isLabel(shape) ? this._getLabel(di) : di; + + var bounds = target.bounds; + + if (!bounds) { + bounds = this._bpmnFactory.createDiBounds(); + target.set('bounds', bounds); + } + + assign$3(bounds, { + x: shape.x, + y: shape.y, + width: shape.width, + height: shape.height + }); +}; + +/** + * @param {ModdleElement} businessObject + * @param {ModdleElement} newContainment + * @param {ModdleElement} oldContainment + */ +BpmnUpdater.prototype.updateFlowNodeRefs = function(businessObject, newContainment, oldContainment) { + + if (oldContainment === newContainment) { + return; + } + + var oldRefs, newRefs; + + if (is$2 (oldContainment, 'bpmn:Lane')) { + oldRefs = oldContainment.get('flowNodeRef'); + remove$2(oldRefs, businessObject); + } + + if (is$2(newContainment, 'bpmn:Lane')) { + newRefs = newContainment.get('flowNodeRef'); + add(newRefs, businessObject); + } +}; + +/** + * @param {Connection} connection + * @param {Element} newSource + * @param {Element} newTarget + */ +BpmnUpdater.prototype.updateDiConnection = function(connection, newSource, newTarget) { + var connectionDi = getDi(connection), + newSourceDi = getDi(newSource), + newTargetDi = getDi(newTarget); + + if (connectionDi.sourceElement && connectionDi.sourceElement.bpmnElement !== getBusinessObject(newSource)) { + connectionDi.sourceElement = newSource && newSourceDi; + } + + if (connectionDi.targetElement && connectionDi.targetElement.bpmnElement !== getBusinessObject(newTarget)) { + connectionDi.targetElement = newTarget && newTargetDi; + } + +}; + +/** + * @param {ModdleElement} di + * @param {ModdleElement} parentDi + */ +BpmnUpdater.prototype.updateDiParent = function(di, parentDi) { + + if (parentDi && !is$2(parentDi, 'bpmndi:BPMNPlane')) { + parentDi = parentDi.$parent; + } + + if (di.$parent === parentDi) { + return; + } + + var planeElements = (parentDi || di.$parent).get('planeElement'); + + if (parentDi) { + planeElements.push(di); + di.$parent = parentDi; + } else { + remove$2(planeElements, di); + di.$parent = null; + } +}; + +/** + * @param {ModdleElement} element + * + * @return {ModdleElement} + */ +function getDefinitions(element) { + while (element && !is$2(element, 'bpmn:Definitions')) { + element = element.$parent; + } + + return element; +} + +/** + * @param {ModdleElement} container + * + * @return {ModdleElement} + */ +BpmnUpdater.prototype.getLaneSet = function(container) { + + var laneSet, laneSets; + + // bpmn:Lane + if (is$2(container, 'bpmn:Lane')) { + laneSet = container.childLaneSet; + + if (!laneSet) { + laneSet = this._bpmnFactory.create('bpmn:LaneSet'); + container.childLaneSet = laneSet; + laneSet.$parent = container; + } + + return laneSet; + } + + // bpmn:Participant + if (is$2(container, 'bpmn:Participant')) { + container = container.processRef; + } + + // bpmn:FlowElementsContainer + laneSets = container.get('laneSets'); + laneSet = laneSets[0]; + + if (!laneSet) { + laneSet = this._bpmnFactory.create('bpmn:LaneSet'); + laneSet.$parent = container; + laneSets.push(laneSet); + } + + return laneSet; +}; + +/** + * @param {ModdleElement} businessObject + * @param {ModdleElement} newParent + * @param {ModdleElement} visualParent + */ +BpmnUpdater.prototype.updateSemanticParent = function(businessObject, newParent, visualParent) { + + var containment, + translate = this._translate; + + if (businessObject.$parent === newParent) { + return; + } + + if (is$2(businessObject, 'bpmn:DataInput') || is$2(businessObject, 'bpmn:DataOutput')) { + + if (is$2(newParent, 'bpmn:Participant') && 'processRef' in newParent) { + newParent = newParent.processRef; + } + + // already in correct ioSpecification + if ('ioSpecification' in newParent && newParent.ioSpecification === businessObject.$parent) { + return; + } + } + + if (is$2(businessObject, 'bpmn:Lane')) { + + if (newParent) { + newParent = this.getLaneSet(newParent); + } + + containment = 'lanes'; + } else + + if (is$2(businessObject, 'bpmn:FlowElement')) { + + if (newParent) { + + if (is$2(newParent, 'bpmn:Participant')) { + newParent = newParent.processRef; + } else + + if (is$2(newParent, 'bpmn:Lane')) { + do { + + // unwrap Lane -> LaneSet -> (Lane | FlowElementsContainer) + newParent = newParent.$parent.$parent; + } while (is$2(newParent, 'bpmn:Lane')); + + } + } + + containment = 'flowElements'; + + } else + + if (is$2(businessObject, 'bpmn:Artifact')) { + + while (newParent && + !is$2(newParent, 'bpmn:Process') && + !is$2(newParent, 'bpmn:SubProcess') && + !is$2(newParent, 'bpmn:Collaboration')) { + + if (is$2(newParent, 'bpmn:Participant')) { + newParent = newParent.processRef; + break; + } else { + newParent = newParent.$parent; + } + } + + containment = 'artifacts'; + } else + + if (is$2(businessObject, 'bpmn:MessageFlow')) { + containment = 'messageFlows'; + + } else + + if (is$2(businessObject, 'bpmn:Participant')) { + containment = 'participants'; + + // make sure the participants process is properly attached / detached + // from the XML document + + var process = businessObject.processRef, + definitions; + + if (process) { + definitions = getDefinitions(businessObject.$parent || newParent); + + if (businessObject.$parent) { + remove$2(definitions.get('rootElements'), process); + process.$parent = null; + } + + if (newParent) { + add(definitions.get('rootElements'), process); + process.$parent = definitions; + } + } + } else + + if (is$2(businessObject, 'bpmn:DataOutputAssociation')) { + containment = 'dataOutputAssociations'; + } else + + if (is$2(businessObject, 'bpmn:DataInputAssociation')) { + containment = 'dataInputAssociations'; + } + + if (!containment) { + throw new Error(translate( + 'no parent for {element} in {parent}', + { + element: businessObject.id, + parent: newParent.id + } + )); + } + + var children; + + if (businessObject.$parent) { + + // remove from old parent + children = businessObject.$parent.get(containment); + remove$2(children, businessObject); + } + + if (!newParent) { + businessObject.$parent = null; + } else { + + // add to new parent + children = newParent.get(containment); + children.push(businessObject); + businessObject.$parent = newParent; + } + + if (visualParent) { + var diChildren = visualParent.get(containment); + + remove$2(children, businessObject); + + if (newParent) { + + if (!diChildren) { + diChildren = []; + newParent.set(containment, diChildren); + } + + diChildren.push(businessObject); + } + } +}; + +/** + * @param {Connection} connection + */ +BpmnUpdater.prototype.updateConnectionWaypoints = function(connection) { + var di = getDi(connection); + + di.set('waypoint', this._bpmnFactory.createDiWaypoints(connection.waypoints)); +}; + +/** + * @param { { + * connection: Connection; + * parent: Parent; + * newParent: Parent; + * } } context + */ +BpmnUpdater.prototype.updateConnection = function(context) { + var connection = context.connection, + businessObject = getBusinessObject(connection), + newSource = connection.source, + newSourceBo = getBusinessObject(newSource), + newTarget = connection.target, + newTargetBo = getBusinessObject(connection.target), + visualParent; + + if (!is$2(businessObject, 'bpmn:DataAssociation')) { + + var inverseSet = is$2(businessObject, 'bpmn:SequenceFlow'); + + if (businessObject.sourceRef !== newSourceBo) { + if (inverseSet) { + remove$2(businessObject.sourceRef && businessObject.sourceRef.get('outgoing'), businessObject); + + if (newSourceBo && newSourceBo.get('outgoing')) { + newSourceBo.get('outgoing').push(businessObject); + } + } + + businessObject.sourceRef = newSourceBo; + } + + if (businessObject.targetRef !== newTargetBo) { + if (inverseSet) { + remove$2(businessObject.targetRef && businessObject.targetRef.get('incoming'), businessObject); + + if (newTargetBo && newTargetBo.get('incoming')) { + newTargetBo.get('incoming').push(businessObject); + } + } + + businessObject.targetRef = newTargetBo; + } + } else + + if (is$2(businessObject, 'bpmn:DataInputAssociation')) { + + // handle obnoxious isMsome sourceRef + businessObject.get('sourceRef')[0] = newSourceBo; + + visualParent = context.parent || context.newParent || newTargetBo; + + this.updateSemanticParent(businessObject, newTargetBo, visualParent); + } else + + if (is$2(businessObject, 'bpmn:DataOutputAssociation')) { + visualParent = context.parent || context.newParent || newSourceBo; + + this.updateSemanticParent(businessObject, newSourceBo, visualParent); + + // targetRef = new target + businessObject.targetRef = newTargetBo; + } + + this.updateConnectionWaypoints(connection); + + this.updateDiConnection(connection, newSource, newTarget); +}; + + +// helpers ////////////////////// + +BpmnUpdater.prototype._getLabel = function(di) { + if (!di.label) { + di.label = this._bpmnFactory.createDiLabel(); + } + + return di.label; +}; + + +/** + * Call function if shape or connection is BPMN element. + * + * @param {Function} fn + * + * @return {Function} + */ +function ifBpmn(fn) { + + return function(event) { + + var context = event.context, + element = context.shape || context.connection || context.element; + + if (is$2(element, 'bpmn:BaseElement')) { + fn(event); + } + }; +} + +/** + * Return dc:Bounds of bpmndi:BPMNLabel if exists. + * + * @param {Shape} shape + * + * @return {ModdleElement|undefined} + */ +function getEmbeddedLabelBounds(shape) { + if (!is$2(shape, 'bpmn:Activity')) { + return; + } + + var di = getDi(shape); + + if (!di) { + return; + } + + var label = di.get('label'); + + if (!label) { + return; + } + + return label.get('bounds'); +} + +var objectRefs = {exports: {}}; + +var collection = {}; + +/** + * An empty collection stub. Use {@link RefsCollection.extend} to extend a + * collection with ref semantics. + * + * @class RefsCollection + */ + +/** + * Extends a collection with {@link Refs} aware methods + * + * @memberof RefsCollection + * @static + * + * @param {Array} collection + * @param {Refs} refs instance + * @param {Object} property represented by the collection + * @param {Object} target object the collection is attached to + * + * @return {RefsCollection} the extended array + */ +function extend(collection, refs, property, target) { + + var inverseProperty = property.inverse; + + /** + * Removes the given element from the array and returns it. + * + * @method RefsCollection#remove + * + * @param {Object} element the element to remove + */ + Object.defineProperty(collection, 'remove', { + value: function(element) { + var idx = this.indexOf(element); + if (idx !== -1) { + this.splice(idx, 1); + + // unset inverse + refs.unset(element, inverseProperty, target); + } + + return element; + } + }); + + /** + * Returns true if the collection contains the given element + * + * @method RefsCollection#contains + * + * @param {Object} element the element to check for + */ + Object.defineProperty(collection, 'contains', { + value: function(element) { + return this.indexOf(element) !== -1; + } + }); + + /** + * Adds an element to the array, unless it exists already (set semantics). + * + * @method RefsCollection#add + * + * @param {Object} element the element to add + * @param {Number} optional index to add element to + * (possibly moving other elements around) + */ + Object.defineProperty(collection, 'add', { + value: function(element, idx) { + + var currentIdx = this.indexOf(element); + + if (typeof idx === 'undefined') { + + if (currentIdx !== -1) { + // element already in collection (!) + return; + } + + // add to end of array, as no idx is specified + idx = this.length; + } + + // handle already in collection + if (currentIdx !== -1) { + + // remove element from currentIdx + this.splice(currentIdx, 1); + } + + // add element at idx + this.splice(idx, 0, element); + + if (currentIdx === -1) { + // set inverse, unless element was + // in collection already + refs.set(element, inverseProperty, target); + } + } + }); + + // a simple marker, identifying this element + // as being a refs collection + Object.defineProperty(collection, '__refs_collection', { + value: true + }); + + return collection; +} + + +function isExtended(collection) { + return collection.__refs_collection === true; +} + +collection.extend = extend; + +collection.isExtended = isExtended; + +var Collection = collection; + +function hasOwnProperty$1(e, property) { + return Object.prototype.hasOwnProperty.call(e, property.name || property); +} + +function defineCollectionProperty(ref, property, target) { + + var collection = Collection.extend(target[property.name] || [], ref, property, target); + + Object.defineProperty(target, property.name, { + enumerable: property.enumerable, + value: collection + }); + + if (collection.length) { + + collection.forEach(function(o) { + ref.set(o, property.inverse, target); + }); + } +} + + +function defineProperty$1(ref, property, target) { + + var inverseProperty = property.inverse; + + var _value = target[property.name]; + + Object.defineProperty(target, property.name, { + configurable: property.configurable, + enumerable: property.enumerable, + + get: function() { + return _value; + }, + + set: function(value) { + + // return if we already performed all changes + if (value === _value) { + return; + } + + var old = _value; + + // temporary set null + _value = null; + + if (old) { + ref.unset(old, inverseProperty, target); + } + + // set new value + _value = value; + + // set inverse value + ref.set(_value, inverseProperty, target); + } + }); + +} + +/** + * Creates a new references object defining two inversly related + * attribute descriptors a and b. + * + *

+ * When bound to an object using {@link Refs#bind} the references + * get activated and ensure that add and remove operations are applied + * reversely, too. + *

+ * + *

+ * For attributes represented as collections {@link Refs} provides the + * {@link RefsCollection#add}, {@link RefsCollection#remove} and {@link RefsCollection#contains} extensions + * that must be used to properly hook into the inverse change mechanism. + *

+ * + * @class Refs + * + * @classdesc A bi-directional reference between two attributes. + * + * @param {Refs.AttributeDescriptor} a property descriptor + * @param {Refs.AttributeDescriptor} b property descriptor + * + * @example + * + * var refs = Refs({ name: 'wheels', collection: true, enumerable: true }, { name: 'car' }); + * + * var car = { name: 'toyota' }; + * var wheels = [{ pos: 'front-left' }, { pos: 'front-right' }]; + * + * refs.bind(car, 'wheels'); + * + * car.wheels // [] + * car.wheels.add(wheels[0]); + * car.wheels.add(wheels[1]); + * + * car.wheels // [{ pos: 'front-left' }, { pos: 'front-right' }] + * + * wheels[0].car // { name: 'toyota' }; + * car.wheels.remove(wheels[0]); + * + * wheels[0].car // undefined + */ +function Refs$1(a, b) { + + if (!(this instanceof Refs$1)) { + return new Refs$1(a, b); + } + + // link + a.inverse = b; + b.inverse = a; + + this.props = {}; + this.props[a.name] = a; + this.props[b.name] = b; +} + +/** + * Binds one side of a bi-directional reference to a + * target object. + * + * @memberOf Refs + * + * @param {Object} target + * @param {String} property + */ +Refs$1.prototype.bind = function(target, property) { + if (typeof property === 'string') { + if (!this.props[property]) { + throw new Error('no property <' + property + '> in ref'); + } + property = this.props[property]; + } + + if (property.collection) { + defineCollectionProperty(this, property, target); + } else { + defineProperty$1(this, property, target); + } +}; + +Refs$1.prototype.ensureRefsCollection = function(target, property) { + + var collection = target[property.name]; + + if (!Collection.isExtended(collection)) { + defineCollectionProperty(this, property, target); + } + + return collection; +}; + +Refs$1.prototype.ensureBound = function(target, property) { + if (!hasOwnProperty$1(target, property)) { + this.bind(target, property); + } +}; + +Refs$1.prototype.unset = function(target, property, value) { + + if (target) { + this.ensureBound(target, property); + + if (property.collection) { + this.ensureRefsCollection(target, property).remove(value); + } else { + target[property.name] = undefined; + } + } +}; + +Refs$1.prototype.set = function(target, property, value) { + + if (target) { + this.ensureBound(target, property); + + if (property.collection) { + this.ensureRefsCollection(target, property).add(value); + } else { + target[property.name] = value; + } + } +}; + +var refs = Refs$1; + +objectRefs.exports = refs; + +objectRefs.exports.Collection = collection; + +var objectRefsExports = objectRefs.exports; +var Refs = /*@__PURE__*/getDefaultExportFromCjs(objectRefsExports); + +var parentRefs = new Refs({ name: 'children', enumerable: true, collection: true }, { name: 'parent' }), + labelRefs = new Refs({ name: 'labels', enumerable: true, collection: true }, { name: 'labelTarget' }), + attacherRefs = new Refs({ name: 'attachers', collection: true }, { name: 'host' }), + outgoingRefs = new Refs({ name: 'outgoing', collection: true }, { name: 'source' }), + incomingRefs = new Refs({ name: 'incoming', collection: true }, { name: 'target' }); + +/** + * @typedef {import('./Types').Element} Element + * @typedef {import('./Types').Shape} Shape + * @typedef {import('./Types').Root} Root + * @typedef {import('./Types').Label} Label + * @typedef {import('./Types').Connection} Connection + */ + +/** + * The basic graphical representation + * + * @class + * @constructor + */ +function ElementImpl() { + + /** + * The object that backs up the shape + * + * @name Element#businessObject + * @type Object + */ + Object.defineProperty(this, 'businessObject', { + writable: true + }); + + + /** + * Single label support, will mapped to multi label array + * + * @name Element#label + * @type Object + */ + Object.defineProperty(this, 'label', { + get: function() { + return this.labels[0]; + }, + set: function(newLabel) { + + var label = this.label, + labels = this.labels; + + if (!newLabel && label) { + labels.remove(label); + } else { + labels.add(newLabel, 0); + } + } + }); + + /** + * The parent shape + * + * @name Element#parent + * @type Shape + */ + parentRefs.bind(this, 'parent'); + + /** + * The list of labels + * + * @name Element#labels + * @type Label + */ + labelRefs.bind(this, 'labels'); + + /** + * The list of outgoing connections + * + * @name Element#outgoing + * @type Array + */ + outgoingRefs.bind(this, 'outgoing'); + + /** + * The list of incoming connections + * + * @name Element#incoming + * @type Array + */ + incomingRefs.bind(this, 'incoming'); +} + + +/** + * A graphical object + * + * @class + * @constructor + * + * @extends ElementImpl + */ +function ShapeImpl() { + ElementImpl.call(this); + + /** + * Indicates frame shapes + * + * @name ShapeImpl#isFrame + * @type boolean + */ + + /** + * The list of children + * + * @name ShapeImpl#children + * @type Element[] + */ + parentRefs.bind(this, 'children'); + + /** + * @name ShapeImpl#host + * @type Shape + */ + attacherRefs.bind(this, 'host'); + + /** + * @name ShapeImpl#attachers + * @type Shape + */ + attacherRefs.bind(this, 'attachers'); +} + +e(ShapeImpl, ElementImpl); + + +/** + * A root graphical object + * + * @class + * @constructor + * + * @extends ElementImpl + */ +function RootImpl() { + ElementImpl.call(this); + + /** + * The list of children + * + * @name RootImpl#children + * @type Element[] + */ + parentRefs.bind(this, 'children'); +} + +e(RootImpl, ShapeImpl); + + +/** + * A label for an element + * + * @class + * @constructor + * + * @extends ShapeImpl + */ +function LabelImpl() { + ShapeImpl.call(this); + + /** + * The labeled element + * + * @name LabelImpl#labelTarget + * @type Element + */ + labelRefs.bind(this, 'labelTarget'); +} + +e(LabelImpl, ShapeImpl); + + +/** + * A connection between two elements + * + * @class + * @constructor + * + * @extends ElementImpl + */ +function ConnectionImpl() { + ElementImpl.call(this); + + /** + * The element this connection originates from + * + * @name ConnectionImpl#source + * @type Element + */ + outgoingRefs.bind(this, 'source'); + + /** + * The element this connection points to + * + * @name ConnectionImpl#target + * @type Element + */ + incomingRefs.bind(this, 'target'); +} + +e(ConnectionImpl, ElementImpl); + + +var types$7 = { + connection: ConnectionImpl, + shape: ShapeImpl, + label: LabelImpl, + root: RootImpl +}; + +/** + * Creates a root element. + * + * @overlord + * + * @example + * + * ```javascript + * import * as Model from 'diagram-js/lib/model'; + * + * const root = Model.create('root', { + * x: 100, + * y: 100, + * width: 100, + * height: 100 + * }); + * ``` + * + * @param {'root'} type + * @param {any} [attrs] + * + * @return {Root} + */ + +/** + * Creates a connection. + * + * @overlord + * + * @example + * + * ```javascript + * import * as Model from 'diagram-js/lib/model'; + * + * const connection = Model.create('connection', { + * waypoints: [ + * { x: 100, y: 100 }, + * { x: 200, y: 100 } + * ] + * }); + * ``` + * + * @param {'connection'} type + * @param {any} [attrs] + * + * @return {Connection} + */ + +/** + * Creates a shape. + * + * @overlord + * + * @example + * + * ```javascript + * import * as Model from 'diagram-js/lib/model'; + * + * const shape = Model.create('shape', { + * x: 100, + * y: 100, + * width: 100, + * height: 100 + * }); + * ``` + * + * @param {'shape'} type + * @param {any} [attrs] + * + * @return {Shape} + */ + +/** + * Creates a label. + * + * @example + * + * ```javascript + * import * as Model from 'diagram-js/lib/model'; + * + * const label = Model.create('label', { + * x: 100, + * y: 100, + * width: 100, + * height: 100, + * labelTarget: shape + * }); + * ``` + * + * @param {'label'} type + * @param {Object} [attrs] + * + * @return {Label} + */ +function create$1(type, attrs) { + var Type = types$7[type]; + if (!Type) { + throw new Error('unknown type: <' + type + '>'); + } + return assign$3(new Type(), attrs); +} + +/** + * Checks whether an object is a model instance. + * + * @param {any} obj + * + * @return {boolean} + */ +function isModelElement(obj) { + return obj instanceof ElementImpl; +} + +/** + * @typedef {import('../model/Types').Element} Element + * @typedef {import('../model/Types').Connection} Connection + * @typedef {import('../model/Types').Label} Label + * @typedef {import('../model/Types').Root} Root + * @typedef {import('../model/Types').Shape} Shape + */ + +/** + * A factory for model elements. + * + * @template {Connection} [T=Connection] + * @template {Label} [U=Label] + * @template {Root} [V=Root] + * @template {Shape} [W=Shape] + */ +function ElementFactory$1() { + this._uid = 12; +} + +/** + * Create a root element. + * + * @param {Partial} [attrs] + * + * @return {V} The created root element. + */ +ElementFactory$1.prototype.createRoot = function(attrs) { + return this.create('root', attrs); +}; + +/** + * Create a label. + * + * @param {Partial