diff --git a/apps/tutorial/application.js b/apps/tutorial/application.js index 901530326..dffb325aa 100644 --- a/apps/tutorial/application.js +++ b/apps/tutorial/application.js @@ -9211,9 +9211,9 @@ var Hl = u((r) => typeof r == "object" && r !== null && typeof r.initMenu == "fu function Ie(r) { class e extends r { initMenu() { - this._tippy || this.menuContent !== null && (this.addEventListener("click", this.dispatchShowMenuEvent), this.menu = St(this, { allowHTML: true, animation: false, arrow: false, content: this.menuContent, interactive: true, appendTo: document.body, offset: [0, 16], placement: "top", theme: "operation-menu", trigger: "manual", onShow: this.initMenuItems.bind(this), onHide: () => { - var l, c, f, b; - (l = this.ifTooltip) == null || l.hide(), (c = this.angleTooltip) == null || c.hide(), (f = this.flagTooltip) == null || f.hide(), (b = this.deleteTooltip) == null || b.hide(); + this.menu || this.menuContent !== null && (this.addEventListener("click", this.dispatchShowMenuEvent), this.menu = St(this, { allowHTML: true, animation: false, arrow: false, content: this.menuContent, interactive: true, appendTo: document.body, offset: [0, 16], placement: "top", theme: "operation-menu", trigger: "manual", onShow: this.initMenuItems.bind(this), onHide: () => { + var i, l, c, f; + (i = this.ifTooltip) == null || i.hide(), (l = this.angleTooltip) == null || l.hide(), (c = this.flagTooltip) == null || c.hide(), (f = this.deleteTooltip) == null || f.hide(); } })); } showMenu() { @@ -9223,8 +9223,7 @@ function Ie(r) { this.menu.hide(); } destroyMenu() { - let i = this._tippy; - i == null || i.destroy(); + this.menu.destroy(); } dispatchShowMenuEvent() { this.dispatchEvent(new Event("operation-show-menu", { bubbles: true })); @@ -9296,12 +9295,12 @@ var at = /* @__PURE__ */ __name(class extends Ie(Pe(Me(Oe(xe(HTMLElement))))) { showInspector() { if (F.notNull(this.parentElement), this.parentElement.tagName === "PALETTE-DROPZONE") return; - let e = this._tippy; + let e = this.popup; e && e.destroy(); let t = this.blochInspectorPopupContent(); - St(this, { allowHTML: true, animation: false, arrow: true, delay: 0, placement: "auto", theme: "tooltip", onShow(l) { - l.setContent(t); - } }).show(); + this.popup = St(this, { allowHTML: true, animation: false, arrow: true, delay: 0, placement: "auto", theme: "tooltip", onShow(i) { + i.setContent(t); + } }), this.popup.show(); } blochInspectorPopupContent() { let e = document.createDocumentFragment(); @@ -9330,7 +9329,7 @@ var at = /* @__PURE__ */ __name(class extends Ie(Pe(Me(Oe(xe(HTMLElement))))) { this.shadowRoot === null && (this.attachShadow({ mode: "open" }), this.update(), this.initDraggable(), this.updateBlochVector(), this.addEventListener("mouseenter", this.showInspector)); } disconnectedCallback() { - let e = this._tippy; + let e = this.popup; e == null || e.destroy(); } attributeChangedCallback(e, t, i) { @@ -9475,10 +9474,9 @@ var at = /* @__PURE__ */ __name(class extends Ie(Pe(Me(Oe(xe(HTMLElement))))) { return `"${Bs}"`; } updateBlochVector() { + var t; let e = this.vectorEndCircles[0].offsetWidth; - this.vectorLine.style.height = `calc(${100 * this.d / 2}% - ${e / 2}px)`, this.vectorEnd.style.bottom = `calc(50% + ${100 * this.d / 2}% + ${e / 2}px)`, this.d !== 0 && (this.vector.style.transform = `rotateY(${this.phi}deg) rotateX(${-this.theta}deg)`); - let t = this._tippy; - t == null || t.setContent(this.blochInspectorPopupContent()); + this.vectorLine.style.height = `calc(${100 * this.d / 2}% - ${e / 2}px)`, this.vectorEnd.style.bottom = `calc(50% + ${100 * this.d / 2}% + ${e / 2}px)`, this.d !== 0 && (this.vector.style.transform = `rotateY(${this.phi}deg) rotateX(${-this.theta}deg)`), (t = this.popup) == null || t.setContent(this.blochInspectorPopupContent()); } get d() { let e = this.getAttribute("data-d"); diff --git a/apps/tutorial/application.js.map b/apps/tutorial/application.js.map index 87a6eb3a7..3be8335ef 100644 --- a/apps/tutorial/application.js.map +++ b/apps/tutorial/application.js.map @@ -1,7 +1,7 @@ { "version": 3, "sources": ["../../node_modules/fraction.js/fraction.js", "../../node_modules/interactjs/dist/_header.js", "../../node_modules/interactjs/dist/node_modules/browser-pack-flat/_prelude", "../../node_modules/interactjs/dist/packages/@interactjs/utils/isWindow.ts", "../../node_modules/interactjs/dist/packages/@interactjs/utils/window.ts", "../../node_modules/interactjs/dist/packages/@interactjs/utils/is.ts", "../../node_modules/interactjs/dist/packages/@interactjs/actions/drag/plugin.ts", "../../node_modules/interactjs/dist/packages/@interactjs/utils/domObjects.ts", "../../node_modules/interactjs/dist/packages/@interactjs/utils/browser.ts", "../../node_modules/interactjs/dist/packages/@interactjs/utils/domUtils.ts", "../../node_modules/interactjs/dist/packages/@interactjs/utils/extend.ts", "../../node_modules/interactjs/dist/packages/@interactjs/utils/rect.ts", "../../node_modules/interactjs/dist/packages/@interactjs/utils/getOriginXY.ts", "../../node_modules/interactjs/dist/packages/@interactjs/utils/normalizeListeners.ts", "../../node_modules/interactjs/dist/packages/@interactjs/utils/hypot.ts", "../../node_modules/interactjs/dist/packages/@interactjs/utils/pointerExtend.ts", "../../node_modules/interactjs/dist/packages/@interactjs/utils/pointerUtils.ts", "../../node_modules/interactjs/dist/packages/@interactjs/core/BaseEvent.ts", "../../node_modules/interactjs/dist/packages/@interactjs/utils/arr.ts", "../../node_modules/interactjs/dist/packages/@interactjs/actions/drop/DropEvent.ts", "../../node_modules/interactjs/dist/packages/@interactjs/actions/drop/plugin.ts", "../../node_modules/interactjs/dist/packages/@interactjs/actions/gesture/plugin.ts", "../../node_modules/interactjs/dist/packages/@interactjs/actions/resize/plugin.ts", "../../node_modules/interactjs/dist/packages/@interactjs/actions/plugin.ts", "../../node_modules/interactjs/dist/packages/@interactjs/utils/raf.ts", "../../node_modules/interactjs/dist/packages/@interactjs/auto-scroll/plugin.ts", "../../node_modules/interactjs/dist/packages/@interactjs/utils/misc.ts", "../../node_modules/interactjs/dist/packages/@interactjs/auto-start/InteractableMethods.ts", "../../node_modules/interactjs/dist/packages/@interactjs/auto-start/base.ts", "../../node_modules/interactjs/dist/packages/@interactjs/auto-start/dragAxis.ts", "../../node_modules/interactjs/dist/packages/@interactjs/auto-start/hold.ts", "../../node_modules/interactjs/dist/packages/@interactjs/auto-start/plugin.ts", "../../node_modules/interactjs/dist/packages/@interactjs/core/interactablePreventDefault.ts", "../../node_modules/interactjs/dist/packages/@interactjs/dev-tools/visualizer/plugin.ts", "../../node_modules/interactjs/dist/packages/@interactjs/dev-tools/plugin.ts", "../../node_modules/interactjs/dist/packages/@interactjs/utils/clone.ts", "../../node_modules/interactjs/dist/packages/@interactjs/modifiers/Modification.ts", "../../node_modules/interactjs/dist/packages/@interactjs/modifiers/base.ts", "../../node_modules/interactjs/dist/packages/@interactjs/core/options.ts", "../../node_modules/interactjs/dist/packages/@interactjs/core/InteractEvent.ts", "../../node_modules/interactjs/dist/packages/@interactjs/core/PointerInfo.ts", "../../node_modules/interactjs/dist/packages/@interactjs/core/Interaction.ts", "../../node_modules/interactjs/dist/packages/@interactjs/offset/plugin.ts", "../../node_modules/interactjs/dist/packages/@interactjs/inertia/plugin.ts", "../../node_modules/interactjs/dist/packages/@interactjs/core/Eventable.ts", "../../node_modules/interactjs/dist/packages/@interactjs/core/isNonNativeEvent.ts", "../../node_modules/interactjs/dist/packages/@interactjs/core/InteractStatic.ts", "../../node_modules/interactjs/dist/packages/@interactjs/core/Interactable.ts", "../../node_modules/interactjs/dist/packages/@interactjs/core/InteractableSet.ts", "../../node_modules/interactjs/dist/packages/@interactjs/core/events.ts", "../../node_modules/interactjs/dist/packages/@interactjs/core/interactionFinder.ts", "../../node_modules/interactjs/dist/packages/@interactjs/core/interactions.ts", "../../node_modules/interactjs/dist/packages/@interactjs/core/scope.ts", "../../node_modules/interactjs/dist/packages/@interactjs/core/types.ts", "../../node_modules/interactjs/dist/packages/@interactjs/interact/index.ts", "../../node_modules/interactjs/dist/packages/@interactjs/snappers/edgeTarget.ts", "../../node_modules/interactjs/dist/packages/@interactjs/snappers/elements.ts", "../../node_modules/interactjs/dist/packages/@interactjs/snappers/grid.ts", "../../node_modules/interactjs/dist/packages/@interactjs/snappers/plugin.ts", "../../node_modules/interactjs/dist/packages/@interactjs/modifiers/aspectRatio.ts", "../../node_modules/interactjs/dist/packages/@interactjs/modifiers/noop.ts", "../../node_modules/interactjs/dist/packages/@interactjs/modifiers/restrict/pointer.ts", "../../node_modules/interactjs/dist/packages/@interactjs/modifiers/restrict/edges.ts", "../../node_modules/interactjs/dist/packages/@interactjs/modifiers/restrict/rect.ts", "../../node_modules/interactjs/dist/packages/@interactjs/modifiers/restrict/size.ts", "../../node_modules/interactjs/dist/packages/@interactjs/modifiers/snap/pointer.ts", "../../node_modules/interactjs/dist/packages/@interactjs/modifiers/snap/size.ts", "../../node_modules/interactjs/dist/packages/@interactjs/modifiers/snap/edges.ts", "../../node_modules/interactjs/dist/packages/@interactjs/modifiers/all.ts", "../../node_modules/interactjs/dist/packages/@interactjs/modifiers/plugin.ts", "../../node_modules/interactjs/dist/packages/@interactjs/pointer-events/PointerEvent.ts", "../../node_modules/interactjs/dist/packages/@interactjs/pointer-events/base.ts", "../../node_modules/interactjs/dist/packages/@interactjs/pointer-events/holdRepeat.ts", "../../node_modules/interactjs/dist/packages/@interactjs/pointer-events/interactableTargets.ts", "../../node_modules/interactjs/dist/packages/@interactjs/pointer-events/plugin.ts", "../../node_modules/interactjs/dist/packages/@interactjs/reflow/plugin.ts", "../../node_modules/interactjs/dist/packages/@interactjs/interactjs/index.ts", "../../node_modules/interactjs/dist/packages/interactjs/index.ts", "../../node_modules/interactjs/dist/node_modules/browser-pack-flat/_postlude", "../../node_modules/fastdom/fastdom.js", "../../node_modules/complex.js/complex.js", "../../packages/elements/node_modules/@qni/common/src/angle-parser.ts", "../../packages/elements/node_modules/@qni/common/src/describe.ts", "../../packages/elements/node_modules/@qni/common/src/detailed-error.ts", "../../packages/elements/node_modules/@qni/common/src/format.ts", "../../packages/elements/node_modules/@qni/common/src/util.ts", "../../packages/elements/node_modules/@qni/common/src/complex.ts", "../../packages/elements/node_modules/@qni/common/src/equate.ts", "../../packages/elements/node_modules/@qni/common/src/h-gate.ts", "../../packages/elements/node_modules/@qni/common/src/x-gate.ts", "../../packages/elements/node_modules/@qni/common/src/y-gate.ts", "../../packages/elements/node_modules/@qni/common/src/z-gate.ts", "../../packages/elements/node_modules/@qni/common/src/phase-gate.ts", "../../packages/elements/node_modules/@qni/common/src/t-gate.ts", "../../packages/elements/node_modules/@qni/common/src/rnot-gate.ts", "../../packages/elements/node_modules/@qni/common/src/rx-gate.ts", "../../packages/elements/node_modules/@qni/common/src/ry-gate.ts", "../../packages/elements/node_modules/@qni/common/src/rz-gate.ts", "../../packages/elements/node_modules/@qni/common/src/swap-gate.ts", "../../packages/elements/node_modules/@qni/common/src/control-gate.ts", "../../packages/elements/node_modules/@qni/common/src/bloch-display.ts", "../../packages/elements/node_modules/@qni/common/src/write-gate.ts", "../../packages/elements/node_modules/@qni/common/src/measurement-gate.ts", "../../node_modules/@github/catalyst/src/bind.ts", "../../node_modules/@github/catalyst/src/register.ts", "../../node_modules/@github/catalyst/src/findtarget.ts", "../../node_modules/@github/catalyst/src/target.ts", "../../node_modules/@github/catalyst/src/auto-shadow-root.ts", "../../node_modules/@github/catalyst/src/attr.ts", "../../node_modules/@github/catalyst/src/core.ts", "../../node_modules/@github/catalyst/src/controller.ts", "../../packages/elements/src/mixin/activateable.ts", "../../packages/elements/src/mixin/angleable.ts", "../../packages/elements/src/mixin/controllable.ts", "../../packages/elements/src/mixin/disableable.ts", "../../node_modules/xstate/es/_virtual/_tslib.js", "../../node_modules/xstate/es/types.js", "../../node_modules/xstate/es/actionTypes.js", "../../node_modules/xstate/es/constants.js", "../../node_modules/xstate/es/environment.js", "../../node_modules/xstate/es/utils.js", "../../node_modules/xstate/es/actions.js", "../../node_modules/xstate/es/serviceScope.js", "../../node_modules/xstate/es/Actor.js", "../../node_modules/xstate/es/stateUtils.js", "../../node_modules/xstate/es/State.js", "../../node_modules/xstate/es/scheduler.js", "../../node_modules/xstate/es/registry.js", "../../node_modules/xstate/es/devTools.js", "../../node_modules/xstate/es/behaviors.js", "../../node_modules/xstate/es/interpreter.js", "../../node_modules/xstate/es/invokeUtils.js", "../../node_modules/xstate/es/StateNode.js", "../../node_modules/xstate/es/Machine.js", "../../packages/elements/src/mixin/draggable.ts", "../../packages/elements/src/mixin/flaggable.ts", "../../node_modules/@popperjs/core/lib/enums.js", "../../node_modules/@popperjs/core/lib/dom-utils/getNodeName.js", "../../node_modules/@popperjs/core/lib/dom-utils/getWindow.js", "../../node_modules/@popperjs/core/lib/dom-utils/instanceOf.js", "../../node_modules/@popperjs/core/lib/modifiers/applyStyles.js", "../../node_modules/@popperjs/core/lib/utils/getBasePlacement.js", "../../node_modules/@popperjs/core/lib/utils/math.js", "../../node_modules/@popperjs/core/lib/dom-utils/getBoundingClientRect.js", "../../node_modules/@popperjs/core/lib/dom-utils/getLayoutRect.js", "../../node_modules/@popperjs/core/lib/dom-utils/contains.js", "../../node_modules/@popperjs/core/lib/dom-utils/getComputedStyle.js", "../../node_modules/@popperjs/core/lib/dom-utils/isTableElement.js", "../../node_modules/@popperjs/core/lib/dom-utils/getDocumentElement.js", "../../node_modules/@popperjs/core/lib/dom-utils/getParentNode.js", "../../node_modules/@popperjs/core/lib/dom-utils/getOffsetParent.js", "../../node_modules/@popperjs/core/lib/utils/getMainAxisFromPlacement.js", "../../node_modules/@popperjs/core/lib/utils/within.js", "../../node_modules/@popperjs/core/lib/utils/getFreshSideObject.js", "../../node_modules/@popperjs/core/lib/utils/mergePaddingObject.js", "../../node_modules/@popperjs/core/lib/utils/expandToHashMap.js", "../../node_modules/@popperjs/core/lib/modifiers/arrow.js", "../../node_modules/@popperjs/core/lib/utils/getVariation.js", "../../node_modules/@popperjs/core/lib/modifiers/computeStyles.js", "../../node_modules/@popperjs/core/lib/modifiers/eventListeners.js", "../../node_modules/@popperjs/core/lib/utils/getOppositePlacement.js", "../../node_modules/@popperjs/core/lib/utils/getOppositeVariationPlacement.js", "../../node_modules/@popperjs/core/lib/dom-utils/getWindowScroll.js", "../../node_modules/@popperjs/core/lib/dom-utils/getWindowScrollBarX.js", "../../node_modules/@popperjs/core/lib/dom-utils/getViewportRect.js", "../../node_modules/@popperjs/core/lib/dom-utils/getDocumentRect.js", "../../node_modules/@popperjs/core/lib/dom-utils/isScrollParent.js", "../../node_modules/@popperjs/core/lib/dom-utils/getScrollParent.js", "../../node_modules/@popperjs/core/lib/dom-utils/listScrollParents.js", "../../node_modules/@popperjs/core/lib/utils/rectToClientRect.js", "../../node_modules/@popperjs/core/lib/dom-utils/getClippingRect.js", "../../node_modules/@popperjs/core/lib/utils/computeOffsets.js", "../../node_modules/@popperjs/core/lib/utils/detectOverflow.js", "../../node_modules/@popperjs/core/lib/utils/computeAutoPlacement.js", "../../node_modules/@popperjs/core/lib/modifiers/flip.js", "../../node_modules/@popperjs/core/lib/modifiers/hide.js", "../../node_modules/@popperjs/core/lib/modifiers/offset.js", "../../node_modules/@popperjs/core/lib/modifiers/popperOffsets.js", "../../node_modules/@popperjs/core/lib/utils/getAltAxis.js", "../../node_modules/@popperjs/core/lib/modifiers/preventOverflow.js", "../../node_modules/@popperjs/core/lib/dom-utils/getHTMLElementScroll.js", "../../node_modules/@popperjs/core/lib/dom-utils/getNodeScroll.js", "../../node_modules/@popperjs/core/lib/dom-utils/getCompositeRect.js", "../../node_modules/@popperjs/core/lib/utils/orderModifiers.js", "../../node_modules/@popperjs/core/lib/utils/debounce.js", "../../node_modules/@popperjs/core/lib/utils/mergeByName.js", "../../node_modules/@popperjs/core/lib/createPopper.js", "../../node_modules/@popperjs/core/lib/popper.js", "../../node_modules/tippy.js/src/constants.ts", "../../node_modules/tippy.js/src/utils.ts", "../../node_modules/tippy.js/src/dom-utils.ts", "../../node_modules/tippy.js/src/bindGlobalEventListeners.ts", "../../node_modules/tippy.js/src/browser.ts", "../../node_modules/tippy.js/src/validation.ts", "../../node_modules/tippy.js/src/props.ts", "../../node_modules/tippy.js/src/template.ts", "../../node_modules/tippy.js/src/createTippy.ts", "../../node_modules/tippy.js/src/index.ts", "../../node_modules/tippy.js/src/addons/createSingleton.ts", "../../node_modules/tippy.js/src/addons/delegate.ts", "../../node_modules/tippy.js/src/plugins/animateFill.ts", "../../node_modules/tippy.js/src/plugins/followCursor.ts", "../../node_modules/tippy.js/src/plugins/inlinePositioning.ts", "../../node_modules/tippy.js/src/plugins/sticky.ts", "../../node_modules/tippy.js/build/base.js", "../../packages/elements/src/mixin/helpable.ts", "../../packages/elements/src/mixin/hoverable.ts", "../../node_modules/@github/template-parts/src/template-string-parser.ts", "../../node_modules/@github/template-parts/src/attribute-template-part.ts", "../../node_modules/@github/template-parts/src/node-template-part.ts", "../../node_modules/@github/template-parts/src/processors.ts", "../../node_modules/@github/template-parts/src/template-instance.ts", "../../node_modules/@github/jtml/src/directive.ts", "../../node_modules/@github/jtml/src/events.ts", "../../node_modules/@github/jtml/src/html.ts", "../../node_modules/@github/jtml/src/until.ts", "../../node_modules/@github/jtml/src/unsafe-html.ts", "../../packages/elements/src/mixin/iconable.ts", "../../packages/elements/src/mixin/ifable.ts", "../../packages/elements/src/mixin/menuable.ts", "../../packages/elements/src/util.ts", "../../packages/elements/src/bloch-display-element.ts", "../../packages/elements/src/control-gate-element.ts", "../../packages/elements/src/h-gate-element.ts", "../../packages/elements/src/measurement-gate-element.ts", "../../packages/elements/src/phase-gate-element.ts", "../../packages/elements/src/rnot-gate-element.ts", "../../packages/elements/src/rx-gate-element.ts", "../../packages/elements/src/ry-gate-element.ts", "../../packages/elements/src/rz-gate-element.ts", "../../packages/elements/src/swap-gate-element.ts", "../../packages/elements/src/t-gate-element.ts", "../../packages/elements/src/write-gate-element.ts", "../../packages/elements/src/x-gate-element.ts", "../../packages/elements/src/y-gate-element.ts", "../../packages/elements/src/z-gate-element.ts", "../../packages/elements/src/operation.ts", "../../packages/elements/src/angle-slider-element.ts", "../../packages/elements/src/button-group-element.ts", "../../packages/elements/src/circle-notation-element.ts", "../../packages/elements/src/circle-notation-panel-element.ts", "../../packages/elements/src/gate-carousel-element.ts", "../../packages/elements/src/inspector-button-element.ts", "../../packages/elements/src/operation-inspector-element.ts", "../../packages/elements/src/qubit-circle-element.ts", "../../packages/elements/src/run-circuit-button-element.ts", "../../packages/elements/src/slide-in-element.ts", "../../packages/elements/src/circuit-block-element.ts", "../../packages/elements/src/circuit-dropzone-element.ts", "../../packages/elements/src/circuit-step-element.ts", "../../packages/elements/src/circuit-editor-element.ts", "../../packages/elements/src/palette-dropzone-element.ts", "../../packages/elements/src/quantum-circuit-element.ts", "../../packages/elements/src/quantum-simulator-element.ts", "src/serviceworker-companion.js"], - "sourcesContent": ["/**\n * @license Fraction.js v4.2.0 05/03/2022\n * https://www.xarg.org/2014/03/rational-numbers-in-javascript/\n *\n * Copyright (c) 2021, Robert Eisele (robert@xarg.org)\n * Dual licensed under the MIT or GPL Version 2 licenses.\n **/\n\n\n/**\n *\n * This class offers the possibility to calculate fractions.\n * You can pass a fraction in different formats. Either as array, as double, as string or as an integer.\n *\n * Array/Object form\n * [ 0 => , 1 => ]\n * [ n => , d => ]\n *\n * Integer form\n * - Single integer value\n *\n * Double form\n * - Single double value\n *\n * String form\n * 123.456 - a simple double\n * 123/456 - a string fraction\n * 123.'456' - a double with repeating decimal places\n * 123.(456) - synonym\n * 123.45'6' - a double with repeating last place\n * 123.45(6) - synonym\n *\n * Example:\n *\n * var f = new Fraction(\"9.4'31'\");\n * f.mul([-4, 3]).div(4.9);\n *\n */\n\n(function(root) {\n\n \"use strict\";\n\n // Maximum search depth for cyclic rational numbers. 2000 should be more than enough.\n // Example: 1/7 = 0.(142857) has 6 repeating decimal places.\n // If MAX_CYCLE_LEN gets reduced, long cycles will not be detected and toString() only gets the first 10 digits\n var MAX_CYCLE_LEN = 2000;\n\n // Parsed data to avoid calling \"new\" all the time\n var P = {\n \"s\": 1,\n \"n\": 0,\n \"d\": 1\n };\n\n function assign(n, s) {\n\n if (isNaN(n = parseInt(n, 10))) {\n throw Fraction['InvalidParameter'];\n }\n return n * s;\n }\n\n // Creates a new Fraction internally without the need of the bulky constructor\n function newFraction(n, d) {\n\n if (d === 0) {\n throw Fraction['DivisionByZero'];\n }\n\n var f = Object.create(Fraction.prototype);\n f[\"s\"] = n < 0 ? -1 : 1;\n\n n = n < 0 ? -n : n;\n\n var a = gcd(n, d);\n\n f[\"n\"] = n / a;\n f[\"d\"] = d / a;\n return f;\n }\n\n function factorize(num) {\n\n var factors = {};\n\n var n = num;\n var i = 2;\n var s = 4;\n\n while (s <= n) {\n\n while (n % i === 0) {\n n/= i;\n factors[i] = (factors[i] || 0) + 1;\n }\n s+= 1 + 2 * i++;\n }\n\n if (n !== num) {\n if (n > 1)\n factors[n] = (factors[n] || 0) + 1;\n } else {\n factors[num] = (factors[num] || 0) + 1;\n }\n return factors;\n }\n\n var parse = function(p1, p2) {\n\n var n = 0, d = 1, s = 1;\n var v = 0, w = 0, x = 0, y = 1, z = 1;\n\n var A = 0, B = 1;\n var C = 1, D = 1;\n\n var N = 10000000;\n var M;\n\n if (p1 === undefined || p1 === null) {\n /* void */\n } else if (p2 !== undefined) {\n n = p1;\n d = p2;\n s = n * d;\n\n if (n % 1 !== 0 || d % 1 !== 0) {\n throw Fraction['NonIntegerParameter'];\n }\n\n } else\n switch (typeof p1) {\n\n case \"object\":\n {\n if (\"d\" in p1 && \"n\" in p1) {\n n = p1[\"n\"];\n d = p1[\"d\"];\n if (\"s\" in p1)\n n*= p1[\"s\"];\n } else if (0 in p1) {\n n = p1[0];\n if (1 in p1)\n d = p1[1];\n } else {\n throw Fraction['InvalidParameter'];\n }\n s = n * d;\n break;\n }\n case \"number\":\n {\n if (p1 < 0) {\n s = p1;\n p1 = -p1;\n }\n\n if (p1 % 1 === 0) {\n n = p1;\n } else if (p1 > 0) { // check for != 0, scale would become NaN (log(0)), which converges really slow\n\n if (p1 >= 1) {\n z = Math.pow(10, Math.floor(1 + Math.log(p1) / Math.LN10));\n p1/= z;\n }\n\n // Using Farey Sequences\n // http://www.johndcook.com/blog/2010/10/20/best-rational-approximation/\n\n while (B <= N && D <= N) {\n M = (A + C) / (B + D);\n\n if (p1 === M) {\n if (B + D <= N) {\n n = A + C;\n d = B + D;\n } else if (D > B) {\n n = C;\n d = D;\n } else {\n n = A;\n d = B;\n }\n break;\n\n } else {\n\n if (p1 > M) {\n A+= C;\n B+= D;\n } else {\n C+= A;\n D+= B;\n }\n\n if (B > N) {\n n = C;\n d = D;\n } else {\n n = A;\n d = B;\n }\n }\n }\n n*= z;\n } else if (isNaN(p1) || isNaN(p2)) {\n d = n = NaN;\n }\n break;\n }\n case \"string\":\n {\n B = p1.match(/\\d+|./g);\n\n if (B === null)\n throw Fraction['InvalidParameter'];\n\n if (B[A] === '-') {// Check for minus sign at the beginning\n s = -1;\n A++;\n } else if (B[A] === '+') {// Check for plus sign at the beginning\n A++;\n }\n\n if (B.length === A + 1) { // Check if it's just a simple number \"1234\"\n w = assign(B[A++], s);\n } else if (B[A + 1] === '.' || B[A] === '.') { // Check if it's a decimal number\n\n if (B[A] !== '.') { // Handle 0.5 and .5\n v = assign(B[A++], s);\n }\n A++;\n\n // Check for decimal places\n if (A + 1 === B.length || B[A + 1] === '(' && B[A + 3] === ')' || B[A + 1] === \"'\" && B[A + 3] === \"'\") {\n w = assign(B[A], s);\n y = Math.pow(10, B[A].length);\n A++;\n }\n\n // Check for repeating places\n if (B[A] === '(' && B[A + 2] === ')' || B[A] === \"'\" && B[A + 2] === \"'\") {\n x = assign(B[A + 1], s);\n z = Math.pow(10, B[A + 1].length) - 1;\n A+= 3;\n }\n\n } else if (B[A + 1] === '/' || B[A + 1] === ':') { // Check for a simple fraction \"123/456\" or \"123:456\"\n w = assign(B[A], s);\n y = assign(B[A + 2], 1);\n A+= 3;\n } else if (B[A + 3] === '/' && B[A + 1] === ' ') { // Check for a complex fraction \"123 1/2\"\n v = assign(B[A], s);\n w = assign(B[A + 2], s);\n y = assign(B[A + 4], 1);\n A+= 5;\n }\n\n if (B.length <= A) { // Check for more tokens on the stack\n d = y * z;\n s = /* void */\n n = x + d * v + z * w;\n break;\n }\n\n /* Fall through on error */\n }\n default:\n throw Fraction['InvalidParameter'];\n }\n\n if (d === 0) {\n throw Fraction['DivisionByZero'];\n }\n\n P[\"s\"] = s < 0 ? -1 : 1;\n P[\"n\"] = Math.abs(n);\n P[\"d\"] = Math.abs(d);\n };\n\n function modpow(b, e, m) {\n\n var r = 1;\n for (; e > 0; b = (b * b) % m, e >>= 1) {\n\n if (e & 1) {\n r = (r * b) % m;\n }\n }\n return r;\n }\n\n\n function cycleLen(n, d) {\n\n for (; d % 2 === 0;\n d/= 2) {\n }\n\n for (; d % 5 === 0;\n d/= 5) {\n }\n\n if (d === 1) // Catch non-cyclic numbers\n return 0;\n\n // If we would like to compute really large numbers quicker, we could make use of Fermat's little theorem:\n // 10^(d-1) % d == 1\n // However, we don't need such large numbers and MAX_CYCLE_LEN should be the capstone,\n // as we want to translate the numbers to strings.\n\n var rem = 10 % d;\n var t = 1;\n\n for (; rem !== 1; t++) {\n rem = rem * 10 % d;\n\n if (t > MAX_CYCLE_LEN)\n return 0; // Returning 0 here means that we don't print it as a cyclic number. It's likely that the answer is `d-1`\n }\n return t;\n }\n\n\n function cycleStart(n, d, len) {\n\n var rem1 = 1;\n var rem2 = modpow(10, len, d);\n\n for (var t = 0; t < 300; t++) { // s < ~log10(Number.MAX_VALUE)\n // Solve 10^s == 10^(s+t) (mod d)\n\n if (rem1 === rem2)\n return t;\n\n rem1 = rem1 * 10 % d;\n rem2 = rem2 * 10 % d;\n }\n return 0;\n }\n\n function gcd(a, b) {\n\n if (!a)\n return b;\n if (!b)\n return a;\n\n while (1) {\n a%= b;\n if (!a)\n return b;\n b%= a;\n if (!b)\n return a;\n }\n };\n\n /**\n * Module constructor\n *\n * @constructor\n * @param {number|Fraction=} a\n * @param {number=} b\n */\n function Fraction(a, b) {\n\n parse(a, b);\n\n if (this instanceof Fraction) {\n a = gcd(P[\"d\"], P[\"n\"]); // Abuse variable a\n this[\"s\"] = P[\"s\"];\n this[\"n\"] = P[\"n\"] / a;\n this[\"d\"] = P[\"d\"] / a;\n } else {\n return newFraction(P['s'] * P['n'], P['d']);\n }\n }\n\n Fraction['DivisionByZero'] = new Error(\"Division by Zero\");\n Fraction['InvalidParameter'] = new Error(\"Invalid argument\");\n Fraction['NonIntegerParameter'] = new Error(\"Parameters must be integer\");\n\n Fraction.prototype = {\n\n \"s\": 1,\n \"n\": 0,\n \"d\": 1,\n\n /**\n * Calculates the absolute value\n *\n * Ex: new Fraction(-4).abs() => 4\n **/\n \"abs\": function() {\n\n return newFraction(this[\"n\"], this[\"d\"]);\n },\n\n /**\n * Inverts the sign of the current fraction\n *\n * Ex: new Fraction(-4).neg() => 4\n **/\n \"neg\": function() {\n\n return newFraction(-this[\"s\"] * this[\"n\"], this[\"d\"]);\n },\n\n /**\n * Adds two rational numbers\n *\n * Ex: new Fraction({n: 2, d: 3}).add(\"14.9\") => 467 / 30\n **/\n \"add\": function(a, b) {\n\n parse(a, b);\n return newFraction(\n this[\"s\"] * this[\"n\"] * P[\"d\"] + P[\"s\"] * this[\"d\"] * P[\"n\"],\n this[\"d\"] * P[\"d\"]\n );\n },\n\n /**\n * Subtracts two rational numbers\n *\n * Ex: new Fraction({n: 2, d: 3}).add(\"14.9\") => -427 / 30\n **/\n \"sub\": function(a, b) {\n\n parse(a, b);\n return newFraction(\n this[\"s\"] * this[\"n\"] * P[\"d\"] - P[\"s\"] * this[\"d\"] * P[\"n\"],\n this[\"d\"] * P[\"d\"]\n );\n },\n\n /**\n * Multiplies two rational numbers\n *\n * Ex: new Fraction(\"-17.(345)\").mul(3) => 5776 / 111\n **/\n \"mul\": function(a, b) {\n\n parse(a, b);\n return newFraction(\n this[\"s\"] * P[\"s\"] * this[\"n\"] * P[\"n\"],\n this[\"d\"] * P[\"d\"]\n );\n },\n\n /**\n * Divides two rational numbers\n *\n * Ex: new Fraction(\"-17.(345)\").inverse().div(3)\n **/\n \"div\": function(a, b) {\n\n parse(a, b);\n return newFraction(\n this[\"s\"] * P[\"s\"] * this[\"n\"] * P[\"d\"],\n this[\"d\"] * P[\"n\"]\n );\n },\n\n /**\n * Clones the actual object\n *\n * Ex: new Fraction(\"-17.(345)\").clone()\n **/\n \"clone\": function() {\n return newFraction(this['s'] * this['n'], this['d']);\n },\n\n /**\n * Calculates the modulo of two rational numbers - a more precise fmod\n *\n * Ex: new Fraction('4.(3)').mod([7, 8]) => (13/3) % (7/8) = (5/6)\n **/\n \"mod\": function(a, b) {\n\n if (isNaN(this['n']) || isNaN(this['d'])) {\n return new Fraction(NaN);\n }\n\n if (a === undefined) {\n return newFraction(this[\"s\"] * this[\"n\"] % this[\"d\"], 1);\n }\n\n parse(a, b);\n if (0 === P[\"n\"] && 0 === this[\"d\"]) {\n throw Fraction['DivisionByZero'];\n }\n\n /*\n * First silly attempt, kinda slow\n *\n return that[\"sub\"]({\n \"n\": num[\"n\"] * Math.floor((this.n / this.d) / (num.n / num.d)),\n \"d\": num[\"d\"],\n \"s\": this[\"s\"]\n });*/\n\n /*\n * New attempt: a1 / b1 = a2 / b2 * q + r\n * => b2 * a1 = a2 * b1 * q + b1 * b2 * r\n * => (b2 * a1 % a2 * b1) / (b1 * b2)\n */\n return newFraction(\n this[\"s\"] * (P[\"d\"] * this[\"n\"]) % (P[\"n\"] * this[\"d\"]),\n P[\"d\"] * this[\"d\"]\n );\n },\n\n /**\n * Calculates the fractional gcd of two rational numbers\n *\n * Ex: new Fraction(5,8).gcd(3,7) => 1/56\n */\n \"gcd\": function(a, b) {\n\n parse(a, b);\n\n // gcd(a / b, c / d) = gcd(a, c) / lcm(b, d)\n\n return newFraction(gcd(P[\"n\"], this[\"n\"]) * gcd(P[\"d\"], this[\"d\"]), P[\"d\"] * this[\"d\"]);\n },\n\n /**\n * Calculates the fractional lcm of two rational numbers\n *\n * Ex: new Fraction(5,8).lcm(3,7) => 15\n */\n \"lcm\": function(a, b) {\n\n parse(a, b);\n\n // lcm(a / b, c / d) = lcm(a, c) / gcd(b, d)\n\n if (P[\"n\"] === 0 && this[\"n\"] === 0) {\n return newFraction(0, 1);\n }\n return newFraction(P[\"n\"] * this[\"n\"], gcd(P[\"n\"], this[\"n\"]) * gcd(P[\"d\"], this[\"d\"]));\n },\n\n /**\n * Calculates the ceil of a rational number\n *\n * Ex: new Fraction('4.(3)').ceil() => (5 / 1)\n **/\n \"ceil\": function(places) {\n\n places = Math.pow(10, places || 0);\n\n if (isNaN(this[\"n\"]) || isNaN(this[\"d\"])) {\n return new Fraction(NaN);\n }\n return newFraction(Math.ceil(places * this[\"s\"] * this[\"n\"] / this[\"d\"]), places);\n },\n\n /**\n * Calculates the floor of a rational number\n *\n * Ex: new Fraction('4.(3)').floor() => (4 / 1)\n **/\n \"floor\": function(places) {\n\n places = Math.pow(10, places || 0);\n\n if (isNaN(this[\"n\"]) || isNaN(this[\"d\"])) {\n return new Fraction(NaN);\n }\n return newFraction(Math.floor(places * this[\"s\"] * this[\"n\"] / this[\"d\"]), places);\n },\n\n /**\n * Rounds a rational numbers\n *\n * Ex: new Fraction('4.(3)').round() => (4 / 1)\n **/\n \"round\": function(places) {\n\n places = Math.pow(10, places || 0);\n\n if (isNaN(this[\"n\"]) || isNaN(this[\"d\"])) {\n return new Fraction(NaN);\n }\n return newFraction(Math.round(places * this[\"s\"] * this[\"n\"] / this[\"d\"]), places);\n },\n\n /**\n * Gets the inverse of the fraction, means numerator and denominator are exchanged\n *\n * Ex: new Fraction([-3, 4]).inverse() => -4 / 3\n **/\n \"inverse\": function() {\n\n return newFraction(this[\"s\"] * this[\"d\"], this[\"n\"]);\n },\n\n /**\n * Calculates the fraction to some rational exponent, if possible\n *\n * Ex: new Fraction(-1,2).pow(-3) => -8\n */\n \"pow\": function(a, b) {\n\n parse(a, b);\n\n // Trivial case when exp is an integer\n\n if (P['d'] === 1) {\n\n if (P['s'] < 0) {\n return newFraction(Math.pow(this['s'] * this[\"d\"], P['n']), Math.pow(this[\"n\"], P['n']));\n } else {\n return newFraction(Math.pow(this['s'] * this[\"n\"], P['n']), Math.pow(this[\"d\"], P['n']));\n }\n }\n\n // Negative roots become complex\n // (-a/b)^(c/d) = x\n // <=> (-1)^(c/d) * (a/b)^(c/d) = x\n // <=> (cos(pi) + i*sin(pi))^(c/d) * (a/b)^(c/d) = x # rotate 1 by 180\u00B0\n // <=> (cos(c*pi/d) + i*sin(c*pi/d)) * (a/b)^(c/d) = x # DeMoivre's formula in Q ( https://proofwiki.org/wiki/De_Moivre%27s_Formula/Rational_Index )\n // From which follows that only for c=0 the root is non-complex. c/d is a reduced fraction, so that sin(c/dpi)=0 occurs for d=1, which is handled by our trivial case.\n if (this['s'] < 0) return null;\n\n // Now prime factor n and d\n var N = factorize(this['n']);\n var D = factorize(this['d']);\n\n // Exponentiate and take root for n and d individually\n var n = 1;\n var d = 1;\n for (var k in N) {\n if (k === '1') continue;\n if (k === '0') {\n n = 0;\n break;\n }\n N[k]*= P['n'];\n\n if (N[k] % P['d'] === 0) {\n N[k]/= P['d'];\n } else return null;\n n*= Math.pow(k, N[k]);\n }\n\n for (var k in D) {\n if (k === '1') continue;\n D[k]*= P['n'];\n\n if (D[k] % P['d'] === 0) {\n D[k]/= P['d'];\n } else return null;\n d*= Math.pow(k, D[k]);\n }\n\n if (P['s'] < 0) {\n return newFraction(d, n);\n }\n return newFraction(n, d);\n },\n\n /**\n * Check if two rational numbers are the same\n *\n * Ex: new Fraction(19.6).equals([98, 5]);\n **/\n \"equals\": function(a, b) {\n\n parse(a, b);\n return this[\"s\"] * this[\"n\"] * P[\"d\"] === P[\"s\"] * P[\"n\"] * this[\"d\"]; // Same as compare() === 0\n },\n\n /**\n * Check if two rational numbers are the same\n *\n * Ex: new Fraction(19.6).equals([98, 5]);\n **/\n \"compare\": function(a, b) {\n\n parse(a, b);\n var t = (this[\"s\"] * this[\"n\"] * P[\"d\"] - P[\"s\"] * P[\"n\"] * this[\"d\"]);\n return (0 < t) - (t < 0);\n },\n\n \"simplify\": function(eps) {\n\n if (isNaN(this['n']) || isNaN(this['d'])) {\n return this;\n }\n\n eps = eps || 0.001;\n\n var thisABS = this['abs']();\n var cont = thisABS['toContinued']();\n\n for (var i = 1; i < cont.length; i++) {\n\n var s = newFraction(cont[i - 1], 1);\n for (var k = i - 2; k >= 0; k--) {\n s = s['inverse']()['add'](cont[k]);\n }\n\n if (s['sub'](thisABS)['abs']().valueOf() < eps) {\n return s['mul'](this['s']);\n }\n }\n return this;\n },\n\n /**\n * Check if two rational numbers are divisible\n *\n * Ex: new Fraction(19.6).divisible(1.5);\n */\n \"divisible\": function(a, b) {\n\n parse(a, b);\n return !(!(P[\"n\"] * this[\"d\"]) || ((this[\"n\"] * P[\"d\"]) % (P[\"n\"] * this[\"d\"])));\n },\n\n /**\n * Returns a decimal representation of the fraction\n *\n * Ex: new Fraction(\"100.'91823'\").valueOf() => 100.91823918239183\n **/\n 'valueOf': function() {\n\n return this[\"s\"] * this[\"n\"] / this[\"d\"];\n },\n\n /**\n * Returns a string-fraction representation of a Fraction object\n *\n * Ex: new Fraction(\"1.'3'\").toFraction(true) => \"4 1/3\"\n **/\n 'toFraction': function(excludeWhole) {\n\n var whole, str = \"\";\n var n = this[\"n\"];\n var d = this[\"d\"];\n if (this[\"s\"] < 0) {\n str+= '-';\n }\n\n if (d === 1) {\n str+= n;\n } else {\n\n if (excludeWhole && (whole = Math.floor(n / d)) > 0) {\n str+= whole;\n str+= \" \";\n n%= d;\n }\n\n str+= n;\n str+= '/';\n str+= d;\n }\n return str;\n },\n\n /**\n * Returns a latex representation of a Fraction object\n *\n * Ex: new Fraction(\"1.'3'\").toLatex() => \"\\frac{4}{3}\"\n **/\n 'toLatex': function(excludeWhole) {\n\n var whole, str = \"\";\n var n = this[\"n\"];\n var d = this[\"d\"];\n if (this[\"s\"] < 0) {\n str+= '-';\n }\n\n if (d === 1) {\n str+= n;\n } else {\n\n if (excludeWhole && (whole = Math.floor(n / d)) > 0) {\n str+= whole;\n n%= d;\n }\n\n str+= \"\\\\frac{\";\n str+= n;\n str+= '}{';\n str+= d;\n str+= '}';\n }\n return str;\n },\n\n /**\n * Returns an array of continued fraction elements\n *\n * Ex: new Fraction(\"7/8\").toContinued() => [0,1,7]\n */\n 'toContinued': function() {\n\n var t;\n var a = this['n'];\n var b = this['d'];\n var res = [];\n\n if (isNaN(a) || isNaN(b)) {\n return res;\n }\n\n do {\n res.push(Math.floor(a / b));\n t = a % b;\n a = b;\n b = t;\n } while (a !== 1);\n\n return res;\n },\n\n /**\n * Creates a string representation of a fraction with all digits\n *\n * Ex: new Fraction(\"100.'91823'\").toString() => \"100.(91823)\"\n **/\n 'toString': function(dec) {\n\n var N = this[\"n\"];\n var D = this[\"d\"];\n\n if (isNaN(N) || isNaN(D)) {\n return \"NaN\";\n }\n\n dec = dec || 15; // 15 = decimal places when no repetation\n\n var cycLen = cycleLen(N, D); // Cycle length\n var cycOff = cycleStart(N, D, cycLen); // Cycle start\n\n var str = this['s'] < 0 ? \"-\" : \"\";\n\n str+= N / D | 0;\n\n N%= D;\n N*= 10;\n\n if (N)\n str+= \".\";\n\n if (cycLen) {\n\n for (var i = cycOff; i--;) {\n str+= N / D | 0;\n N%= D;\n N*= 10;\n }\n str+= \"(\";\n for (var i = cycLen; i--;) {\n str+= N / D | 0;\n N%= D;\n N*= 10;\n }\n str+= \")\";\n } else {\n for (var i = dec; N && i--;) {\n str+= N / D | 0;\n N%= D;\n N*= 10;\n }\n }\n return str;\n }\n };\n\n if (typeof define === \"function\" && define[\"amd\"]) {\n define([], function() {\n return Fraction;\n });\n } else if (typeof exports === \"object\") {\n Object.defineProperty(Fraction, \"__esModule\", { 'value': true });\n Fraction['default'] = Fraction;\n Fraction['Fraction'] = Fraction;\n module['exports'] = Fraction;\n } else {\n root['Fraction'] = Fraction;\n }\n\n})(this);\n", "/**\n * interact.js 1.10.14\n *\n * Copyright (c) 2012-present Taye Adeyemi \n * https://interactjs.io/license\n */\n", "(function(f){if(typeof exports===\"object\"&&typeof module!==\"undefined\"){module.exports=f()}else if(typeof define===\"function\"&&define.amd){define([],f)}else{var g;if(typeof window!==\"undefined\"){g=window}else if(typeof global!==\"undefined\"){g=global}else if(typeof self!==\"undefined\"){g=self}else{g=this}g.interact = f()}})(function(){var define,module,exports;\n", "export default (thing: any) => !!(thing && thing.Window) && thing instanceof thing.Window\n", "import isWindow from './isWindow'\n\nexport let realWindow = undefined as Window\n\nlet win = undefined as Window\nexport { win as window }\n\nexport function init (window: Window & { wrap?: (...args: any[]) => any }) {\n // get wrapped window if using Shadow DOM polyfill\n\n realWindow = window\n\n // create a TextNode\n const el = window.document.createTextNode('')\n\n // check if it's wrapped by a polyfill\n if (el.ownerDocument !== window.document && typeof window.wrap === 'function' && window.wrap(el) === el) {\n // use wrapped window\n window = window.wrap(window)\n }\n\n win = window\n}\n\nif (typeof window !== 'undefined' && !!window) {\n init(window)\n}\n\nexport function getWindow (node: any) {\n if (isWindow(node)) {\n return node\n }\n\n const rootNode = node.ownerDocument || node\n\n return rootNode.defaultView || win.window\n}\n", "import isWindow from './isWindow'\nimport * as win from './window'\n\nconst window = (thing: any): thing is Window => thing === win.window || isWindow(thing)\n\nconst docFrag = (thing: any): thing is DocumentFragment => object(thing) && thing.nodeType === 11\n\nconst object = (thing: any): thing is { [index: string]: any } => !!thing && typeof thing === 'object'\n\nconst func = (thing: any): thing is (...args: any[]) => any => typeof thing === 'function'\n\nconst number = (thing: any): thing is number => typeof thing === 'number'\n\nconst bool = (thing: any): thing is boolean => typeof thing === 'boolean'\n\nconst string = (thing: any): thing is string => typeof thing === 'string'\n\nconst element = (thing: any): thing is HTMLElement | SVGElement => {\n if (!thing || typeof thing !== 'object') {\n return false\n }\n\n const _window = win.getWindow(thing) || win.window\n\n return /object|function/.test(typeof Element)\n ? thing instanceof Element || thing instanceof _window.Element\n : thing.nodeType === 1 && typeof thing.nodeName === 'string'\n}\n\nconst plainObject: typeof object = (thing: any): thing is { [index: string]: any } =>\n object(thing) && !!thing.constructor && /function Object\\b/.test(thing.constructor.toString())\n\nconst array = (thing: any): thing is T[] =>\n object(thing) && typeof thing.length !== 'undefined' && func(thing.splice)\n\nexport default {\n window,\n docFrag,\n object,\n func,\n number,\n bool,\n string,\n element,\n plainObject,\n array,\n}\n", "import type { InteractEvent } from '@interactjs/core/InteractEvent'\nimport type { Interactable } from '@interactjs/core/Interactable'\nimport type { PerActionDefaults } from '@interactjs/core/options'\nimport type { Scope, Plugin } from '@interactjs/core/scope'\nimport type { ActionMethod, ListenersArg } from '@interactjs/core/types'\nimport is from '@interactjs/utils/is'\n\ndeclare module '@interactjs/core/Interactable' {\n interface Interactable {\n draggable: DraggableMethod\n }\n}\n\ndeclare module '@interactjs/core/options' {\n interface ActionDefaults {\n drag: DraggableOptions\n }\n}\n\ndeclare module '@interactjs/core/types' {\n interface ActionMap {\n drag?: typeof drag\n }\n}\n\nexport type DragEvent = InteractEvent<'drag'>\n\nexport type DraggableMethod = ActionMethod\n\nexport interface DraggableOptions extends PerActionDefaults {\n startAxis?: 'x' | 'y' | 'xy'\n lockAxis?: 'x' | 'y' | 'xy' | 'start'\n oninertiastart?: ListenersArg\n onstart?: ListenersArg\n onmove?: ListenersArg\n onend?: ListenersArg\n}\n\nfunction install (scope: Scope) {\n const { actions, Interactable, defaults } = scope\n\n Interactable.prototype.draggable = drag.draggable\n\n actions.map.drag = drag\n actions.methodDict.drag = 'draggable'\n\n defaults.actions.drag = drag.defaults\n}\n\nfunction beforeMove ({ interaction }) {\n if (interaction.prepared.name !== 'drag') return\n\n const axis = interaction.prepared.axis\n\n if (axis === 'x') {\n interaction.coords.cur.page.y = interaction.coords.start.page.y\n interaction.coords.cur.client.y = interaction.coords.start.client.y\n\n interaction.coords.velocity.client.y = 0\n interaction.coords.velocity.page.y = 0\n } else if (axis === 'y') {\n interaction.coords.cur.page.x = interaction.coords.start.page.x\n interaction.coords.cur.client.x = interaction.coords.start.client.x\n\n interaction.coords.velocity.client.x = 0\n interaction.coords.velocity.page.x = 0\n }\n}\n\nfunction move ({ iEvent, interaction }) {\n if (interaction.prepared.name !== 'drag') return\n\n const axis = interaction.prepared.axis\n\n if (axis === 'x' || axis === 'y') {\n const opposite = axis === 'x' ? 'y' : 'x'\n\n iEvent.page[opposite] = interaction.coords.start.page[opposite]\n iEvent.client[opposite] = interaction.coords.start.client[opposite]\n iEvent.delta[opposite] = 0\n }\n}\n\n/**\n * ```js\n * interact(element).draggable({\n * onstart: function (event) {},\n * onmove : function (event) {},\n * onend : function (event) {},\n *\n * // the axis in which the first movement must be\n * // for the drag sequence to start\n * // 'xy' by default - any direction\n * startAxis: 'x' || 'y' || 'xy',\n *\n * // 'xy' by default - don't restrict to one axis (move in any direction)\n * // 'x' or 'y' to restrict movement to either axis\n * // 'start' to restrict movement to the axis the drag started in\n * lockAxis: 'x' || 'y' || 'xy' || 'start',\n *\n * // max number of drags that can happen concurrently\n * // with elements of this Interactable. Infinity by default\n * max: Infinity,\n *\n * // max number of drags that can target the same element+Interactable\n * // 1 by default\n * maxPerElement: 2\n * })\n *\n * var isDraggable = interact('element').draggable(); // true\n * ```\n *\n * Get or set whether drag actions can be performed on the target\n *\n * @alias Interactable.prototype.draggable\n *\n * @param {boolean | object} [options] true/false or An object with event\n * listeners to be fired on drag events (object makes the Interactable\n * draggable)\n * @return {boolean | Interactable} boolean indicating if this can be the\n * target of drag events, or this Interctable\n */\nconst draggable: DraggableMethod = function draggable (\n this: Interactable,\n options?: DraggableOptions | boolean,\n): any {\n if (is.object(options)) {\n this.options.drag.enabled = options.enabled !== false\n this.setPerAction('drag', options)\n this.setOnEvents('drag', options)\n\n if (/^(xy|x|y|start)$/.test(options.lockAxis)) {\n this.options.drag.lockAxis = options.lockAxis\n }\n if (/^(xy|x|y)$/.test(options.startAxis)) {\n this.options.drag.startAxis = options.startAxis\n }\n\n return this\n }\n\n if (is.bool(options)) {\n this.options.drag.enabled = options\n\n return this\n }\n\n return this.options.drag as DraggableOptions\n}\n\nconst drag: Plugin = {\n id: 'actions/drag',\n install,\n listeners: {\n 'interactions:before-action-move': beforeMove,\n 'interactions:action-resume': beforeMove,\n\n // dragmove\n 'interactions:action-move': move,\n 'auto-start:check': (arg) => {\n const { interaction, interactable, buttons } = arg\n const dragOptions = interactable.options.drag\n\n if (\n !(dragOptions && dragOptions.enabled) ||\n // check mouseButton setting if the pointer is down\n (interaction.pointerIsDown &&\n /mouse|pointer/.test(interaction.pointerType) &&\n (buttons & interactable.options.drag.mouseButtons) === 0)\n ) {\n return undefined\n }\n\n arg.action = {\n name: 'drag',\n axis: dragOptions.lockAxis === 'start' ? dragOptions.startAxis : dragOptions.lockAxis,\n }\n\n return false\n },\n },\n draggable,\n beforeMove,\n move,\n defaults: {\n startAxis: 'xy',\n lockAxis: 'xy',\n } as DraggableOptions,\n\n getCursor () {\n return 'move'\n },\n}\n\nexport default drag\n", "const domObjects: {\n init: any\n document: Document\n DocumentFragment: typeof DocumentFragment\n SVGElement: typeof SVGElement\n SVGSVGElement: typeof SVGSVGElement\n SVGElementInstance: any\n Element: typeof Element\n HTMLElement: typeof HTMLElement\n Event: typeof Event\n Touch: typeof Touch\n PointerEvent: typeof PointerEvent\n} = {\n init,\n document: null,\n DocumentFragment: null,\n SVGElement: null,\n SVGSVGElement: null,\n SVGElementInstance: null,\n Element: null,\n HTMLElement: null,\n Event: null,\n Touch: null,\n PointerEvent: null,\n}\n\nfunction blank () {}\n\nexport default domObjects\n\nfunction init (window: Window) {\n const win = window as any\n\n domObjects.document = win.document\n domObjects.DocumentFragment = win.DocumentFragment || blank\n domObjects.SVGElement = win.SVGElement || blank\n domObjects.SVGSVGElement = win.SVGSVGElement || blank\n domObjects.SVGElementInstance = win.SVGElementInstance || blank\n domObjects.Element = win.Element || blank\n domObjects.HTMLElement = win.HTMLElement || domObjects.Element\n\n domObjects.Event = win.Event\n domObjects.Touch = win.Touch || blank\n domObjects.PointerEvent = win.PointerEvent || win.MSPointerEvent\n}\n", "import domObjects from './domObjects'\nimport is from './is'\n\nconst browser = {\n init,\n supportsTouch: null as boolean,\n supportsPointerEvent: null as boolean,\n isIOS7: null as boolean,\n isIOS: null as boolean,\n isIe9: null as boolean,\n isOperaMobile: null as boolean,\n prefixedMatchesSelector: null as 'matches',\n pEventTypes: null as {\n up: string\n down: string\n over: string\n out: string\n move: string\n cancel: string\n },\n wheelEvent: null as string,\n}\n\nfunction init (window: any) {\n const Element = domObjects.Element\n const navigator: Partial = window.navigator || {}\n\n // Does the browser support touch input?\n browser.supportsTouch =\n 'ontouchstart' in window ||\n (is.func(window.DocumentTouch) && domObjects.document instanceof window.DocumentTouch)\n\n // Does the browser support PointerEvents\n // https://github.com/taye/interact.js/issues/703#issuecomment-471570492\n browser.supportsPointerEvent = (navigator as any).pointerEnabled !== false && !!domObjects.PointerEvent\n\n browser.isIOS = /iP(hone|od|ad)/.test(navigator.platform)\n\n // scrolling doesn't change the result of getClientRects on iOS 7\n browser.isIOS7 = /iP(hone|od|ad)/.test(navigator.platform) && /OS 7[^\\d]/.test(navigator.appVersion)\n\n browser.isIe9 = /MSIE 9/.test(navigator.userAgent)\n\n // Opera Mobile must be handled differently\n browser.isOperaMobile =\n navigator.appName === 'Opera' && browser.supportsTouch && /Presto/.test(navigator.userAgent)\n\n // prefix matchesSelector\n browser.prefixedMatchesSelector = (\n 'matches' in Element.prototype\n ? 'matches'\n : 'webkitMatchesSelector' in Element.prototype\n ? 'webkitMatchesSelector'\n : 'mozMatchesSelector' in Element.prototype\n ? 'mozMatchesSelector'\n : 'oMatchesSelector' in Element.prototype\n ? 'oMatchesSelector'\n : 'msMatchesSelector'\n ) as 'matches'\n\n browser.pEventTypes = browser.supportsPointerEvent\n ? domObjects.PointerEvent === window.MSPointerEvent\n ? {\n up: 'MSPointerUp',\n down: 'MSPointerDown',\n over: 'mouseover',\n out: 'mouseout',\n move: 'MSPointerMove',\n cancel: 'MSPointerCancel',\n }\n : {\n up: 'pointerup',\n down: 'pointerdown',\n over: 'pointerover',\n out: 'pointerout',\n move: 'pointermove',\n cancel: 'pointercancel',\n }\n : null\n\n // because Webkit and Opera still use 'mousewheel' event type\n browser.wheelEvent = domObjects.document && 'onmousewheel' in domObjects.document ? 'mousewheel' : 'wheel'\n}\n\nexport default browser\n", "import type { Rect, Target, Element } from '@interactjs/core/types'\n\nimport browser from './browser'\nimport domObjects from './domObjects'\nimport is from './is'\nimport * as win from './window'\n\nexport function nodeContains (parent: Node, child: Node) {\n if (parent.contains) {\n return parent.contains(child as Node)\n }\n\n while (child) {\n if (child === parent) {\n return true\n }\n\n child = (child as Node).parentNode\n }\n\n return false\n}\n\nexport function closest (element: Node, selector: string) {\n while (is.element(element)) {\n if (matchesSelector(element, selector)) {\n return element\n }\n\n element = parentNode(element)\n }\n\n return null\n}\n\nexport function parentNode (node: Node | Document) {\n let parent = node.parentNode\n\n if (is.docFrag(parent)) {\n // skip past #shado-root fragments\n // tslint:disable-next-line\n while ((parent = (parent as any).host) && is.docFrag(parent)) {\n continue\n }\n\n return parent\n }\n\n return parent\n}\n\nexport function matchesSelector (element: Element, selector: string) {\n // remove /deep/ from selectors if shadowDOM polyfill is used\n if (win.window !== win.realWindow) {\n selector = selector.replace(/\\/deep\\//g, ' ')\n }\n\n return element[browser.prefixedMatchesSelector](selector)\n}\n\nconst getParent = (el: Node | Document | ShadowRoot) => el.parentNode || (el as ShadowRoot).host\n\n// Test for the element that's \"above\" all other qualifiers\nexport function indexOfDeepestElement (elements: Element[] | NodeListOf) {\n let deepestNodeParents: Node[] = []\n let deepestNodeIndex: number\n\n for (let i = 0; i < elements.length; i++) {\n const currentNode = elements[i]\n const deepestNode: Node = elements[deepestNodeIndex]\n\n // node may appear in elements array multiple times\n if (!currentNode || i === deepestNodeIndex) {\n continue\n }\n\n if (!deepestNode) {\n deepestNodeIndex = i\n continue\n }\n\n const currentNodeParent = getParent(currentNode)\n const deepestNodeParent = getParent(deepestNode)\n\n // check if the deepest or current are document.documentElement/rootElement\n // - if the current node is, do nothing and continue\n if (currentNodeParent === currentNode.ownerDocument) {\n continue\n }\n // - if deepest is, update with the current node and continue to next\n else if (deepestNodeParent === currentNode.ownerDocument) {\n deepestNodeIndex = i\n continue\n }\n\n // compare zIndex of siblings\n if (currentNodeParent === deepestNodeParent) {\n if (zIndexIsHigherThan(currentNode, deepestNode)) {\n deepestNodeIndex = i\n }\n\n continue\n }\n\n // populate the ancestry array for the latest deepest node\n deepestNodeParents = deepestNodeParents.length ? deepestNodeParents : getNodeParents(deepestNode)\n\n let ancestryStart: Node\n\n // if the deepest node is an HTMLElement and the current node is a non root svg element\n if (\n deepestNode instanceof domObjects.HTMLElement &&\n currentNode instanceof domObjects.SVGElement &&\n !(currentNode instanceof domObjects.SVGSVGElement)\n ) {\n // TODO: is this check necessary? Was this for HTML elements embedded in SVG?\n if (currentNode === deepestNodeParent) {\n continue\n }\n\n ancestryStart = currentNode.ownerSVGElement\n } else {\n ancestryStart = currentNode\n }\n\n const currentNodeParents = getNodeParents(ancestryStart, deepestNode.ownerDocument)\n let commonIndex = 0\n\n // get (position of closest common ancestor) + 1\n while (\n currentNodeParents[commonIndex] &&\n currentNodeParents[commonIndex] === deepestNodeParents[commonIndex]\n ) {\n commonIndex++\n }\n\n const parents = [\n currentNodeParents[commonIndex - 1],\n currentNodeParents[commonIndex],\n deepestNodeParents[commonIndex],\n ]\n\n if (parents[0]) {\n let child = parents[0].lastChild\n\n while (child) {\n if (child === parents[1]) {\n deepestNodeIndex = i\n deepestNodeParents = currentNodeParents\n\n break\n } else if (child === parents[2]) {\n break\n }\n\n child = child.previousSibling\n }\n }\n }\n\n return deepestNodeIndex\n}\n\nfunction getNodeParents (node: Node, limit?: Node) {\n const parents: Node[] = []\n let parent: Node = node\n let parentParent: Node\n\n while ((parentParent = getParent(parent)) && parent !== limit && parentParent !== parent.ownerDocument) {\n parents.unshift(parent)\n parent = parentParent\n }\n\n return parents\n}\n\nfunction zIndexIsHigherThan (higherNode: Node, lowerNode: Node) {\n const higherIndex = parseInt(win.getWindow(higherNode).getComputedStyle(higherNode).zIndex, 10) || 0\n const lowerIndex = parseInt(win.getWindow(lowerNode).getComputedStyle(lowerNode).zIndex, 10) || 0\n\n return higherIndex >= lowerIndex\n}\n\nexport function matchesUpTo (element: Element, selector: string, limit: Node) {\n while (is.element(element)) {\n if (matchesSelector(element, selector)) {\n return true\n }\n\n element = parentNode(element) as Element\n\n if (element === limit) {\n return matchesSelector(element, selector)\n }\n }\n\n return false\n}\n\nexport function getActualElement (element: Element) {\n return (element as any).correspondingUseElement || element\n}\n\nexport function getScrollXY (relevantWindow?: Window) {\n relevantWindow = relevantWindow || win.window\n return {\n x: relevantWindow.scrollX || relevantWindow.document.documentElement.scrollLeft,\n y: relevantWindow.scrollY || relevantWindow.document.documentElement.scrollTop,\n }\n}\n\nexport function getElementClientRect (element: Element): Required {\n const clientRect =\n element instanceof domObjects.SVGElement ? element.getBoundingClientRect() : element.getClientRects()[0]\n\n return (\n clientRect && {\n left: clientRect.left,\n right: clientRect.right,\n top: clientRect.top,\n bottom: clientRect.bottom,\n width: clientRect.width || clientRect.right - clientRect.left,\n height: clientRect.height || clientRect.bottom - clientRect.top,\n }\n )\n}\n\nexport function getElementRect (element: Element) {\n const clientRect = getElementClientRect(element)\n\n if (!browser.isIOS7 && clientRect) {\n const scroll = getScrollXY(win.getWindow(element))\n\n clientRect.left += scroll.x\n clientRect.right += scroll.x\n clientRect.top += scroll.y\n clientRect.bottom += scroll.y\n }\n\n return clientRect\n}\n\nexport function getPath (node: Node | Document) {\n const path = []\n\n while (node) {\n path.push(node)\n node = parentNode(node)\n }\n\n return path\n}\n\nexport function trySelector (value: Target) {\n if (!is.string(value)) {\n return false\n }\n\n // an exception will be raised if it is invalid\n domObjects.document.querySelector(value)\n return true\n}\n", "export default function extend (dest: U & Partial, source: T): T & U {\n for (const prop in source) {\n ;(dest as unknown as T)[prop] = source[prop]\n }\n\n const ret = dest as T & U\n\n return ret\n}\n", "import type {\n HasGetRect,\n RectResolvable,\n Rect,\n Element,\n Point,\n FullRect,\n EdgeOptions,\n} from '@interactjs/core/types'\n\nimport { closest, getElementRect, parentNode } from './domUtils'\nimport extend from './extend'\nimport is from './is'\n\nexport function getStringOptionResult (value: any, target: HasGetRect, element: Node) {\n if (value === 'parent') {\n return parentNode(element)\n }\n\n if (value === 'self') {\n return target.getRect(element as Element)\n }\n\n return closest(element, value)\n}\n\nexport function resolveRectLike (\n value: RectResolvable,\n target?: HasGetRect,\n element?: Node,\n functionArgs?: T,\n) {\n let returnValue: any = value\n if (is.string(returnValue)) {\n returnValue = getStringOptionResult(returnValue, target, element)\n } else if (is.func(returnValue)) {\n returnValue = returnValue(...functionArgs)\n }\n\n if (is.element(returnValue)) {\n returnValue = getElementRect(returnValue)\n }\n\n return returnValue as Rect\n}\n\nexport function rectToXY (rect: Rect | Point) {\n return (\n rect && {\n x: 'x' in rect ? rect.x : rect.left,\n y: 'y' in rect ? rect.y : rect.top,\n }\n )\n}\n\nexport function xywhToTlbr> (rect: T) {\n if (rect && !('left' in rect && 'top' in rect)) {\n rect = extend({}, rect)\n\n rect.left = rect.x || 0\n rect.top = rect.y || 0\n rect.right = rect.right || rect.left + rect.width\n rect.bottom = rect.bottom || rect.top + rect.height\n }\n\n return rect as Rect & T\n}\n\nexport function tlbrToXywh (rect: Rect & Partial) {\n if (rect && !('x' in rect && 'y' in rect)) {\n rect = extend({}, rect)\n\n rect.x = rect.left || 0\n rect.y = rect.top || 0\n rect.width = rect.width || (rect.right || 0) - rect.x\n rect.height = rect.height || (rect.bottom || 0) - rect.y\n }\n\n return rect as FullRect & Point\n}\n\nexport function addEdges (edges: EdgeOptions, rect: Rect, delta: Point) {\n if (edges.left) {\n rect.left += delta.x\n }\n if (edges.right) {\n rect.right += delta.x\n }\n if (edges.top) {\n rect.top += delta.y\n }\n if (edges.bottom) {\n rect.bottom += delta.y\n }\n\n rect.width = rect.right - rect.left\n rect.height = rect.bottom - rect.top\n}\n", "import type { PerActionDefaults } from '@interactjs/core/options'\nimport type { ActionName, HasGetRect } from '@interactjs/core/types'\n\nimport { rectToXY, resolveRectLike } from './rect'\n\nexport default function (\n target: HasGetRect & { options: PerActionDefaults },\n element: Node,\n actionName?: ActionName,\n) {\n const actionOptions = (target.options as any)[actionName]\n const actionOrigin = actionOptions && actionOptions.origin\n const origin = actionOrigin || target.options.origin\n\n const originRect = resolveRectLike(origin, target, element, [target && element])\n\n return rectToXY(originRect) || { x: 0, y: 0 }\n}\n", "import type { EventTypes, Listener, ListenersArg } from '@interactjs/core/types'\n\nimport extend from './extend'\nimport is from './is'\n\nexport interface NormalizedListeners {\n [type: string]: Listener[]\n}\n\nexport default function normalize (\n type: EventTypes,\n listeners?: ListenersArg | ListenersArg[],\n result?: NormalizedListeners,\n): NormalizedListeners {\n result = result || {}\n\n if (is.string(type) && type.search(' ') !== -1) {\n type = split(type)\n }\n\n if (is.array(type)) {\n return type.reduce((acc, t) => extend(acc, normalize(t, listeners, result)), result)\n }\n\n // ({ type: fn }) -> ('', { type: fn })\n if (is.object(type)) {\n listeners = type\n type = ''\n }\n\n if (is.func(listeners)) {\n result[type] = result[type] || []\n result[type].push(listeners)\n } else if (is.array(listeners)) {\n for (const l of listeners) {\n normalize(type, l, result)\n }\n } else if (is.object(listeners)) {\n for (const prefix in listeners) {\n const combinedTypes = split(prefix).map((p) => `${type}${p}`)\n\n normalize(combinedTypes, listeners[prefix], result)\n }\n }\n\n return result as NormalizedListeners\n}\n\nfunction split (type: string) {\n return type.trim().split(/ +/)\n}\n", "export default (x: number, y: number) => Math.sqrt(x * x + y * y)\n", "export default function pointerExtend (dest: Partial }>, source: T) {\n dest.__set ||= {} as any\n\n for (const prop in source) {\n if (typeof dest[prop] !== 'function' && prop !== '__set') {\n Object.defineProperty(dest, prop, {\n get () {\n if (prop in dest.__set) return dest.__set[prop]\n\n return (dest.__set[prop] = source[prop] as any)\n },\n set (value: any) {\n dest.__set[prop] = value\n },\n configurable: true,\n })\n }\n }\n return dest\n}\n", "import type { InteractEvent } from '@interactjs/core/InteractEvent'\nimport type { CoordsSetMember, PointerType, Point, PointerEventType, Element } from '@interactjs/core/types'\n\nimport browser from './browser'\nimport dom from './domObjects'\nimport * as domUtils from './domUtils'\nimport hypot from './hypot'\nimport is from './is'\nimport pointerExtend from './pointerExtend'\n\nexport function copyCoords (dest: CoordsSetMember, src: CoordsSetMember) {\n dest.page = dest.page || ({} as any)\n dest.page.x = src.page.x\n dest.page.y = src.page.y\n\n dest.client = dest.client || ({} as any)\n dest.client.x = src.client.x\n dest.client.y = src.client.y\n\n dest.timeStamp = src.timeStamp\n}\n\nexport function setCoordDeltas (targetObj: CoordsSetMember, prev: CoordsSetMember, cur: CoordsSetMember) {\n targetObj.page.x = cur.page.x - prev.page.x\n targetObj.page.y = cur.page.y - prev.page.y\n targetObj.client.x = cur.client.x - prev.client.x\n targetObj.client.y = cur.client.y - prev.client.y\n targetObj.timeStamp = cur.timeStamp - prev.timeStamp\n}\n\nexport function setCoordVelocity (targetObj: CoordsSetMember, delta: CoordsSetMember) {\n const dt = Math.max(delta.timeStamp / 1000, 0.001)\n\n targetObj.page.x = delta.page.x / dt\n targetObj.page.y = delta.page.y / dt\n targetObj.client.x = delta.client.x / dt\n targetObj.client.y = delta.client.y / dt\n targetObj.timeStamp = dt\n}\n\nexport function setZeroCoords (targetObj: CoordsSetMember) {\n targetObj.page.x = 0\n targetObj.page.y = 0\n targetObj.client.x = 0\n targetObj.client.y = 0\n}\n\nexport function isNativePointer (pointer: any) {\n return pointer instanceof dom.Event || pointer instanceof dom.Touch\n}\n\n// Get specified X/Y coords for mouse or event.touches[0]\nexport function getXY (type: string, pointer: PointerType | InteractEvent, xy: Point) {\n xy = xy || ({} as Point)\n type = type || 'page'\n\n xy.x = pointer[(type + 'X') as 'pageX']\n xy.y = pointer[(type + 'Y') as 'pageY']\n\n return xy\n}\n\nexport function getPageXY (pointer: PointerType | InteractEvent, page?: Point) {\n page = page || { x: 0, y: 0 }\n\n // Opera Mobile handles the viewport and scrolling oddly\n if (browser.isOperaMobile && isNativePointer(pointer)) {\n getXY('screen', pointer, page)\n\n page.x += window.scrollX\n page.y += window.scrollY\n } else {\n getXY('page', pointer, page)\n }\n\n return page\n}\n\nexport function getClientXY (pointer: PointerType, client: Point) {\n client = client || ({} as any)\n\n if (browser.isOperaMobile && isNativePointer(pointer)) {\n // Opera Mobile handles the viewport and scrolling oddly\n getXY('screen', pointer, client)\n } else {\n getXY('client', pointer, client)\n }\n\n return client\n}\n\nexport function getPointerId (pointer: { pointerId?: number, identifier?: number, type?: string }) {\n return is.number(pointer.pointerId) ? pointer.pointerId! : pointer.identifier!\n}\n\nexport function setCoords (dest: CoordsSetMember, pointers: any[], timeStamp: number) {\n const pointer = pointers.length > 1 ? pointerAverage(pointers) : pointers[0]\n\n getPageXY(pointer, dest.page)\n getClientXY(pointer, dest.client)\n\n dest.timeStamp = timeStamp\n}\n\nexport function getTouchPair (event: TouchEvent | PointerType[]) {\n const touches: PointerType[] = []\n\n // array of touches is supplied\n if (is.array(event)) {\n touches[0] = event[0]\n touches[1] = event[1]\n }\n // an event\n else {\n if (event.type === 'touchend') {\n if (event.touches.length === 1) {\n touches[0] = event.touches[0]\n touches[1] = event.changedTouches[0]\n } else if (event.touches.length === 0) {\n touches[0] = event.changedTouches[0]\n touches[1] = event.changedTouches[1]\n }\n } else {\n touches[0] = event.touches[0]\n touches[1] = event.touches[1]\n }\n }\n\n return touches\n}\n\nexport function pointerAverage (pointers: PointerType[]) {\n const average = {\n pageX: 0,\n pageY: 0,\n clientX: 0,\n clientY: 0,\n screenX: 0,\n screenY: 0,\n }\n\n type CoordKeys = keyof typeof average\n\n for (const pointer of pointers) {\n for (const prop in average) {\n average[prop as CoordKeys] += pointer[prop as CoordKeys]\n }\n }\n for (const prop in average) {\n average[prop as CoordKeys] /= pointers.length\n }\n\n return average\n}\n\nexport function touchBBox (event: PointerType[]) {\n if (!event.length) {\n return null\n }\n\n const touches = getTouchPair(event)\n const minX = Math.min(touches[0].pageX, touches[1].pageX)\n const minY = Math.min(touches[0].pageY, touches[1].pageY)\n const maxX = Math.max(touches[0].pageX, touches[1].pageX)\n const maxY = Math.max(touches[0].pageY, touches[1].pageY)\n\n return {\n x: minX,\n y: minY,\n left: minX,\n top: minY,\n right: maxX,\n bottom: maxY,\n width: maxX - minX,\n height: maxY - minY,\n }\n}\n\nexport function touchDistance (event: PointerType[] | TouchEvent, deltaSource: string) {\n const sourceX = (deltaSource + 'X') as 'pageX'\n const sourceY = (deltaSource + 'Y') as 'pageY'\n const touches = getTouchPair(event)\n\n const dx = touches[0][sourceX] - touches[1][sourceX]\n const dy = touches[0][sourceY] - touches[1][sourceY]\n\n return hypot(dx, dy)\n}\n\nexport function touchAngle (event: PointerType[] | TouchEvent, deltaSource: string) {\n const sourceX = (deltaSource + 'X') as 'pageX'\n const sourceY = (deltaSource + 'Y') as 'pageY'\n const touches = getTouchPair(event)\n const dx = touches[1][sourceX] - touches[0][sourceX]\n const dy = touches[1][sourceY] - touches[0][sourceY]\n const angle = (180 * Math.atan2(dy, dx)) / Math.PI\n\n return angle\n}\n\nexport function getPointerType (pointer: { pointerType?: string, identifier?: number, type?: string }) {\n return is.string(pointer.pointerType)\n ? pointer.pointerType\n : is.number(pointer.pointerType)\n ? [undefined, undefined, 'touch', 'pen', 'mouse'][pointer.pointerType]!\n : // if the PointerEvent API isn't available, then the \"pointer\" must\n // be either a MouseEvent, TouchEvent, or Touch object\n /touch/.test(pointer.type || '') || pointer instanceof dom.Touch\n ? 'touch'\n : 'mouse'\n}\n\n// [ event.target, event.currentTarget ]\nexport function getEventTargets (event: Event) {\n const path = is.func(event.composedPath)\n ? (event.composedPath() as Element[])\n : (event as unknown as { path: Element[] }).path\n\n return [\n domUtils.getActualElement(path ? path[0] : (event.target as Element)),\n domUtils.getActualElement(event.currentTarget as Element),\n ]\n}\n\nexport function newCoords (): CoordsSetMember {\n return {\n page: { x: 0, y: 0 },\n client: { x: 0, y: 0 },\n timeStamp: 0,\n }\n}\n\nexport function coordsToEvent (coords: MockCoords) {\n const event = {\n coords,\n get page () {\n return this.coords.page\n },\n get client () {\n return this.coords.client\n },\n get timeStamp () {\n return this.coords.timeStamp\n },\n get pageX () {\n return this.coords.page.x\n },\n get pageY () {\n return this.coords.page.y\n },\n get clientX () {\n return this.coords.client.x\n },\n get clientY () {\n return this.coords.client.y\n },\n get pointerId () {\n return this.coords.pointerId\n },\n get target () {\n return this.coords.target\n },\n get type () {\n return this.coords.type\n },\n get pointerType () {\n return this.coords.pointerType\n },\n get buttons () {\n return this.coords.buttons\n },\n preventDefault () {},\n }\n\n return event as typeof event & PointerType & PointerEventType\n}\n\nexport interface MockCoords {\n page: Point\n client: Point\n timeStamp?: number\n pointerId?: any\n target?: any\n type?: string\n pointerType?: string\n buttons?: number\n}\n\nexport { pointerExtend }\n", "import type { Interactable } from '@interactjs/core/Interactable'\nimport type { Interaction, InteractionProxy } from '@interactjs/core/Interaction'\nimport type { ActionName } from '@interactjs/core/types'\n\nexport class BaseEvent {\n declare type: string\n declare target: EventTarget\n declare currentTarget: Node\n declare interactable: Interactable\n declare _interaction: Interaction\n declare timeStamp: number\n immediatePropagationStopped = false\n propagationStopped = false\n\n constructor (interaction: Interaction) {\n this._interaction = interaction\n }\n\n preventDefault () {}\n\n /**\n * Don't call any other listeners (even on the current target)\n */\n stopPropagation () {\n this.propagationStopped = true\n }\n\n /**\n * Don't call listeners on the remaining targets\n */\n stopImmediatePropagation () {\n this.immediatePropagationStopped = this.propagationStopped = true\n }\n}\n\n// defined outside of class definition to avoid assignment of undefined during\n// construction\nexport interface BaseEvent {\n interaction: InteractionProxy\n}\n\n// getters and setters defined here to support typescript 3.6 and below which\n// don't support getter and setters in .d.ts files\nObject.defineProperty(BaseEvent.prototype, 'interaction', {\n get (this: BaseEvent) {\n return this._interaction._proxy\n },\n set (this: BaseEvent) {},\n})\n", "type Filter = (element: T, index: number, array: T[]) => boolean\n\nexport const contains = (array: T[], target: T) => array.indexOf(target) !== -1\n\nexport const remove = (array: T[], target: T) => array.splice(array.indexOf(target), 1)\n\nexport const merge = (target: Array, source: U[]) => {\n for (const item of source) {\n target.push(item)\n }\n\n return target\n}\n\nexport const from = (source: ArrayLike) => merge([] as T[], source as T[])\n\nexport const findIndex = (array: T[], func: Filter) => {\n for (let i = 0; i < array.length; i++) {\n if (func(array[i], i, array)) {\n return i\n }\n }\n\n return -1\n}\n\nexport const find = (array: T[], func: Filter) => array[findIndex(array, func)]\n", "import { BaseEvent } from '@interactjs/core/BaseEvent'\nimport type { InteractEvent } from '@interactjs/core/InteractEvent'\nimport type { Interactable } from '@interactjs/core/Interactable'\nimport type { Element } from '@interactjs/core/types'\nimport * as arr from '@interactjs/utils/arr'\n\nimport type { DropState } from './plugin'\n\nexport class DropEvent extends BaseEvent<'drag'> {\n declare target: Element\n dropzone: Interactable\n dragEvent: InteractEvent<'drag'>\n relatedTarget: Element\n draggable: Interactable\n propagationStopped = false\n immediatePropagationStopped = false\n\n /**\n * Class of events fired on dropzones during drags with acceptable targets.\n */\n constructor (dropState: DropState, dragEvent: InteractEvent<'drag'>, type: string) {\n super(dragEvent._interaction)\n\n const { element, dropzone } = type === 'dragleave' ? dropState.prev : dropState.cur\n\n this.type = type\n this.target = element\n this.currentTarget = element\n this.dropzone = dropzone\n this.dragEvent = dragEvent\n this.relatedTarget = dragEvent.target\n this.draggable = dragEvent.interactable\n this.timeStamp = dragEvent.timeStamp\n }\n\n /**\n * If this is a `dropactivate` event, the dropzone element will be\n * deactivated.\n *\n * If this is a `dragmove` or `dragenter`, a `dragleave` will be fired on the\n * dropzone element and more.\n */\n reject () {\n const { dropState } = this._interaction\n\n if (\n this.type !== 'dropactivate' &&\n (!this.dropzone || dropState.cur.dropzone !== this.dropzone || dropState.cur.element !== this.target)\n ) {\n return\n }\n\n dropState.prev.dropzone = this.dropzone\n dropState.prev.element = this.target\n\n dropState.rejected = true\n dropState.events.enter = null\n\n this.stopImmediatePropagation()\n\n if (this.type === 'dropactivate') {\n const activeDrops = dropState.activeDrops\n const index = arr.findIndex(\n activeDrops,\n ({ dropzone, element }) => dropzone === this.dropzone && element === this.target,\n )\n\n dropState.activeDrops.splice(index, 1)\n\n const deactivateEvent = new DropEvent(dropState, this.dragEvent, 'dropdeactivate')\n\n deactivateEvent.dropzone = this.dropzone\n deactivateEvent.target = this.target\n\n this.dropzone.fire(deactivateEvent)\n } else {\n this.dropzone.fire(new DropEvent(dropState, this.dragEvent, 'dragleave'))\n }\n }\n\n preventDefault () {}\n\n stopPropagation () {\n this.propagationStopped = true\n }\n\n stopImmediatePropagation () {\n this.immediatePropagationStopped = this.propagationStopped = true\n }\n}\n", "import type { EventPhase, InteractEvent } from '@interactjs/core/InteractEvent'\nimport type { Interactable } from '@interactjs/core/Interactable'\nimport type { Interaction, DoPhaseArg } from '@interactjs/core/Interaction'\nimport type { PerActionDefaults } from '@interactjs/core/options'\nimport type { Scope, Plugin } from '@interactjs/core/scope'\nimport type { Element, PointerEventType, Rect, ListenersArg } from '@interactjs/core/types'\nimport * as domUtils from '@interactjs/utils/domUtils'\nimport extend from '@interactjs/utils/extend'\nimport getOriginXY from '@interactjs/utils/getOriginXY'\nimport is from '@interactjs/utils/is'\nimport normalizeListeners from '@interactjs/utils/normalizeListeners'\nimport * as pointerUtils from '@interactjs/utils/pointerUtils'\n\nimport type { DragEvent } from '../drag/plugin'\nimport drag from '../drag/plugin'\n\nimport { DropEvent } from './DropEvent'\n\nexport type DropFunctionChecker = (\n dragEvent: any, // related drag operation\n event: any, // touch or mouse EventEmitter\n dropped: boolean, // default checker result\n dropzone: Interactable, // dropzone interactable\n dropElement: Element, // drop zone element\n draggable: Interactable, // draggable's Interactable\n draggableElement: Element, // dragged element\n) => boolean\n\nexport interface DropzoneOptions extends PerActionDefaults {\n accept?:\n | string\n | Element\n | (({ dropzone, draggableElement }: { dropzone: Interactable, draggableElement: Element }) => boolean)\n // How the overlap is checked on the drop zone\n overlap?: 'pointer' | 'center' | number\n checker?: DropFunctionChecker\n\n ondropactivate?: ListenersArg\n ondropdeactivate?: ListenersArg\n ondragenter?: ListenersArg\n ondragleave?: ListenersArg\n ondropmove?: ListenersArg\n ondrop?: ListenersArg\n}\n\nexport interface DropzoneMethod {\n (this: Interactable, options: DropzoneOptions | boolean): Interactable\n (): DropzoneOptions\n}\n\ndeclare module '@interactjs/core/Interactable' {\n interface Interactable {\n dropzone: DropzoneMethod\n dropCheck: (\n dragEvent: InteractEvent,\n event: PointerEventType,\n draggable: Interactable,\n draggableElement: Element,\n dropElemen: Element,\n rect: any,\n ) => boolean\n }\n}\n\ndeclare module '@interactjs/core/Interaction' {\n interface Interaction {\n dropState?: DropState\n }\n}\n\ndeclare module '@interactjs/core/InteractEvent' {\n interface InteractEvent {\n prevDropzone?: Interactable\n dropzone?: Interactable\n dragEnter?: Element\n dragLeave?: Element\n }\n}\n\ndeclare module '@interactjs/core/options' {\n interface ActionDefaults {\n drop: DropzoneOptions\n }\n}\n\ndeclare module '@interactjs/core/scope' {\n interface Scope {\n dynamicDrop?: boolean\n }\n\n interface SignalArgs {\n 'actions/drop:start': DropSignalArg\n 'actions/drop:move': DropSignalArg\n 'actions/drop:end': DropSignalArg\n }\n}\n\ndeclare module '@interactjs/core/types' {\n interface ActionMap {\n drop?: typeof drop\n }\n}\n\ndeclare module '@interactjs/core/InteractStatic' {\n interface InteractStatic {\n dynamicDrop: (this: InteractStatic, newValue?: boolean) => boolean | this\n }\n}\n\ninterface DropSignalArg {\n interaction: Interaction<'drag'>\n dragEvent: DragEvent\n}\n\nexport interface ActiveDrop {\n dropzone: Interactable\n element: Element\n rect: Rect\n}\n\nexport interface DropState {\n cur: {\n // the dropzone a drag target might be dropped into\n dropzone: Interactable\n // the element at the time of checking\n element: Element\n }\n prev: {\n // the dropzone that was recently dragged away from\n dropzone: Interactable\n // the element at the time of checking\n element: Element\n }\n // wheather the potential drop was rejected from a listener\n rejected: boolean\n // the drop events related to the current drag event\n events: FiredDropEvents\n activeDrops: ActiveDrop[]\n}\n\nfunction install (scope: Scope) {\n const {\n actions,\n /** @lends module:interact */\n interactStatic: interact,\n /** @lends Interactable */\n Interactable,\n defaults,\n } = scope\n\n scope.usePlugin(drag)\n\n /**\n *\n * ```js\n * interact('.drop').dropzone({\n * accept: '.can-drop' || document.getElementById('single-drop'),\n * overlap: 'pointer' || 'center' || zeroToOne\n * }\n * ```\n *\n * Returns or sets whether draggables can be dropped onto this target to\n * trigger drop events\n *\n * Dropzones can receive the following events:\n * - `dropactivate` and `dropdeactivate` when an acceptable drag starts and ends\n * - `dragenter` and `dragleave` when a draggable enters and leaves the dropzone\n * - `dragmove` when a draggable that has entered the dropzone is moved\n * - `drop` when a draggable is dropped into this dropzone\n *\n * Use the `accept` option to allow only elements that match the given CSS\n * selector or element. The value can be:\n *\n * - **an Element** - only that element can be dropped into this dropzone.\n * - **a string**, - the element being dragged must match it as a CSS selector.\n * - **`null`** - accept options is cleared - it accepts any element.\n *\n * Use the `overlap` option to set how drops are checked for. The allowed\n * values are:\n *\n * - `'pointer'`, the pointer must be over the dropzone (default)\n * - `'center'`, the draggable element's center must be over the dropzone\n * - a number from 0-1 which is the `(intersection area) / (draggable area)`.\n * e.g. `0.5` for drop to happen when half of the area of the draggable is\n * over the dropzone\n *\n * Use the `checker` option to specify a function to check if a dragged element\n * is over this Interactable.\n *\n * @param {boolean | object | null} [options] The new options to be set.\n * @return {object | Interactable} The current setting or this Interactable\n */\n Interactable.prototype.dropzone = function (this: Interactable, options) {\n return dropzoneMethod(this, options)\n } as Interactable['dropzone']\n\n /**\n * ```js\n * interact(target)\n * .dropChecker(function(dragEvent, // related dragmove or dragend event\n * event, // TouchEvent/PointerEvent/MouseEvent\n * dropped, // bool result of the default checker\n * dropzone, // dropzone Interactable\n * dropElement, // dropzone elemnt\n * draggable, // draggable Interactable\n * draggableElement) {// draggable element\n *\n * return dropped && event.target.hasAttribute('allow-drop')\n * }\n * ```\n */\n Interactable.prototype.dropCheck = function (\n this: Interactable,\n dragEvent,\n event,\n draggable,\n draggableElement,\n dropElement,\n rect,\n ) {\n return dropCheckMethod(this, dragEvent, event, draggable, draggableElement, dropElement, rect)\n }\n\n /**\n * Returns or sets whether the dimensions of dropzone elements are calculated\n * on every dragmove or only on dragstart for the default dropChecker\n *\n * @param {boolean} [newValue] True to check on each move. False to check only\n * before start\n * @return {boolean | interact} The current setting or interact\n */\n interact.dynamicDrop = function (newValue?: boolean) {\n if (is.bool(newValue)) {\n // if (dragging && scope.dynamicDrop !== newValue && !newValue) {\n // calcRects(dropzones)\n // }\n\n scope.dynamicDrop = newValue\n\n return interact\n }\n return scope.dynamicDrop\n }\n\n extend(actions.phaselessTypes, {\n dragenter: true,\n dragleave: true,\n dropactivate: true,\n dropdeactivate: true,\n dropmove: true,\n drop: true,\n })\n actions.methodDict.drop = 'dropzone'\n\n scope.dynamicDrop = false\n\n defaults.actions.drop = drop.defaults\n}\n\nfunction collectDrops ({ interactables }: Scope, draggableElement: Element) {\n const drops: ActiveDrop[] = []\n\n // collect all dropzones and their elements which qualify for a drop\n for (const dropzone of interactables.list) {\n if (!dropzone.options.drop.enabled) {\n continue\n }\n\n const accept = dropzone.options.drop.accept\n\n // test the draggable draggableElement against the dropzone's accept setting\n if (\n (is.element(accept) && accept !== draggableElement) ||\n (is.string(accept) && !domUtils.matchesSelector(draggableElement, accept)) ||\n (is.func(accept) && !accept({ dropzone, draggableElement }))\n ) {\n continue\n }\n\n // query for new elements if necessary\n const dropElements = (\n is.string(dropzone.target)\n ? dropzone._context.querySelectorAll(dropzone.target)\n : is.array(dropzone.target)\n ? dropzone.target\n : [dropzone.target]\n ) as Element[]\n\n for (const dropzoneElement of dropElements) {\n if (dropzoneElement !== draggableElement) {\n drops.push({\n dropzone,\n element: dropzoneElement,\n rect: dropzone.getRect(dropzoneElement),\n })\n }\n }\n }\n\n return drops\n}\n\nfunction fireActivationEvents (activeDrops: ActiveDrop[], event: DropEvent) {\n // loop through all active dropzones and trigger event\n for (const { dropzone, element } of activeDrops.slice()) {\n event.dropzone = dropzone\n\n // set current element as event target\n event.target = element\n dropzone.fire(event)\n event.propagationStopped = event.immediatePropagationStopped = false\n }\n}\n\n// return a new array of possible drops. getActiveDrops should always be\n// called when a drag has just started or a drag event happens while\n// dynamicDrop is true\nfunction getActiveDrops (scope: Scope, dragElement: Element) {\n // get dropzones and their elements that could receive the draggable\n const activeDrops = collectDrops(scope, dragElement)\n\n for (const activeDrop of activeDrops) {\n activeDrop.rect = activeDrop.dropzone.getRect(activeDrop.element)\n }\n\n return activeDrops\n}\n\nfunction getDrop (\n { dropState, interactable: draggable, element: dragElement }: Partial,\n dragEvent,\n pointerEvent,\n) {\n const validDrops = []\n\n // collect all dropzones and their elements which qualify for a drop\n for (const { dropzone, element: dropzoneElement, rect } of dropState.activeDrops) {\n validDrops.push(\n dropzone.dropCheck(dragEvent, pointerEvent, draggable, dragElement, dropzoneElement, rect)\n ? dropzoneElement\n : null,\n )\n }\n\n // get the most appropriate dropzone based on DOM depth and order\n const dropIndex = domUtils.indexOfDeepestElement(validDrops)\n\n return dropState.activeDrops[dropIndex] || null\n}\n\nfunction getDropEvents (interaction: Interaction, _pointerEvent, dragEvent: DragEvent) {\n const { dropState } = interaction\n const dropEvents = {\n enter: null,\n leave: null,\n activate: null,\n deactivate: null,\n move: null,\n drop: null,\n }\n\n if (dragEvent.type === 'dragstart') {\n dropEvents.activate = new DropEvent(dropState, dragEvent, 'dropactivate')\n\n dropEvents.activate.target = null\n dropEvents.activate.dropzone = null\n }\n if (dragEvent.type === 'dragend') {\n dropEvents.deactivate = new DropEvent(dropState, dragEvent, 'dropdeactivate')\n\n dropEvents.deactivate.target = null\n dropEvents.deactivate.dropzone = null\n }\n\n if (dropState.rejected) {\n return dropEvents\n }\n\n if (dropState.cur.element !== dropState.prev.element) {\n // if there was a previous dropzone, create a dragleave event\n if (dropState.prev.dropzone) {\n dropEvents.leave = new DropEvent(dropState, dragEvent, 'dragleave')\n\n dragEvent.dragLeave = dropEvents.leave.target = dropState.prev.element\n dragEvent.prevDropzone = dropEvents.leave.dropzone = dropState.prev.dropzone\n }\n // if dropzone is not null, create a dragenter event\n if (dropState.cur.dropzone) {\n dropEvents.enter = new DropEvent(dropState, dragEvent, 'dragenter')\n\n dragEvent.dragEnter = dropState.cur.element\n dragEvent.dropzone = dropState.cur.dropzone\n }\n }\n\n if (dragEvent.type === 'dragend' && dropState.cur.dropzone) {\n dropEvents.drop = new DropEvent(dropState, dragEvent, 'drop')\n\n dragEvent.dropzone = dropState.cur.dropzone\n dragEvent.relatedTarget = dropState.cur.element\n }\n if (dragEvent.type === 'dragmove' && dropState.cur.dropzone) {\n dropEvents.move = new DropEvent(dropState, dragEvent, 'dropmove')\n\n dropEvents.move.dragmove = dragEvent\n dragEvent.dropzone = dropState.cur.dropzone\n }\n\n return dropEvents\n}\n\ntype FiredDropEvents = Partial<\nRecord<'leave' | 'enter' | 'move' | 'drop' | 'activate' | 'deactivate', DropEvent>\n>\n\nfunction fireDropEvents (interaction: Interaction, events: FiredDropEvents) {\n const { dropState } = interaction\n const { activeDrops, cur, prev } = dropState\n\n if (events.leave) {\n prev.dropzone.fire(events.leave)\n }\n if (events.enter) {\n cur.dropzone.fire(events.enter)\n }\n if (events.move) {\n cur.dropzone.fire(events.move)\n }\n if (events.drop) {\n cur.dropzone.fire(events.drop)\n }\n\n if (events.deactivate) {\n fireActivationEvents(activeDrops, events.deactivate)\n }\n\n dropState.prev.dropzone = cur.dropzone\n dropState.prev.element = cur.element\n}\n\nfunction onEventCreated ({ interaction, iEvent, event }: DoPhaseArg<'drag', EventPhase>, scope: Scope) {\n if (iEvent.type !== 'dragmove' && iEvent.type !== 'dragend') {\n return\n }\n\n const { dropState } = interaction\n\n if (scope.dynamicDrop) {\n dropState.activeDrops = getActiveDrops(scope, interaction.element)\n }\n\n const dragEvent = iEvent\n const dropResult = getDrop(interaction, dragEvent, event)\n\n // update rejected status\n dropState.rejected =\n dropState.rejected &&\n !!dropResult &&\n dropResult.dropzone === dropState.cur.dropzone &&\n dropResult.element === dropState.cur.element\n\n dropState.cur.dropzone = dropResult && dropResult.dropzone\n dropState.cur.element = dropResult && dropResult.element\n\n dropState.events = getDropEvents(interaction, event, dragEvent)\n}\n\nfunction dropzoneMethod(interactable: Interactable): DropzoneOptions\nfunction dropzoneMethod(interactable: Interactable, options: DropzoneOptions | boolean): Interactable\nfunction dropzoneMethod (interactable: Interactable, options?: DropzoneOptions | boolean) {\n if (is.object(options)) {\n interactable.options.drop.enabled = options.enabled !== false\n\n if (options.listeners) {\n const normalized = normalizeListeners(options.listeners)\n // rename 'drop' to '' as it will be prefixed with 'drop'\n const corrected = Object.keys(normalized).reduce((acc, type) => {\n const correctedType = /^(enter|leave)/.test(type)\n ? `drag${type}`\n : /^(activate|deactivate|move)/.test(type)\n ? `drop${type}`\n : type\n\n acc[correctedType] = normalized[type]\n\n return acc\n }, {})\n\n interactable.off(interactable.options.drop.listeners)\n interactable.on(corrected)\n interactable.options.drop.listeners = corrected\n }\n\n if (is.func(options.ondrop)) {\n interactable.on('drop', options.ondrop)\n }\n if (is.func(options.ondropactivate)) {\n interactable.on('dropactivate', options.ondropactivate)\n }\n if (is.func(options.ondropdeactivate)) {\n interactable.on('dropdeactivate', options.ondropdeactivate)\n }\n if (is.func(options.ondragenter)) {\n interactable.on('dragenter', options.ondragenter)\n }\n if (is.func(options.ondragleave)) {\n interactable.on('dragleave', options.ondragleave)\n }\n if (is.func(options.ondropmove)) {\n interactable.on('dropmove', options.ondropmove)\n }\n\n if (/^(pointer|center)$/.test(options.overlap as string)) {\n interactable.options.drop.overlap = options.overlap\n } else if (is.number(options.overlap)) {\n interactable.options.drop.overlap = Math.max(Math.min(1, options.overlap), 0)\n }\n if ('accept' in options) {\n interactable.options.drop.accept = options.accept\n }\n if ('checker' in options) {\n interactable.options.drop.checker = options.checker\n }\n\n return interactable\n }\n\n if (is.bool(options)) {\n interactable.options.drop.enabled = options\n\n return interactable\n }\n\n return interactable.options.drop\n}\n\nfunction dropCheckMethod (\n interactable: Interactable,\n dragEvent: InteractEvent,\n event: PointerEventType,\n draggable: Interactable,\n draggableElement: Element,\n dropElement: Element,\n rect: any,\n) {\n let dropped = false\n\n // if the dropzone has no rect (eg. display: none)\n // call the custom dropChecker or just return false\n if (!(rect = rect || interactable.getRect(dropElement))) {\n return interactable.options.drop.checker\n ? interactable.options.drop.checker(\n dragEvent,\n event,\n dropped,\n interactable,\n dropElement,\n draggable,\n draggableElement,\n )\n : false\n }\n\n const dropOverlap = interactable.options.drop.overlap\n\n if (dropOverlap === 'pointer') {\n const origin = getOriginXY(draggable, draggableElement, 'drag')\n const page = pointerUtils.getPageXY(dragEvent)\n\n page.x += origin.x\n page.y += origin.y\n\n const horizontal = page.x > rect.left && page.x < rect.right\n const vertical = page.y > rect.top && page.y < rect.bottom\n\n dropped = horizontal && vertical\n }\n\n const dragRect = draggable.getRect(draggableElement)\n\n if (dragRect && dropOverlap === 'center') {\n const cx = dragRect.left + dragRect.width / 2\n const cy = dragRect.top + dragRect.height / 2\n\n dropped = cx >= rect.left && cx <= rect.right && cy >= rect.top && cy <= rect.bottom\n }\n\n if (dragRect && is.number(dropOverlap)) {\n const overlapArea =\n Math.max(0, Math.min(rect.right, dragRect.right) - Math.max(rect.left, dragRect.left)) *\n Math.max(0, Math.min(rect.bottom, dragRect.bottom) - Math.max(rect.top, dragRect.top))\n\n const overlapRatio = overlapArea / (dragRect.width * dragRect.height)\n\n dropped = overlapRatio >= dropOverlap\n }\n\n if (interactable.options.drop.checker) {\n dropped = interactable.options.drop.checker(\n dragEvent,\n event,\n dropped,\n interactable,\n dropElement,\n draggable,\n draggableElement,\n )\n }\n\n return dropped\n}\n\nconst drop: Plugin = {\n id: 'actions/drop',\n install,\n listeners: {\n 'interactions:before-action-start': ({ interaction }) => {\n if (interaction.prepared.name !== 'drag') {\n return\n }\n\n interaction.dropState = {\n cur: {\n dropzone: null,\n element: null,\n },\n prev: {\n dropzone: null,\n element: null,\n },\n rejected: null,\n events: null,\n activeDrops: [],\n }\n },\n\n 'interactions:after-action-start': (\n { interaction, event, iEvent: dragEvent }: DoPhaseArg<'drag', EventPhase>,\n scope,\n ) => {\n if (interaction.prepared.name !== 'drag') {\n return\n }\n\n const { dropState } = interaction\n\n // reset active dropzones\n dropState.activeDrops = null\n dropState.events = null\n dropState.activeDrops = getActiveDrops(scope, interaction.element)\n dropState.events = getDropEvents(interaction, event, dragEvent)\n\n if (dropState.events.activate) {\n fireActivationEvents(dropState.activeDrops, dropState.events.activate)\n scope.fire('actions/drop:start', { interaction, dragEvent })\n }\n },\n\n 'interactions:action-move': onEventCreated,\n\n 'interactions:after-action-move': (\n { interaction, iEvent: dragEvent }: DoPhaseArg<'drag', EventPhase>,\n scope,\n ) => {\n if (interaction.prepared.name !== 'drag') {\n return\n }\n\n fireDropEvents(interaction, interaction.dropState.events)\n\n scope.fire('actions/drop:move', { interaction, dragEvent })\n interaction.dropState.events = {}\n },\n\n 'interactions:action-end': (arg: DoPhaseArg<'drag', EventPhase>, scope) => {\n if (arg.interaction.prepared.name !== 'drag') {\n return\n }\n\n const { interaction, iEvent: dragEvent } = arg\n\n onEventCreated(arg, scope)\n fireDropEvents(interaction, interaction.dropState.events)\n scope.fire('actions/drop:end', { interaction, dragEvent })\n },\n\n 'interactions:stop': ({ interaction }) => {\n if (interaction.prepared.name !== 'drag') {\n return\n }\n\n const { dropState } = interaction\n\n if (dropState) {\n dropState.activeDrops = null\n dropState.events = null\n dropState.cur.dropzone = null\n dropState.cur.element = null\n dropState.prev.dropzone = null\n dropState.prev.element = null\n dropState.rejected = false\n }\n },\n },\n getActiveDrops,\n getDrop,\n getDropEvents,\n fireDropEvents,\n defaults: {\n enabled: false,\n accept: null,\n overlap: 'pointer',\n } as DropzoneOptions,\n}\n\nexport default drop\n", "import type { InteractEvent, EventPhase } from '@interactjs/core/InteractEvent'\nimport type { Interaction, DoPhaseArg } from '@interactjs/core/Interaction'\nimport type { PerActionDefaults } from '@interactjs/core/options'\nimport type { Scope, Plugin } from '@interactjs/core/scope'\nimport type { ActionMethod, Rect, PointerType, ListenersArg } from '@interactjs/core/types'\nimport is from '@interactjs/utils/is'\nimport * as pointerUtils from '@interactjs/utils/pointerUtils'\n\nexport type GesturableMethod = ActionMethod\n\ndeclare module '@interactjs/core/Interaction' {\n interface Interaction {\n gesture?: {\n angle: number // angle from first to second touch\n distance: number\n scale: number // gesture.distance / gesture.startDistance\n startAngle: number // angle of line joining two touches\n startDistance: number // distance between two touches of touchStart\n }\n }\n}\n\ndeclare module '@interactjs/core/Interactable' {\n interface Interactable {\n gesturable: GesturableMethod\n }\n}\n\ndeclare module '@interactjs/core/options' {\n interface ActionDefaults {\n gesture: GesturableOptions\n }\n}\n\ndeclare module '@interactjs/core/types' {\n interface ActionMap {\n gesture?: typeof gesture\n }\n}\n\nexport interface GesturableOptions extends PerActionDefaults {\n onstart?: ListenersArg\n onmove?: ListenersArg\n onend?: ListenersArg\n}\n\nexport interface GestureEvent extends InteractEvent<'gesture'> {\n distance: number\n angle: number\n da: number // angle change\n scale: number // ratio of distance start to current event\n ds: number // scale change\n box: Rect // enclosing box of all points\n touches: PointerType[]\n}\n\nexport interface GestureSignalArg extends DoPhaseArg<'gesture', EventPhase> {\n iEvent: GestureEvent\n interaction: Interaction<'gesture'>\n}\n\nfunction install (scope: Scope) {\n const { actions, Interactable, defaults } = scope\n\n /**\n * ```js\n * interact(element).gesturable({\n * onstart: function (event) {},\n * onmove : function (event) {},\n * onend : function (event) {},\n *\n * // limit multiple gestures.\n * // See the explanation in {@link Interactable.draggable} example\n * max: Infinity,\n * maxPerElement: 1,\n * })\n *\n * var isGestureable = interact(element).gesturable()\n * ```\n *\n * Gets or sets whether multitouch gestures can be performed on the target\n *\n * @param {boolean | object} [options] true/false or An object with event\n * listeners to be fired on gesture events (makes the Interactable gesturable)\n * @return {boolean | Interactable} A boolean indicating if this can be the\n * target of gesture events, or this Interactable\n */\n Interactable.prototype.gesturable = function (\n this: InstanceType,\n options: GesturableOptions | boolean,\n ) {\n if (is.object(options)) {\n this.options.gesture.enabled = options.enabled !== false\n this.setPerAction('gesture', options)\n this.setOnEvents('gesture', options)\n\n return this\n }\n\n if (is.bool(options)) {\n this.options.gesture.enabled = options\n\n return this\n }\n\n return this.options.gesture as GesturableOptions\n } as GesturableMethod\n\n actions.map.gesture = gesture\n actions.methodDict.gesture = 'gesturable'\n\n defaults.actions.gesture = gesture.defaults\n}\n\nfunction updateGestureProps ({ interaction, iEvent, phase }: GestureSignalArg) {\n if (interaction.prepared.name !== 'gesture') return\n\n const pointers = interaction.pointers.map((p) => p.pointer)\n const starting = phase === 'start'\n const ending = phase === 'end'\n const deltaSource = interaction.interactable.options.deltaSource\n\n iEvent.touches = [pointers[0], pointers[1]]\n\n if (starting) {\n iEvent.distance = pointerUtils.touchDistance(pointers, deltaSource)\n iEvent.box = pointerUtils.touchBBox(pointers)\n iEvent.scale = 1\n iEvent.ds = 0\n iEvent.angle = pointerUtils.touchAngle(pointers, deltaSource)\n iEvent.da = 0\n\n interaction.gesture.startDistance = iEvent.distance\n interaction.gesture.startAngle = iEvent.angle\n } else if (ending) {\n const prevEvent = interaction.prevEvent as GestureEvent\n\n iEvent.distance = prevEvent.distance\n iEvent.box = prevEvent.box\n iEvent.scale = prevEvent.scale\n iEvent.ds = 0\n iEvent.angle = prevEvent.angle\n iEvent.da = 0\n } else {\n iEvent.distance = pointerUtils.touchDistance(pointers, deltaSource)\n iEvent.box = pointerUtils.touchBBox(pointers)\n iEvent.scale = iEvent.distance / interaction.gesture.startDistance\n iEvent.angle = pointerUtils.touchAngle(pointers, deltaSource)\n\n iEvent.ds = iEvent.scale - interaction.gesture.scale\n iEvent.da = iEvent.angle - interaction.gesture.angle\n }\n\n interaction.gesture.distance = iEvent.distance\n interaction.gesture.angle = iEvent.angle\n\n if (is.number(iEvent.scale) && iEvent.scale !== Infinity && !isNaN(iEvent.scale)) {\n interaction.gesture.scale = iEvent.scale\n }\n}\n\nconst gesture: Plugin = {\n id: 'actions/gesture',\n before: ['actions/drag', 'actions/resize'],\n install,\n listeners: {\n 'interactions:action-start': updateGestureProps,\n 'interactions:action-move': updateGestureProps,\n 'interactions:action-end': updateGestureProps,\n\n 'interactions:new': ({ interaction }) => {\n interaction.gesture = {\n angle: 0,\n distance: 0,\n scale: 1,\n startAngle: 0,\n startDistance: 0,\n }\n },\n\n 'auto-start:check': (arg) => {\n if (arg.interaction.pointers.length < 2) {\n return undefined\n }\n\n const gestureOptions = arg.interactable.options.gesture\n\n if (!(gestureOptions && gestureOptions.enabled)) {\n return undefined\n }\n\n arg.action = { name: 'gesture' }\n\n return false\n },\n },\n\n defaults: {},\n\n getCursor () {\n return ''\n },\n}\n\nexport default gesture\n", "import type { EventPhase, InteractEvent } from '@interactjs/core/InteractEvent'\nimport type { Interactable } from '@interactjs/core/Interactable'\nimport type { Interaction } from '@interactjs/core/Interaction'\nimport type { PerActionDefaults } from '@interactjs/core/options'\nimport type { Scope, Plugin } from '@interactjs/core/scope'\nimport type {\n ActionName,\n ActionProps,\n ActionMethod,\n EdgeOptions,\n FullRect,\n ListenersArg,\n OrBoolean,\n Point,\n Rect,\n} from '@interactjs/core/types'\nimport * as dom from '@interactjs/utils/domUtils'\nimport extend from '@interactjs/utils/extend'\nimport is from '@interactjs/utils/is'\n\nexport type EdgeName = 'top' | 'left' | 'bottom' | 'right'\n\nexport type ResizableMethod = ActionMethod\n\ndeclare module '@interactjs/core/Interactable' {\n interface Interactable {\n resizable: ResizableMethod\n }\n}\n\ndeclare module '@interactjs/core/Interaction' {\n interface Interaction {\n resizeAxes: 'x' | 'y' | 'xy'\n resizeStartAspectRatio: number\n }\n}\n\ndeclare module '@interactjs/core/options' {\n interface ActionDefaults {\n resize: ResizableOptions\n }\n}\n\ndeclare module '@interactjs/core/types' {\n interface ActionMap {\n resize?: typeof resize\n }\n}\n\nexport interface ResizableOptions extends PerActionDefaults {\n square?: boolean\n preserveAspectRatio?: boolean\n edges?: EdgeOptions | null\n axis?: 'x' | 'y' | 'xy' // deprecated\n invert?: 'none' | 'negate' | 'reposition'\n margin?: number\n squareResize?: boolean\n oninertiastart?: ListenersArg\n onstart?: ListenersArg\n onmove?: ListenersArg\n onend?: ListenersArg\n}\n\nexport interface ResizeEvent

extends InteractEvent<'resize', P> {\n deltaRect?: FullRect\n edges?: ActionProps['edges']\n}\n\nfunction install (scope: Scope) {\n const {\n actions,\n browser,\n /** @lends Interactable */\n Interactable, // tslint:disable-line no-shadowed-variable\n defaults,\n } = scope\n\n // Less Precision with touch input\n\n resize.cursors = initCursors(browser)\n resize.defaultMargin = browser.supportsTouch || browser.supportsPointerEvent ? 20 : 10\n\n /**\n * ```js\n * interact(element).resizable({\n * onstart: function (event) {},\n * onmove : function (event) {},\n * onend : function (event) {},\n *\n * edges: {\n * top : true, // Use pointer coords to check for resize.\n * left : false, // Disable resizing from left edge.\n * bottom: '.resize-s',// Resize if pointer target matches selector\n * right : handleEl // Resize if pointer target is the given Element\n * },\n *\n * // Width and height can be adjusted independently. When `true`, width and\n * // height are adjusted at a 1:1 ratio.\n * square: false,\n *\n * // Width and height can be adjusted independently. When `true`, width and\n * // height maintain the aspect ratio they had when resizing started.\n * preserveAspectRatio: false,\n *\n * // a value of 'none' will limit the resize rect to a minimum of 0x0\n * // 'negate' will allow the rect to have negative width/height\n * // 'reposition' will keep the width/height positive by swapping\n * // the top and bottom edges and/or swapping the left and right edges\n * invert: 'none' || 'negate' || 'reposition'\n *\n * // limit multiple resizes.\n * // See the explanation in the {@link Interactable.draggable} example\n * max: Infinity,\n * maxPerElement: 1,\n * })\n *\n * var isResizeable = interact(element).resizable()\n * ```\n *\n * Gets or sets whether resize actions can be performed on the target\n *\n * @param {boolean | object} [options] true/false or An object with event\n * listeners to be fired on resize events (object makes the Interactable\n * resizable)\n * @return {boolean | Interactable} A boolean indicating if this can be the\n * target of resize elements, or this Interactable\n */\n Interactable.prototype.resizable = function (this: Interactable, options: ResizableOptions | boolean) {\n return resizable(this, options, scope)\n } as ResizableMethod\n\n actions.map.resize = resize\n actions.methodDict.resize = 'resizable'\n\n defaults.actions.resize = resize.defaults\n}\n\nfunction resizeChecker (arg) {\n const { interaction, interactable, element, rect, buttons } = arg\n\n if (!rect) {\n return undefined\n }\n\n const page = extend({}, interaction.coords.cur.page)\n const resizeOptions = interactable.options.resize\n\n if (\n !(resizeOptions && resizeOptions.enabled) ||\n // check mouseButton setting if the pointer is down\n (interaction.pointerIsDown &&\n /mouse|pointer/.test(interaction.pointerType) &&\n (buttons & resizeOptions.mouseButtons) === 0)\n ) {\n return undefined\n }\n\n // if using resize.edges\n if (is.object(resizeOptions.edges)) {\n const resizeEdges = {\n left: false,\n right: false,\n top: false,\n bottom: false,\n }\n\n for (const edge in resizeEdges) {\n resizeEdges[edge] = checkResizeEdge(\n edge,\n resizeOptions.edges[edge],\n page,\n interaction._latestPointer.eventTarget,\n element,\n rect,\n resizeOptions.margin || resize.defaultMargin,\n )\n }\n\n resizeEdges.left = resizeEdges.left && !resizeEdges.right\n resizeEdges.top = resizeEdges.top && !resizeEdges.bottom\n\n if (resizeEdges.left || resizeEdges.right || resizeEdges.top || resizeEdges.bottom) {\n arg.action = {\n name: 'resize',\n edges: resizeEdges,\n }\n }\n } else {\n const right = resizeOptions.axis !== 'y' && page.x > rect.right - resize.defaultMargin\n const bottom = resizeOptions.axis !== 'x' && page.y > rect.bottom - resize.defaultMargin\n\n if (right || bottom) {\n arg.action = {\n name: 'resize',\n axes: (right ? 'x' : '') + (bottom ? 'y' : ''),\n }\n }\n }\n\n return arg.action ? false : undefined\n}\n\nfunction resizable (interactable: Interactable, options: OrBoolean | boolean, scope: Scope) {\n if (is.object(options)) {\n interactable.options.resize.enabled = options.enabled !== false\n interactable.setPerAction('resize', options)\n interactable.setOnEvents('resize', options)\n\n if (is.string(options.axis) && /^x$|^y$|^xy$/.test(options.axis)) {\n interactable.options.resize.axis = options.axis\n } else if (options.axis === null) {\n interactable.options.resize.axis = scope.defaults.actions.resize.axis\n }\n\n if (is.bool(options.preserveAspectRatio)) {\n interactable.options.resize.preserveAspectRatio = options.preserveAspectRatio\n } else if (is.bool(options.square)) {\n interactable.options.resize.square = options.square\n }\n\n return interactable\n }\n if (is.bool(options)) {\n interactable.options.resize.enabled = options\n\n return interactable\n }\n return interactable.options.resize\n}\n\nfunction checkResizeEdge (\n name: string,\n value: any,\n page: Point,\n element: Node,\n interactableElement: Element,\n rect: Rect,\n margin: number,\n) {\n // false, '', undefined, null\n if (!value) {\n return false\n }\n\n // true value, use pointer coords and element rect\n if (value === true) {\n // if dimensions are negative, \"switch\" edges\n const width = is.number(rect.width) ? rect.width : rect.right - rect.left\n const height = is.number(rect.height) ? rect.height : rect.bottom - rect.top\n\n // don't use margin greater than half the relevent dimension\n margin = Math.min(margin, Math.abs((name === 'left' || name === 'right' ? width : height) / 2))\n\n if (width < 0) {\n if (name === 'left') {\n name = 'right'\n } else if (name === 'right') {\n name = 'left'\n }\n }\n if (height < 0) {\n if (name === 'top') {\n name = 'bottom'\n } else if (name === 'bottom') {\n name = 'top'\n }\n }\n\n if (name === 'left') {\n const edge = width >= 0 ? rect.left : rect.right\n return page.x < edge + margin\n }\n if (name === 'top') {\n const edge = height >= 0 ? rect.top : rect.bottom\n return page.y < edge + margin\n }\n\n if (name === 'right') {\n return page.x > (width >= 0 ? rect.right : rect.left) - margin\n }\n if (name === 'bottom') {\n return page.y > (height >= 0 ? rect.bottom : rect.top) - margin\n }\n }\n\n // the remaining checks require an element\n if (!is.element(element)) {\n return false\n }\n\n return is.element(value)\n ? // the value is an element to use as a resize handle\n value === element\n : // otherwise check if element matches value as selector\n dom.matchesUpTo(element, value, interactableElement)\n}\n\n/* eslint-disable multiline-ternary */\n// eslint-disable-next-line @typescript-eslint/consistent-type-imports\nfunction initCursors (browser: typeof import('@interactjs/utils/browser').default) {\n return browser.isIe9\n ? {\n x: 'e-resize',\n y: 's-resize',\n xy: 'se-resize',\n\n top: 'n-resize',\n left: 'w-resize',\n bottom: 's-resize',\n right: 'e-resize',\n topleft: 'se-resize',\n bottomright: 'se-resize',\n topright: 'ne-resize',\n bottomleft: 'ne-resize',\n }\n : {\n x: 'ew-resize',\n y: 'ns-resize',\n xy: 'nwse-resize',\n\n top: 'ns-resize',\n left: 'ew-resize',\n bottom: 'ns-resize',\n right: 'ew-resize',\n topleft: 'nwse-resize',\n bottomright: 'nwse-resize',\n topright: 'nesw-resize',\n bottomleft: 'nesw-resize',\n }\n}\n/* eslint-enable multiline-ternary */\n\nfunction start ({ iEvent, interaction }: { iEvent: InteractEvent, interaction: Interaction }) {\n if (interaction.prepared.name !== 'resize' || !interaction.prepared.edges) {\n return\n }\n\n const resizeEvent = iEvent as ResizeEvent\n const rect = interaction.rect\n\n interaction._rects = {\n start: extend({}, rect),\n corrected: extend({}, rect),\n previous: extend({}, rect),\n delta: {\n left: 0,\n right: 0,\n width: 0,\n top: 0,\n bottom: 0,\n height: 0,\n },\n }\n\n resizeEvent.edges = interaction.prepared.edges\n resizeEvent.rect = interaction._rects.corrected\n resizeEvent.deltaRect = interaction._rects.delta\n}\n\nfunction move ({ iEvent, interaction }: { iEvent: InteractEvent, interaction: Interaction }) {\n if (interaction.prepared.name !== 'resize' || !interaction.prepared.edges) return\n\n const resizeEvent = iEvent as ResizeEvent\n const resizeOptions = interaction.interactable.options.resize\n const invert = resizeOptions.invert\n const invertible = invert === 'reposition' || invert === 'negate'\n\n const current = interaction.rect\n const { start: startRect, corrected, delta: deltaRect, previous } = interaction._rects\n\n extend(previous, corrected)\n\n if (invertible) {\n // if invertible, copy the current rect\n extend(corrected, current)\n\n if (invert === 'reposition') {\n // swap edge values if necessary to keep width/height positive\n if (corrected.top > corrected.bottom) {\n const swap = corrected.top\n\n corrected.top = corrected.bottom\n corrected.bottom = swap\n }\n if (corrected.left > corrected.right) {\n const swap = corrected.left\n\n corrected.left = corrected.right\n corrected.right = swap\n }\n }\n } else {\n // if not invertible, restrict to minimum of 0x0 rect\n corrected.top = Math.min(current.top, startRect.bottom)\n corrected.bottom = Math.max(current.bottom, startRect.top)\n corrected.left = Math.min(current.left, startRect.right)\n corrected.right = Math.max(current.right, startRect.left)\n }\n\n corrected.width = corrected.right - corrected.left\n corrected.height = corrected.bottom - corrected.top\n\n for (const edge in corrected) {\n deltaRect[edge] = corrected[edge] - previous[edge]\n }\n\n resizeEvent.edges = interaction.prepared.edges\n resizeEvent.rect = corrected\n resizeEvent.deltaRect = deltaRect\n}\n\nfunction end ({ iEvent, interaction }: { iEvent: InteractEvent, interaction: Interaction }) {\n if (interaction.prepared.name !== 'resize' || !interaction.prepared.edges) return\n\n const resizeEvent = iEvent as ResizeEvent\n\n resizeEvent.edges = interaction.prepared.edges\n resizeEvent.rect = interaction._rects.corrected\n resizeEvent.deltaRect = interaction._rects.delta\n}\n\nfunction updateEventAxes ({\n iEvent,\n interaction,\n}: {\n iEvent: InteractEvent\n interaction: Interaction\n}) {\n if (interaction.prepared.name !== 'resize' || !interaction.resizeAxes) return\n\n const options = interaction.interactable.options\n const resizeEvent = iEvent as ResizeEvent\n\n if (options.resize.square) {\n if (interaction.resizeAxes === 'y') {\n resizeEvent.delta.x = resizeEvent.delta.y\n } else {\n resizeEvent.delta.y = resizeEvent.delta.x\n }\n resizeEvent.axes = 'xy'\n } else {\n resizeEvent.axes = interaction.resizeAxes\n\n if (interaction.resizeAxes === 'x') {\n resizeEvent.delta.y = 0\n } else if (interaction.resizeAxes === 'y') {\n resizeEvent.delta.x = 0\n }\n }\n}\n\nconst resize: Plugin = {\n id: 'actions/resize',\n before: ['actions/drag'],\n install,\n listeners: {\n 'interactions:new': ({ interaction }) => {\n interaction.resizeAxes = 'xy'\n },\n\n 'interactions:action-start': (arg) => {\n start(arg)\n updateEventAxes(arg)\n },\n 'interactions:action-move': (arg) => {\n move(arg)\n updateEventAxes(arg)\n },\n 'interactions:action-end': end,\n 'auto-start:check': resizeChecker,\n },\n\n defaults: {\n square: false,\n preserveAspectRatio: false,\n axis: 'xy',\n\n // use default margin\n margin: NaN,\n\n // object with props left, right, top, bottom which are\n // true/false values to resize when the pointer is over that edge,\n // CSS selectors to match the handles for each direction\n // or the Elements for each handle\n edges: null,\n\n // a value of 'none' will limit the resize rect to a minimum of 0x0\n // 'negate' will alow the rect to have negative width/height\n // 'reposition' will keep the width/height positive by swapping\n // the top and bottom edges and/or swapping the left and right edges\n invert: 'none',\n } as ResizableOptions,\n\n cursors: null as ReturnType,\n\n getCursor ({ edges, axis, name }: ActionProps) {\n const cursors = resize.cursors\n let result: string = null\n\n if (axis) {\n result = cursors[name + axis]\n } else if (edges) {\n let cursorKey = ''\n\n for (const edge of ['top', 'bottom', 'left', 'right']) {\n if (edges[edge]) {\n cursorKey += edge\n }\n }\n\n result = cursors[cursorKey]\n }\n\n return result\n },\n\n defaultMargin: null as number,\n}\n\nexport default resize\n", "import type { Scope } from '@interactjs/core/scope'\n\nimport drag from './drag/plugin'\nimport drop from './drop/plugin'\nimport gesture from './gesture/plugin'\nimport resize from './resize/plugin'\n\nexport default {\n id: 'actions',\n install (scope: Scope) {\n scope.usePlugin(gesture)\n scope.usePlugin(resize)\n scope.usePlugin(drag)\n scope.usePlugin(drop)\n },\n}\n", "let lastTime = 0\nlet request: typeof requestAnimationFrame\nlet cancel: typeof cancelAnimationFrame\n\nfunction init (global: Window | typeof globalThis) {\n request = global.requestAnimationFrame\n cancel = global.cancelAnimationFrame\n\n if (!request) {\n const vendors = ['ms', 'moz', 'webkit', 'o']\n\n for (const vendor of vendors) {\n request = global[`${vendor}RequestAnimationFrame` as 'requestAnimationFrame']\n cancel =\n global[`${vendor}CancelAnimationFrame` as 'cancelAnimationFrame'] ||\n global[`${vendor}CancelRequestAnimationFrame` as 'cancelAnimationFrame']\n }\n }\n\n request = request && request.bind(global)\n cancel = cancel && cancel.bind(global)\n\n if (!request) {\n request = (callback) => {\n const currTime = Date.now()\n const timeToCall = Math.max(0, 16 - (currTime - lastTime))\n const token = global.setTimeout(() => {\n // eslint-disable-next-line n/no-callback-literal\n callback(currTime + timeToCall)\n }, timeToCall)\n\n lastTime = currTime + timeToCall\n return token as any\n }\n\n cancel = (token) => clearTimeout(token)\n }\n}\n\nexport default {\n request: (callback: FrameRequestCallback) => request(callback),\n cancel: (token: number) => cancel(token),\n init,\n}\n", "import type { Interactable } from '@interactjs/core/Interactable'\nimport type Interaction from '@interactjs/core/Interaction'\nimport type { Scope, Plugin } from '@interactjs/core/scope'\nimport type { ActionName, PointerType } from '@interactjs/core/types'\nimport * as domUtils from '@interactjs/utils/domUtils'\nimport is from '@interactjs/utils/is'\nimport raf from '@interactjs/utils/raf'\nimport { getStringOptionResult } from '@interactjs/utils/rect'\nimport { getWindow } from '@interactjs/utils/window'\n\ndeclare module '@interactjs/core/scope' {\n interface Scope {\n autoScroll: typeof autoScroll\n }\n}\n\ndeclare module '@interactjs/core/Interaction' {\n interface Interaction {\n autoScroll?: typeof autoScroll\n }\n}\n\ndeclare module '@interactjs/core/options' {\n interface PerActionDefaults {\n autoScroll?: AutoScrollOptions\n }\n}\n\nexport interface AutoScrollOptions {\n container?: Window | HTMLElement | string\n margin?: number\n distance?: number\n interval?: number\n speed?: number\n enabled?: boolean\n}\n\nfunction install (scope: Scope) {\n const { defaults, actions } = scope\n\n scope.autoScroll = autoScroll\n autoScroll.now = () => scope.now()\n\n actions.phaselessTypes.autoscroll = true\n defaults.perAction.autoScroll = autoScroll.defaults\n}\n\nconst autoScroll = {\n defaults: {\n enabled: false,\n margin: 60,\n\n // the item that is scrolled (Window or HTMLElement)\n container: null as AutoScrollOptions['container'],\n\n // the scroll speed in pixels per second\n speed: 300,\n } as AutoScrollOptions,\n\n now: Date.now,\n\n interaction: null as Interaction | null,\n i: 0, // the handle returned by window.setInterval\n\n // Direction each pulse is to scroll in\n x: 0,\n y: 0,\n\n isScrolling: false,\n prevTime: 0,\n margin: 0,\n speed: 0,\n\n start (interaction: Interaction) {\n autoScroll.isScrolling = true\n raf.cancel(autoScroll.i)\n\n interaction.autoScroll = autoScroll\n autoScroll.interaction = interaction\n autoScroll.prevTime = autoScroll.now()\n autoScroll.i = raf.request(autoScroll.scroll)\n },\n\n stop () {\n autoScroll.isScrolling = false\n if (autoScroll.interaction) {\n autoScroll.interaction.autoScroll = null\n }\n raf.cancel(autoScroll.i)\n },\n\n // scroll the window by the values in scroll.x/y\n scroll () {\n const { interaction } = autoScroll\n const { interactable, element } = interaction\n const actionName = interaction.prepared.name\n const options = interactable.options[actionName].autoScroll\n const container = getContainer(options.container, interactable, element)\n const now = autoScroll.now()\n // change in time in seconds\n const dt = (now - autoScroll.prevTime) / 1000\n // displacement\n const s = options.speed * dt\n\n if (s >= 1) {\n const scrollBy = {\n x: autoScroll.x * s,\n y: autoScroll.y * s,\n }\n\n if (scrollBy.x || scrollBy.y) {\n const prevScroll = getScroll(container)\n\n if (is.window(container)) {\n container.scrollBy(scrollBy.x, scrollBy.y)\n } else if (container) {\n container.scrollLeft += scrollBy.x\n container.scrollTop += scrollBy.y\n }\n\n const curScroll = getScroll(container)\n const delta = {\n x: curScroll.x - prevScroll.x,\n y: curScroll.y - prevScroll.y,\n }\n\n if (delta.x || delta.y) {\n interactable.fire({\n type: 'autoscroll',\n target: element,\n interactable,\n delta,\n interaction,\n container,\n })\n }\n }\n\n autoScroll.prevTime = now\n }\n\n if (autoScroll.isScrolling) {\n raf.cancel(autoScroll.i)\n autoScroll.i = raf.request(autoScroll.scroll)\n }\n },\n check (interactable: Interactable, actionName: ActionName) {\n const options = interactable.options\n\n return options[actionName].autoScroll?.enabled\n },\n onInteractionMove ({\n interaction,\n pointer,\n }: {\n interaction: Interaction\n pointer: PointerType\n }) {\n if (\n !(interaction.interacting() && autoScroll.check(interaction.interactable, interaction.prepared.name))\n ) {\n return\n }\n\n if (interaction.simulation) {\n autoScroll.x = autoScroll.y = 0\n return\n }\n\n let top: boolean\n let right: boolean\n let bottom: boolean\n let left: boolean\n\n const { interactable, element } = interaction\n const actionName = interaction.prepared.name\n const options = interactable.options[actionName].autoScroll\n const container = getContainer(options.container, interactable, element)\n\n if (is.window(container)) {\n left = pointer.clientX < autoScroll.margin\n top = pointer.clientY < autoScroll.margin\n right = pointer.clientX > container.innerWidth - autoScroll.margin\n bottom = pointer.clientY > container.innerHeight - autoScroll.margin\n } else {\n const rect = domUtils.getElementClientRect(container)\n\n left = pointer.clientX < rect.left + autoScroll.margin\n top = pointer.clientY < rect.top + autoScroll.margin\n right = pointer.clientX > rect.right - autoScroll.margin\n bottom = pointer.clientY > rect.bottom - autoScroll.margin\n }\n\n autoScroll.x = right ? 1 : left ? -1 : 0\n autoScroll.y = bottom ? 1 : top ? -1 : 0\n\n if (!autoScroll.isScrolling) {\n // set the autoScroll properties to those of the target\n autoScroll.margin = options.margin\n autoScroll.speed = options.speed\n\n autoScroll.start(interaction)\n }\n },\n}\n\nexport function getContainer (value: any, interactable: Interactable, element: Element) {\n return (\n (is.string(value) ? getStringOptionResult(value, interactable, element) : value) || getWindow(element)\n )\n}\n\nexport function getScroll (container: any) {\n if (is.window(container)) {\n container = window.document.body\n }\n\n return { x: container.scrollLeft, y: container.scrollTop }\n}\n\nexport function getScrollSize (container: any) {\n if (is.window(container)) {\n container = window.document.body\n }\n\n return { x: container.scrollWidth, y: container.scrollHeight }\n}\n\nexport function getScrollSizeDelta (\n {\n interaction,\n element,\n }: {\n interaction: Partial>\n element: Element\n },\n func: any,\n) {\n const scrollOptions = interaction && interaction.interactable.options[interaction.prepared.name].autoScroll\n\n if (!scrollOptions || !scrollOptions.enabled) {\n func()\n return { x: 0, y: 0 }\n }\n\n const scrollContainer = getContainer(scrollOptions.container, interaction.interactable, element)\n\n const prevSize = getScroll(scrollContainer)\n func()\n const curSize = getScroll(scrollContainer)\n\n return {\n x: curSize.x - prevSize.x,\n y: curSize.y - prevSize.y,\n }\n}\n\nconst autoScrollPlugin: Plugin = {\n id: 'auto-scroll',\n install,\n listeners: {\n 'interactions:new': ({ interaction }) => {\n interaction.autoScroll = null\n },\n\n 'interactions:destroy': ({ interaction }) => {\n interaction.autoScroll = null\n autoScroll.stop()\n if (autoScroll.interaction) {\n autoScroll.interaction = null\n }\n },\n\n 'interactions:stop': autoScroll.stop,\n\n 'interactions:action-move': (arg: any) => autoScroll.onInteractionMove(arg),\n },\n}\n\nexport default autoScrollPlugin\n", "import type { ActionName, ActionProps } from '@interactjs/core/types'\n\nimport { window } from './window'\n\nexport function warnOnce (this: T, method: (...args: any[]) => any, message: string) {\n let warned = false\n\n return function (this: T) {\n if (!warned) {\n ;(window as any).console.warn(message)\n warned = true\n }\n\n return method.apply(this, arguments)\n }\n}\n\nexport function copyAction (dest: ActionProps, src: ActionProps) {\n dest.name = src.name\n dest.axis = src.axis\n dest.edges = src.edges\n\n return dest\n}\n\nexport const sign = (n: number) => (n >= 0 ? 1 : -1)\n", "import type { Interactable } from '@interactjs/core/Interactable'\nimport type { Interaction } from '@interactjs/core/Interaction'\nimport type { Scope } from '@interactjs/core/scope'\nimport type { ActionProps, PointerType, PointerEventType, Element } from '@interactjs/core/types'\nimport is from '@interactjs/utils/is'\nimport { warnOnce } from '@interactjs/utils/misc'\n\ndeclare module '@interactjs/core/Interactable' {\n interface Interactable {\n getAction: (\n this: Interactable,\n pointer: PointerType,\n event: PointerEventType,\n interaction: Interaction,\n element: Element,\n ) => ActionProps | null\n styleCursor: typeof styleCursor\n actionChecker: typeof actionChecker\n ignoreFrom: {\n (...args: any[]): Interactable\n (): boolean\n }\n allowFrom: {\n (...args: any[]): Interactable\n (): boolean\n }\n }\n}\n\nfunction install (scope: Scope) {\n const {\n /** @lends Interactable */\n Interactable, // tslint:disable-line no-shadowed-variable\n } = scope\n\n Interactable.prototype.getAction = function getAction (\n this: Interactable,\n pointer: PointerType,\n event: PointerEventType,\n interaction: Interaction,\n element: Element,\n ): ActionProps {\n const action = defaultActionChecker(this, event, interaction, element, scope)\n\n if (this.options.actionChecker) {\n return this.options.actionChecker(pointer, event, action, this, element, interaction)\n }\n\n return action\n }\n\n /**\n * If the target of the `mousedown`, `pointerdown` or `touchstart` event or any\n * of it's parents match the given CSS selector or Element, no\n * drag/resize/gesture is started.\n *\n * @deprecated\n * Don't use this method. Instead set the `ignoreFrom` option for each action\n * or for `pointerEvents`\n *\n * ```js\n * interact(targett)\n * .draggable({\n * ignoreFrom: 'input, textarea, a[href]'',\n * })\n * .pointerEvents({\n * ignoreFrom: '[no-pointer]',\n * })\n * ```\n *\n * @param {string | Element | null} [newValue] a CSS selector string, an\n * Element or `null` to not ignore any elements\n * @return {string | Element | object} The current ignoreFrom value or this\n * Interactable\n */\n Interactable.prototype.ignoreFrom = warnOnce(function (this: Interactable, newValue) {\n return this._backCompatOption('ignoreFrom', newValue)\n }, 'Interactable.ignoreFrom() has been deprecated. Use Interactble.draggable({ignoreFrom: newValue}).')\n\n /**\n *\n * A drag/resize/gesture is started only If the target of the `mousedown`,\n * `pointerdown` or `touchstart` event or any of it's parents match the given\n * CSS selector or Element.\n *\n * @deprecated\n * Don't use this method. Instead set the `allowFrom` option for each action\n * or for `pointerEvents`\n *\n * ```js\n * interact(targett)\n * .resizable({\n * allowFrom: '.resize-handle',\n * .pointerEvents({\n * allowFrom: '.handle',,\n * })\n * ```\n *\n * @param {string | Element | null} [newValue] a CSS selector string, an\n * Element or `null` to allow from any element\n * @return {string | Element | object} The current allowFrom value or this\n * Interactable\n */\n Interactable.prototype.allowFrom = warnOnce(function (this: Interactable, newValue) {\n return this._backCompatOption('allowFrom', newValue)\n }, 'Interactable.allowFrom() has been deprecated. Use Interactble.draggable({allowFrom: newValue}).')\n\n /**\n * ```js\n * interact('.resize-drag')\n * .resizable(true)\n * .draggable(true)\n * .actionChecker(function (pointer, event, action, interactable, element, interaction) {\n *\n * if (interact.matchesSelector(event.target, '.drag-handle')) {\n * // force drag with handle target\n * action.name = drag\n * }\n * else {\n * // resize from the top and right edges\n * action.name = 'resize'\n * action.edges = { top: true, right: true }\n * }\n *\n * return action\n * })\n * ```\n *\n * Returns or sets the function used to check action to be performed on\n * pointerDown\n *\n * @param {function | null} [checker] A function which takes a pointer event,\n * defaultAction string, interactable, element and interaction as parameters\n * and returns an object with name property 'drag' 'resize' or 'gesture' and\n * optionally an `edges` object with boolean 'top', 'left', 'bottom' and right\n * props.\n * @return {Function | Interactable} The checker function or this Interactable\n */\n Interactable.prototype.actionChecker = actionChecker\n\n /**\n * Returns or sets whether the the cursor should be changed depending on the\n * action that would be performed if the mouse were pressed and dragged.\n *\n * @param {boolean} [newValue]\n * @return {boolean | Interactable} The current setting or this Interactable\n */\n Interactable.prototype.styleCursor = styleCursor\n}\n\nfunction defaultActionChecker (\n interactable: Interactable,\n event: PointerEventType,\n interaction: Interaction,\n element: Element,\n scope: Scope,\n) {\n const rect = interactable.getRect(element)\n const buttons =\n (event as MouseEvent).buttons ||\n {\n 0: 1,\n 1: 4,\n 3: 8,\n 4: 16,\n }[(event as MouseEvent).button as 0 | 1 | 3 | 4]\n const arg = {\n action: null,\n interactable,\n interaction,\n element,\n rect,\n buttons,\n }\n\n scope.fire('auto-start:check', arg)\n\n return arg.action\n}\n\nfunction styleCursor(this: Interactable): boolean\nfunction styleCursor(this: Interactable, newValue: boolean): typeof this\nfunction styleCursor (this: Interactable, newValue?: boolean) {\n if (is.bool(newValue)) {\n this.options.styleCursor = newValue\n\n return this\n }\n\n if (newValue === null) {\n delete this.options.styleCursor\n\n return this\n }\n\n return this.options.styleCursor\n}\n\nfunction actionChecker (this: Interactable, checker: any) {\n if (is.func(checker)) {\n this.options.actionChecker = checker\n\n return this\n }\n\n if (checker === null) {\n delete this.options.actionChecker\n\n return this\n }\n\n return this.options.actionChecker\n}\n\nexport default {\n id: 'auto-start/interactableMethods',\n install,\n}\n", "import type { Interactable } from '@interactjs/core/Interactable'\nimport type { Interaction } from '@interactjs/core/Interaction'\nimport type { Scope, SignalArgs, Plugin } from '@interactjs/core/scope'\nimport type {\n CursorChecker,\n PointerType,\n PointerEventType,\n Element,\n ActionName,\n ActionProps,\n} from '@interactjs/core/types'\nimport * as domUtils from '@interactjs/utils/domUtils'\nimport extend from '@interactjs/utils/extend'\nimport is from '@interactjs/utils/is'\nimport { copyAction } from '@interactjs/utils/misc'\n\nimport InteractableMethods from './InteractableMethods'\n\ndeclare module '@interactjs/core/InteractStatic' {\n export interface InteractStatic {\n maxInteractions: (newValue: any) => any\n }\n}\n\ndeclare module '@interactjs/core/scope' {\n interface Scope {\n autoStart: AutoStart\n }\n\n interface SignalArgs {\n 'autoStart:before-start': Omit & {\n interaction: Interaction\n }\n 'autoStart:prepared': { interaction: Interaction }\n 'auto-start:check': CheckSignalArg\n }\n}\n\ndeclare module '@interactjs/core/options' {\n interface BaseDefaults {\n actionChecker?: any\n cursorChecker?: any\n styleCursor?: any\n }\n\n interface PerActionDefaults {\n manualStart?: boolean\n max?: number\n maxPerElement?: number\n allowFrom?: string | Element\n ignoreFrom?: string | Element\n cursorChecker?: CursorChecker\n\n // only allow left button by default\n // see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons#Return_value\n // TODO: docst\n mouseButtons?: 0 | 1 | 2 | 4 | 8 | 16\n }\n}\n\ninterface CheckSignalArg {\n interactable: Interactable\n interaction: Interaction\n element: Element\n action: ActionProps\n buttons: number\n}\n\nexport interface AutoStart {\n // Allow this many interactions to happen simultaneously\n maxInteractions: number\n withinInteractionLimit: typeof withinInteractionLimit\n cursorElement: Element\n}\n\nfunction install (scope: Scope) {\n const { interactStatic: interact, defaults } = scope\n\n scope.usePlugin(InteractableMethods)\n\n defaults.base.actionChecker = null\n defaults.base.styleCursor = true\n\n extend(defaults.perAction, {\n manualStart: false,\n max: Infinity,\n maxPerElement: 1,\n allowFrom: null,\n ignoreFrom: null,\n\n // only allow left button by default\n // see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons#Return_value\n mouseButtons: 1,\n })\n\n /**\n * Returns or sets the maximum number of concurrent interactions allowed. By\n * default only 1 interaction is allowed at a time (for backwards\n * compatibility). To allow multiple interactions on the same Interactables and\n * elements, you need to enable it in the draggable, resizable and gesturable\n * `'max'` and `'maxPerElement'` options.\n *\n * @alias module:interact.maxInteractions\n *\n * @param {number} [newValue] Any number. newValue <= 0 means no interactions.\n */\n interact.maxInteractions = (newValue: number) => maxInteractions(newValue, scope)\n\n scope.autoStart = {\n // Allow this many interactions to happen simultaneously\n maxInteractions: Infinity,\n withinInteractionLimit,\n cursorElement: null,\n }\n}\n\nfunction prepareOnDown (\n { interaction, pointer, event, eventTarget }: SignalArgs['interactions:down'],\n scope: Scope,\n) {\n if (interaction.interacting()) return\n\n const actionInfo = getActionInfo(interaction, pointer, event, eventTarget, scope)\n prepare(interaction, actionInfo, scope)\n}\n\nfunction prepareOnMove (\n { interaction, pointer, event, eventTarget }: SignalArgs['interactions:move'],\n scope: Scope,\n) {\n if (interaction.pointerType !== 'mouse' || interaction.pointerIsDown || interaction.interacting()) return\n\n const actionInfo = getActionInfo(interaction, pointer, event, eventTarget as Element, scope)\n prepare(interaction, actionInfo, scope)\n}\n\nfunction startOnMove (arg: SignalArgs['interactions:move'], scope: Scope) {\n const { interaction } = arg\n\n if (\n !interaction.pointerIsDown ||\n interaction.interacting() ||\n !interaction.pointerWasMoved ||\n !interaction.prepared.name\n ) {\n return\n }\n\n scope.fire('autoStart:before-start', arg)\n\n const { interactable } = interaction\n const actionName = (interaction as Interaction).prepared.name\n\n if (actionName && interactable) {\n // check manualStart and interaction limit\n if (\n interactable.options[actionName].manualStart ||\n !withinInteractionLimit(interactable, interaction.element, interaction.prepared, scope)\n ) {\n interaction.stop()\n } else {\n interaction.start(interaction.prepared, interactable, interaction.element)\n setInteractionCursor(interaction, scope)\n }\n }\n}\n\nfunction clearCursorOnStop ({ interaction }: { interaction: Interaction }, scope: Scope) {\n const { interactable } = interaction\n\n if (interactable && interactable.options.styleCursor) {\n setCursor(interaction.element, '', scope)\n }\n}\n\n// Check if the current interactable supports the action.\n// If so, return the validated action. Otherwise, return null\nfunction validateAction (\n action: ActionProps,\n interactable: Interactable,\n element: Element,\n eventTarget: Node,\n scope: Scope,\n) {\n if (\n interactable.testIgnoreAllow(interactable.options[action.name], element, eventTarget) &&\n interactable.options[action.name].enabled &&\n withinInteractionLimit(interactable, element, action, scope)\n ) {\n return action\n }\n\n return null\n}\n\nfunction validateMatches (\n interaction: Interaction,\n pointer: PointerType,\n event: PointerEventType,\n matches: Interactable[],\n matchElements: Element[],\n eventTarget: Node,\n scope: Scope,\n) {\n for (let i = 0, len = matches.length; i < len; i++) {\n const match = matches[i]\n const matchElement = matchElements[i]\n const matchAction = match.getAction(pointer, event, interaction, matchElement)\n\n if (!matchAction) {\n continue\n }\n\n const action = validateAction(matchAction, match, matchElement, eventTarget, scope)\n\n if (action) {\n return {\n action,\n interactable: match,\n element: matchElement,\n }\n }\n }\n\n return { action: null, interactable: null, element: null }\n}\n\nfunction getActionInfo (\n interaction: Interaction,\n pointer: PointerType,\n event: PointerEventType,\n eventTarget: Node,\n scope: Scope,\n) {\n let matches: Interactable[] = []\n let matchElements: Element[] = []\n\n let element = eventTarget as Element\n\n function pushMatches (interactable: Interactable) {\n matches.push(interactable)\n matchElements.push(element)\n }\n\n while (is.element(element)) {\n matches = []\n matchElements = []\n\n scope.interactables.forEachMatch(element, pushMatches)\n\n const actionInfo = validateMatches(\n interaction,\n pointer,\n event,\n matches,\n matchElements,\n eventTarget,\n scope,\n )\n\n if (actionInfo.action && !actionInfo.interactable.options[actionInfo.action.name].manualStart) {\n return actionInfo\n }\n\n element = domUtils.parentNode(element) as Element\n }\n\n return { action: null, interactable: null, element: null }\n}\n\nfunction prepare (\n interaction: Interaction,\n {\n action,\n interactable,\n element,\n }: {\n action: ActionProps\n interactable: Interactable\n element: Element\n },\n scope: Scope,\n) {\n action = action || { name: null }\n\n interaction.interactable = interactable\n interaction.element = element\n copyAction(interaction.prepared, action)\n\n interaction.rect = interactable && action.name ? interactable.getRect(element) : null\n\n setInteractionCursor(interaction, scope)\n\n scope.fire('autoStart:prepared', { interaction })\n}\n\nfunction withinInteractionLimit (\n interactable: Interactable,\n element: Element,\n action: ActionProps,\n scope: Scope,\n) {\n const options = interactable.options\n const maxActions = options[action.name].max\n const maxPerElement = options[action.name].maxPerElement\n const autoStartMax = scope.autoStart.maxInteractions\n let activeInteractions = 0\n let interactableCount = 0\n let elementCount = 0\n\n // no actions if any of these values == 0\n if (!(maxActions && maxPerElement && autoStartMax)) {\n return false\n }\n\n for (const interaction of scope.interactions.list) {\n const otherAction = interaction.prepared.name\n\n if (!interaction.interacting()) {\n continue\n }\n\n activeInteractions++\n\n if (activeInteractions >= autoStartMax) {\n return false\n }\n\n if (interaction.interactable !== interactable) {\n continue\n }\n\n interactableCount += otherAction === action.name ? 1 : 0\n\n if (interactableCount >= maxActions) {\n return false\n }\n\n if (interaction.element === element) {\n elementCount++\n\n if (otherAction === action.name && elementCount >= maxPerElement) {\n return false\n }\n }\n }\n\n return autoStartMax > 0\n}\n\nfunction maxInteractions (newValue: any, scope: Scope) {\n if (is.number(newValue)) {\n scope.autoStart.maxInteractions = newValue\n\n return this\n }\n\n return scope.autoStart.maxInteractions\n}\n\nfunction setCursor (element: Element, cursor: string, scope: Scope) {\n const { cursorElement: prevCursorElement } = scope.autoStart\n\n if (prevCursorElement && prevCursorElement !== element) {\n prevCursorElement.style.cursor = ''\n }\n\n element.ownerDocument.documentElement.style.cursor = cursor\n element.style.cursor = cursor\n scope.autoStart.cursorElement = cursor ? element : null\n}\n\nfunction setInteractionCursor (interaction: Interaction, scope: Scope) {\n const { interactable, element, prepared } = interaction\n\n if (!(interaction.pointerType === 'mouse' && interactable && interactable.options.styleCursor)) {\n // clear previous target element cursor\n if (scope.autoStart.cursorElement) {\n setCursor(scope.autoStart.cursorElement, '', scope)\n }\n\n return\n }\n\n let cursor = ''\n\n if (prepared.name) {\n const cursorChecker = interactable.options[prepared.name].cursorChecker\n\n if (is.func(cursorChecker)) {\n cursor = cursorChecker(prepared, interactable, element, interaction._interacting)\n } else {\n cursor = scope.actions.map[prepared.name].getCursor(prepared)\n }\n }\n\n setCursor(interaction.element, cursor || '', scope)\n}\n\nconst autoStart: Plugin = {\n id: 'auto-start/base',\n before: ['actions'],\n install,\n listeners: {\n 'interactions:down': prepareOnDown,\n 'interactions:move': (arg, scope) => {\n prepareOnMove(arg, scope)\n startOnMove(arg, scope)\n },\n 'interactions:stop': clearCursorOnStop,\n },\n maxInteractions,\n withinInteractionLimit,\n validateAction,\n}\n\nexport default autoStart\n", "import type { Interactable } from '@interactjs/core/Interactable'\nimport type Interaction from '@interactjs/core/Interaction'\nimport type { SignalArgs, Scope } from '@interactjs/core/scope'\nimport type { ActionName, Element } from '@interactjs/core/types'\nimport { parentNode } from '@interactjs/utils/domUtils'\nimport is from '@interactjs/utils/is'\n\nimport autoStart from './base'\n\nfunction beforeStart ({ interaction, eventTarget, dx, dy }: SignalArgs['interactions:move'], scope: Scope) {\n if (interaction.prepared.name !== 'drag') return\n\n // check if a drag is in the correct axis\n const absX = Math.abs(dx)\n const absY = Math.abs(dy)\n const targetOptions = interaction.interactable.options.drag\n const startAxis = targetOptions.startAxis\n const currentAxis = absX > absY ? 'x' : absX < absY ? 'y' : 'xy'\n\n interaction.prepared.axis =\n targetOptions.lockAxis === 'start'\n ? (currentAxis[0] as 'x' | 'y') // always lock to one axis even if currentAxis === 'xy'\n : targetOptions.lockAxis\n\n // if the movement isn't in the startAxis of the interactable\n if (currentAxis !== 'xy' && startAxis !== 'xy' && startAxis !== currentAxis) {\n // cancel the prepared action\n ;(interaction as Interaction).prepared.name = null\n\n // then try to get a drag from another ineractable\n let element = eventTarget as Element\n\n const getDraggable = function (interactable: Interactable): Interactable | void {\n if (interactable === interaction.interactable) return\n\n const options = interaction.interactable.options.drag\n\n if (!options.manualStart && interactable.testIgnoreAllow(options, element, eventTarget)) {\n const action = interactable.getAction(\n interaction.downPointer,\n interaction.downEvent,\n interaction,\n element,\n )\n\n if (\n action &&\n action.name === 'drag' &&\n checkStartAxis(currentAxis, interactable) &&\n autoStart.validateAction(action, interactable, element, eventTarget, scope)\n ) {\n return interactable\n }\n }\n }\n\n // check all interactables\n while (is.element(element)) {\n const interactable = scope.interactables.forEachMatch(element, getDraggable)\n\n if (interactable) {\n ;(interaction as Interaction).prepared.name = 'drag'\n interaction.interactable = interactable\n interaction.element = element\n break\n }\n\n element = parentNode(element) as Element\n }\n }\n}\n\nfunction checkStartAxis (startAxis: string, interactable: Interactable) {\n if (!interactable) {\n return false\n }\n\n const thisAxis = interactable.options.drag.startAxis\n\n return startAxis === 'xy' || thisAxis === 'xy' || thisAxis === startAxis\n}\n\nexport default {\n id: 'auto-start/dragAxis',\n listeners: { 'autoStart:before-start': beforeStart },\n}\n", "import type Interaction from '@interactjs/core/Interaction'\nimport type { Scope, Plugin } from '@interactjs/core/scope'\n\nimport basePlugin from './base'\n\ndeclare module '@interactjs/core/options' {\n interface PerActionDefaults {\n hold?: number\n delay?: number\n }\n}\n\ndeclare module '@interactjs/core/Interaction' {\n interface Interaction {\n autoStartHoldTimer?: any\n }\n}\n\nfunction install (scope: Scope) {\n const { defaults } = scope\n\n scope.usePlugin(basePlugin)\n\n defaults.perAction.hold = 0\n defaults.perAction.delay = 0\n}\n\nfunction getHoldDuration (interaction: Interaction) {\n const actionName = interaction.prepared && interaction.prepared.name\n\n if (!actionName) {\n return null\n }\n\n const options = interaction.interactable.options\n\n return options[actionName].hold || options[actionName].delay\n}\n\nconst hold: Plugin = {\n id: 'auto-start/hold',\n install,\n listeners: {\n 'interactions:new': ({ interaction }) => {\n interaction.autoStartHoldTimer = null\n },\n\n 'autoStart:prepared': ({ interaction }) => {\n const hold = getHoldDuration(interaction)\n\n if (hold > 0) {\n interaction.autoStartHoldTimer = setTimeout(() => {\n interaction.start(interaction.prepared, interaction.interactable, interaction.element)\n }, hold)\n }\n },\n\n 'interactions:move': ({ interaction, duplicate }) => {\n if (interaction.autoStartHoldTimer && interaction.pointerWasMoved && !duplicate) {\n clearTimeout(interaction.autoStartHoldTimer)\n interaction.autoStartHoldTimer = null\n }\n },\n\n // prevent regular down->move autoStart\n 'autoStart:before-start': ({ interaction }) => {\n const holdDuration = getHoldDuration(interaction)\n\n if (holdDuration > 0) {\n interaction.prepared.name = null\n }\n },\n },\n getHoldDuration,\n}\nexport default hold\n", "import type { Scope } from '@interactjs/core/scope'\n\nimport autoStart from './base'\nimport dragAxis from './dragAxis'\nimport hold from './hold'\n\nexport default {\n id: 'auto-start',\n install (scope: Scope) {\n scope.usePlugin(autoStart)\n scope.usePlugin(hold)\n scope.usePlugin(dragAxis)\n },\n}\n", "import type { Interactable } from '@interactjs/core/Interactable'\nimport type Interaction from '@interactjs/core/Interaction'\nimport type { Scope } from '@interactjs/core/scope'\nimport type { PointerEventType } from '@interactjs/core/types'\nimport { matchesSelector, nodeContains } from '@interactjs/utils/domUtils'\nimport is from '@interactjs/utils/is'\nimport { getWindow } from '@interactjs/utils/window'\n\ndeclare module '@interactjs/core/Interactable' {\n interface Interactable {\n preventDefault: typeof preventDefault\n checkAndPreventDefault: (event: Event) => void\n }\n}\n\ntype PreventDefaultValue = 'always' | 'never' | 'auto'\nfunction preventDefault(this: Interactable): PreventDefaultValue\nfunction preventDefault(this: Interactable, newValue: PreventDefaultValue): typeof this\nfunction preventDefault (this: Interactable, newValue?: PreventDefaultValue) {\n if (/^(always|never|auto)$/.test(newValue)) {\n this.options.preventDefault = newValue\n return this\n }\n\n if (is.bool(newValue)) {\n this.options.preventDefault = newValue ? 'always' : 'never'\n return this\n }\n\n return this.options.preventDefault\n}\n\nfunction checkAndPreventDefault (interactable: Interactable, scope: Scope, event: Event) {\n const setting = interactable.options.preventDefault\n\n if (setting === 'never') return\n\n if (setting === 'always') {\n event.preventDefault()\n return\n }\n\n // setting === 'auto'\n\n // if the browser supports passive event listeners and isn't running on iOS,\n // don't preventDefault of touch{start,move} events. CSS touch-action and\n // user-select should be used instead of calling event.preventDefault().\n if (scope.events.supportsPassive && /^touch(start|move)$/.test(event.type)) {\n const doc = getWindow(event.target).document\n const docOptions = scope.getDocOptions(doc)\n\n if (!(docOptions && docOptions.events) || docOptions.events.passive !== false) {\n return\n }\n }\n\n // don't preventDefault of pointerdown events\n if (/^(mouse|pointer|touch)*(down|start)/i.test(event.type)) {\n return\n }\n\n // don't preventDefault on editable elements\n if (\n is.element(event.target) &&\n matchesSelector(event.target, 'input,select,textarea,[contenteditable=true],[contenteditable=true] *')\n ) {\n return\n }\n\n event.preventDefault()\n}\n\nfunction onInteractionEvent ({ interaction, event }: { interaction: Interaction, event: PointerEventType }) {\n if (interaction.interactable) {\n interaction.interactable.checkAndPreventDefault(event as Event)\n }\n}\n\nexport function install (scope: Scope) {\n /** @lends Interactable */\n const { Interactable } = scope\n\n /**\n * Returns or sets whether to prevent the browser's default behaviour in\n * response to pointer events. Can be set to:\n * - `'always'` to always prevent\n * - `'never'` to never prevent\n * - `'auto'` to let interact.js try to determine what would be best\n *\n * @param {string} [newValue] `'always'`, `'never'` or `'auto'`\n * @return {string | Interactable} The current setting or this Interactable\n */\n Interactable.prototype.preventDefault = preventDefault\n\n Interactable.prototype.checkAndPreventDefault = function (event) {\n return checkAndPreventDefault(this, scope, event)\n }\n\n // prevent native HTML5 drag on interact.js target elements\n scope.interactions.docEvents.push({\n type: 'dragstart',\n listener (event) {\n for (const interaction of scope.interactions.list) {\n if (\n interaction.element &&\n (interaction.element === event.target || nodeContains(interaction.element, event.target))\n ) {\n interaction.interactable.checkAndPreventDefault(event)\n return\n }\n }\n },\n })\n}\n\nexport default {\n id: 'core/interactablePreventDefault',\n install,\n listeners: ['down', 'move', 'up', 'cancel'].reduce((acc, eventType) => {\n acc[`interactions:${eventType}`] = onInteractionEvent\n return acc\n }, {} as any),\n}\n", "export default {}\n", "import type Interaction from '@interactjs/core/Interaction'\nimport type { Scope, Plugin } from '@interactjs/core/scope'\nimport type { Element, OptionMethod } from '@interactjs/core/types'\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport visualizer from '@interactjs/dev-tools/visualizer/plugin'\nimport domObjects from '@interactjs/utils/domObjects'\nimport { parentNode } from '@interactjs/utils/domUtils'\nimport extend from '@interactjs/utils/extend'\nimport is from '@interactjs/utils/is'\nimport * as win from '@interactjs/utils/window'\n\ndeclare module '@interactjs/core/scope' {\n interface Scope {\n logger: Logger\n }\n}\n\ndeclare module '@interactjs/core/InteractStatic' {\n export interface InteractStatic {\n visializer: typeof visualizer\n }\n}\n\ndeclare module '@interactjs/core/options' {\n interface BaseDefaults {\n devTools?: DevToolsOptions\n }\n}\n\ndeclare module '@interactjs/core/Interactable' {\n interface Interactable {\n devTools: OptionMethod\n }\n}\n\nexport interface DevToolsOptions {\n ignore: { [P in keyof typeof CheckName]?: boolean }\n}\n\nexport interface Logger {\n warn: (...args: any[]) => void\n error: (...args: any[]) => void\n log: (...args: any[]) => void\n}\n\nexport interface Check {\n name: CheckName\n text: string\n perform: (interaction: Interaction) => boolean\n getInfo: (interaction: Interaction) => any[]\n}\n\nenum CheckName {\n touchAction = 'touchAction',\n boxSizing = 'boxSizing',\n noListeners = 'noListeners',\n}\n\nconst prefix = '[interact.js] '\nconst links = {\n touchAction: 'https://developer.mozilla.org/en-US/docs/Web/CSS/touch-action',\n boxSizing: 'https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing',\n}\n\n// eslint-disable-next-line no-undef\nconst isProduction = process.env.NODE_ENV === 'production'\n\nfunction install (scope: Scope, { logger }: { logger?: Logger } = {}) {\n const { Interactable, defaults } = scope\n\n scope.logger = logger || console\n\n defaults.base.devTools = {\n ignore: {},\n }\n\n Interactable.prototype.devTools = function (options?: object) {\n if (options) {\n extend(this.options.devTools, options)\n return this\n }\n\n return this.options.devTools\n }\n\n scope.usePlugin(visualizer)\n}\n\nconst checks: Check[] = [\n {\n name: CheckName.touchAction,\n perform ({ element }) {\n return !parentHasStyle(element, 'touchAction', /pan-|pinch|none/)\n },\n getInfo ({ element }) {\n return [element, links.touchAction]\n },\n text: 'Consider adding CSS \"touch-action: none\" to this element\\n',\n },\n\n {\n name: CheckName.boxSizing,\n perform (interaction) {\n const { element } = interaction\n\n return (\n interaction.prepared.name === 'resize' &&\n element instanceof domObjects.HTMLElement &&\n !hasStyle(element, 'boxSizing', /border-box/)\n )\n },\n text: 'Consider adding CSS \"box-sizing: border-box\" to this resizable element',\n getInfo ({ element }) {\n return [element, links.boxSizing]\n },\n },\n\n {\n name: CheckName.noListeners,\n perform (interaction) {\n const actionName = interaction.prepared.name\n const moveListeners = interaction.interactable.events.types[`${actionName}move`] || []\n\n return !moveListeners.length\n },\n getInfo (interaction) {\n return [interaction.prepared.name, interaction.interactable]\n },\n text: 'There are no listeners set for this action',\n },\n]\n\nfunction hasStyle (element: HTMLElement, prop: keyof CSSStyleDeclaration, styleRe: RegExp) {\n const value = element.style[prop] || win.window.getComputedStyle(element)[prop]\n return styleRe.test((value || '').toString())\n}\n\nfunction parentHasStyle (element: Element, prop: keyof CSSStyleDeclaration, styleRe: RegExp) {\n let parent = element as HTMLElement\n\n while (is.element(parent)) {\n if (hasStyle(parent, prop, styleRe)) {\n return true\n }\n\n parent = parentNode(parent) as HTMLElement\n }\n\n return false\n}\n\nconst id = 'dev-tools'\nconst defaultExport: Plugin = isProduction\n ? { id, install: () => {} }\n : {\n id,\n install,\n listeners: {\n 'interactions:action-start': ({ interaction }, scope) => {\n for (const check of checks) {\n const options = interaction.interactable && interaction.interactable.options\n\n if (\n !(options && options.devTools && options.devTools.ignore[check.name]) &&\n check.perform(interaction)\n ) {\n scope.logger.warn(prefix + check.text, ...check.getInfo(interaction))\n }\n }\n },\n },\n checks,\n CheckName,\n links,\n prefix,\n }\n\nexport default defaultExport\n", "import * as arr from './arr'\nimport is from './is'\n\n// tslint:disable-next-line ban-types\nexport default function clone (source: T): Partial {\n const dest = {} as Partial\n\n for (const prop in source) {\n const value = source[prop]\n\n if (is.plainObject(value)) {\n dest[prop] = clone(value) as any\n } else if (is.array(value)) {\n dest[prop] = arr.from(value) as typeof value\n } else {\n dest[prop] = value\n }\n }\n\n return dest\n}\n", "import type { EventPhase } from '@interactjs/core/InteractEvent'\nimport type { Interaction, DoAnyPhaseArg } from '@interactjs/core/Interaction'\nimport type { EdgeOptions, FullRect, Point, Rect } from '@interactjs/core/types'\nimport clone from '@interactjs/utils/clone'\nimport extend from '@interactjs/utils/extend'\nimport * as rectUtils from '@interactjs/utils/rect'\n\nimport type { Modifier, ModifierArg, ModifierState } from './base'\n\nexport interface ModificationResult {\n delta: Point\n rectDelta: Rect\n coords: Point\n rect: FullRect\n eventProps: any[]\n changed: boolean\n}\n\ninterface MethodArg {\n phase: EventPhase\n pageCoords: Point\n rect: FullRect\n coords: Point\n preEnd?: boolean\n skipModifiers?: number\n}\n\nexport default class Modification {\n states: ModifierState[] = []\n startOffset: Rect = { left: 0, right: 0, top: 0, bottom: 0 }\n startDelta!: Point\n result!: ModificationResult\n endResult!: Point\n edges!: EdgeOptions\n readonly interaction: Readonly\n\n constructor (interaction: Interaction) {\n this.interaction = interaction\n this.result = createResult()\n }\n\n start ({ phase }: { phase: EventPhase }, pageCoords: Point) {\n const { interaction } = this\n const modifierList = getModifierList(interaction)\n this.prepareStates(modifierList)\n\n this.edges = extend({}, interaction.edges)\n this.startOffset = getRectOffset(interaction.rect, pageCoords)\n this.startDelta = { x: 0, y: 0 }\n\n const arg = this.fillArg({\n phase,\n pageCoords,\n preEnd: false,\n })\n\n this.result = createResult()\n this.startAll(arg)\n\n const result = (this.result = this.setAll(arg))\n\n return result\n }\n\n fillArg (arg: Partial) {\n const { interaction } = this\n\n arg.interaction = interaction\n arg.interactable = interaction.interactable\n arg.element = interaction.element\n arg.rect = arg.rect || interaction.rect\n arg.edges = this.edges\n arg.startOffset = this.startOffset\n\n return arg as ModifierArg\n }\n\n startAll (arg: MethodArg & Partial) {\n for (const state of this.states) {\n if (state.methods.start) {\n arg.state = state\n state.methods.start(arg as ModifierArg)\n }\n }\n }\n\n setAll (arg: MethodArg & Partial): ModificationResult {\n const { phase, preEnd, skipModifiers, rect: unmodifiedRect } = arg\n\n arg.coords = extend({}, arg.pageCoords)\n arg.rect = extend({}, unmodifiedRect)\n\n const states = skipModifiers ? this.states.slice(skipModifiers) : this.states\n\n const newResult = createResult(arg.coords, arg.rect)\n\n for (const state of states) {\n const { options } = state\n const lastModifierCoords = extend({}, arg.coords)\n let returnValue = null\n\n if (state.methods?.set && this.shouldDo(options, preEnd, phase)) {\n arg.state = state\n returnValue = state.methods.set(arg as ModifierArg)\n\n rectUtils.addEdges(this.interaction.edges, arg.rect, {\n x: arg.coords.x - lastModifierCoords.x,\n y: arg.coords.y - lastModifierCoords.y,\n })\n }\n\n newResult.eventProps.push(returnValue)\n }\n\n newResult.delta.x = arg.coords.x - arg.pageCoords.x\n newResult.delta.y = arg.coords.y - arg.pageCoords.y\n\n newResult.rectDelta.left = arg.rect.left - unmodifiedRect.left\n newResult.rectDelta.right = arg.rect.right - unmodifiedRect.right\n newResult.rectDelta.top = arg.rect.top - unmodifiedRect.top\n newResult.rectDelta.bottom = arg.rect.bottom - unmodifiedRect.bottom\n\n const prevCoords = this.result.coords\n const prevRect = this.result.rect\n\n if (prevCoords && prevRect) {\n const rectChanged =\n newResult.rect.left !== prevRect.left ||\n newResult.rect.right !== prevRect.right ||\n newResult.rect.top !== prevRect.top ||\n newResult.rect.bottom !== prevRect.bottom\n\n newResult.changed =\n rectChanged || prevCoords.x !== newResult.coords.x || prevCoords.y !== newResult.coords.y\n }\n\n return newResult\n }\n\n applyToInteraction (arg: { phase: EventPhase, rect?: Rect }) {\n const { interaction } = this\n const { phase } = arg\n const curCoords = interaction.coords.cur\n const startCoords = interaction.coords.start\n const { result, startDelta } = this\n const curDelta = result.delta\n\n if (phase === 'start') {\n extend(this.startDelta, result.delta)\n }\n\n for (const [coordsSet, delta] of [\n [startCoords, startDelta],\n [curCoords, curDelta],\n ] as const) {\n coordsSet.page.x += delta.x\n coordsSet.page.y += delta.y\n coordsSet.client.x += delta.x\n coordsSet.client.y += delta.y\n }\n\n const { rectDelta } = this.result\n const rect = arg.rect || interaction.rect\n\n rect.left += rectDelta.left\n rect.right += rectDelta.right\n rect.top += rectDelta.top\n rect.bottom += rectDelta.bottom\n\n rect.width = rect.right - rect.left\n rect.height = rect.bottom - rect.top\n }\n\n setAndApply (\n arg: Partial & {\n phase: EventPhase\n preEnd?: boolean\n skipModifiers?: number\n modifiedCoords?: Point\n },\n ): void | false {\n const { interaction } = this\n const { phase, preEnd, skipModifiers } = arg\n\n const result = this.setAll(\n this.fillArg({\n preEnd,\n phase,\n pageCoords: arg.modifiedCoords || interaction.coords.cur.page,\n }),\n )\n\n this.result = result\n\n // don't fire an action move if a modifier would keep the event in the same\n // cordinates as before\n if (\n !result.changed &&\n (!skipModifiers || skipModifiers < this.states.length) &&\n interaction.interacting()\n ) {\n return false\n }\n\n if (arg.modifiedCoords) {\n const { page } = interaction.coords.cur\n const adjustment = {\n x: arg.modifiedCoords.x - page.x,\n y: arg.modifiedCoords.y - page.y,\n }\n\n result.coords.x += adjustment.x\n result.coords.y += adjustment.y\n result.delta.x += adjustment.x\n result.delta.y += adjustment.y\n }\n\n this.applyToInteraction(arg)\n }\n\n beforeEnd (arg: Omit & { state?: ModifierState }): void | false {\n const { interaction, event } = arg\n const states = this.states\n\n if (!states || !states.length) {\n return\n }\n\n let doPreend = false\n\n for (const state of states) {\n arg.state = state\n const { options, methods } = state\n\n const endPosition = methods.beforeEnd && methods.beforeEnd(arg as unknown as ModifierArg)\n\n if (endPosition) {\n this.endResult = endPosition\n return false\n }\n\n doPreend = doPreend || (!doPreend && this.shouldDo(options, true, arg.phase, true))\n }\n\n if (doPreend) {\n // trigger a final modified move before ending\n interaction.move({ event, preEnd: true })\n }\n }\n\n stop (arg: { interaction: Interaction }) {\n const { interaction } = arg\n\n if (!this.states || !this.states.length) {\n return\n }\n\n const modifierArg: Partial = extend(\n {\n states: this.states,\n interactable: interaction.interactable,\n element: interaction.element,\n rect: null,\n },\n arg,\n )\n\n this.fillArg(modifierArg)\n\n for (const state of this.states) {\n modifierArg.state = state\n\n if (state.methods.stop) {\n state.methods.stop(modifierArg as ModifierArg)\n }\n }\n\n this.states = null\n this.endResult = null\n }\n\n prepareStates (modifierList: Modifier[]) {\n this.states = []\n\n for (let index = 0; index < modifierList.length; index++) {\n const { options, methods, name } = modifierList[index]\n\n this.states.push({\n options,\n methods,\n index,\n name,\n })\n }\n\n return this.states\n }\n\n restoreInteractionCoords ({ interaction: { coords, rect, modification } }: { interaction: Interaction }) {\n if (!modification.result) return\n\n const { startDelta } = modification\n const { delta: curDelta, rectDelta } = modification.result\n\n const coordsAndDeltas = [\n [coords.start, startDelta],\n [coords.cur, curDelta],\n ]\n\n for (const [coordsSet, delta] of coordsAndDeltas as any) {\n coordsSet.page.x -= delta.x\n coordsSet.page.y -= delta.y\n coordsSet.client.x -= delta.x\n coordsSet.client.y -= delta.y\n }\n\n rect.left -= rectDelta.left\n rect.right -= rectDelta.right\n rect.top -= rectDelta.top\n rect.bottom -= rectDelta.bottom\n }\n\n shouldDo (options, preEnd?: boolean, phase?: string, requireEndOnly?: boolean) {\n if (\n // ignore disabled modifiers\n !options ||\n options.enabled === false ||\n // check if we require endOnly option to fire move before end\n (requireEndOnly && !options.endOnly) ||\n // don't apply endOnly modifiers when not ending\n (options.endOnly && !preEnd) ||\n // check if modifier should run be applied on start\n (phase === 'start' && !options.setStart)\n ) {\n return false\n }\n\n return true\n }\n\n copyFrom (other: Modification) {\n this.startOffset = other.startOffset\n this.startDelta = other.startDelta\n this.edges = other.edges\n this.states = other.states.map((s) => clone(s) as ModifierState)\n this.result = createResult(extend({}, other.result.coords), extend({}, other.result.rect))\n }\n\n destroy () {\n for (const prop in this) {\n this[prop] = null\n }\n }\n}\n\nfunction createResult (coords?: Point, rect?: FullRect): ModificationResult {\n return {\n rect,\n coords,\n delta: { x: 0, y: 0 },\n rectDelta: {\n left: 0,\n right: 0,\n top: 0,\n bottom: 0,\n },\n eventProps: [],\n changed: true,\n }\n}\n\nfunction getModifierList (interaction) {\n const actionOptions = interaction.interactable.options[interaction.prepared.name]\n const actionModifiers = actionOptions.modifiers\n\n if (actionModifiers && actionModifiers.length) {\n return actionModifiers\n }\n\n return ['snap', 'snapSize', 'snapEdges', 'restrict', 'restrictEdges', 'restrictSize']\n .map((type) => {\n const options = actionOptions[type]\n\n return (\n options &&\n options.enabled && {\n options,\n methods: options._methods,\n }\n )\n })\n .filter((m) => !!m)\n}\n\nexport function getRectOffset (rect, coords) {\n return rect\n ? {\n left: coords.x - rect.left,\n top: coords.y - rect.top,\n right: rect.right - coords.x,\n bottom: rect.bottom - coords.y,\n }\n : {\n left: 0,\n top: 0,\n right: 0,\n bottom: 0,\n }\n}\n", "import type { EventPhase, InteractEvent } from '@interactjs/core/InteractEvent'\nimport type { Interactable } from '@interactjs/core/Interactable'\nimport type Interaction from '@interactjs/core/Interaction'\nimport type { Plugin } from '@interactjs/core/scope'\nimport type { EdgeOptions, FullRect, Point, Rect } from '@interactjs/core/types'\n\nimport Modification from './Modification'\n\ndeclare module '@interactjs/core/Interaction' {\n interface Interaction {\n modification?: Modification\n }\n}\n\ndeclare module '@interactjs/core/InteractEvent' {\n interface InteractEvent {\n modifiers?: Array<{\n name: string\n [key: string]: any\n }>\n }\n}\n\ndeclare module '@interactjs/core/options' {\n interface PerActionDefaults {\n modifiers?: Modifier[]\n }\n}\n\nexport interface Modifier<\n Defaults = any,\n State extends ModifierState = any,\n Name extends string = any,\n Result = any,\n> {\n options: Defaults\n methods: {\n start?: (arg: ModifierArg) => void\n set?: (arg: ModifierArg) => Result\n beforeEnd?: (arg: ModifierArg) => Point | void\n stop?: (arg: ModifierArg) => void\n }\n name?: Name\n enable: () => Modifier\n disable: () => Modifier\n}\n\nexport type ModifierState = {\n options: Defaults\n methods?: Modifier['methods']\n index?: number\n name?: Name\n} & StateProps\n\nexport interface ModifierArg {\n interaction: Interaction\n interactable: Interactable\n phase: EventPhase\n rect: FullRect\n edges: EdgeOptions\n state: State\n element: Element\n pageCoords: Point\n prevCoords: Point\n prevRect?: FullRect\n coords: Point\n startOffset: Rect\n preEnd?: boolean\n}\n\nexport interface ModifierModule<\n Defaults extends { enabled?: boolean },\n State extends ModifierState,\n Result = unknown,\n> {\n defaults?: Defaults\n start?(arg: ModifierArg): void\n set?(arg: ModifierArg): Result\n beforeEnd?(arg: ModifierArg): Point | void\n stop?(arg: ModifierArg): void\n}\n\nexport interface ModifierFunction<\n Defaults extends { enabled?: boolean },\n State extends ModifierState,\n Name extends string,\n> {\n (_options?: Partial): Modifier\n _defaults: Defaults\n _methods: ModifierModule\n}\n\nexport function makeModifier<\n Defaults extends { enabled?: boolean },\n State extends ModifierState,\n Name extends string,\n Result,\n> (module: ModifierModule, name?: Name) {\n const { defaults } = module\n const methods = {\n start: module.start,\n set: module.set,\n beforeEnd: module.beforeEnd,\n stop: module.stop,\n }\n\n const modifier = (_options?: Partial) => {\n const options = (_options || {}) as Defaults\n\n options.enabled = options.enabled !== false\n\n // add missing defaults to options\n for (const prop in defaults) {\n if (!(prop in options)) {\n ;(options as any)[prop] = defaults[prop]\n }\n }\n\n const m: Modifier = {\n options,\n methods,\n name,\n enable: () => {\n options.enabled = true\n return m\n },\n disable: () => {\n options.enabled = false\n return m\n },\n }\n\n return m\n }\n\n if (name && typeof name === 'string') {\n // for backwrads compatibility\n modifier._defaults = defaults\n modifier._methods = methods\n }\n\n return modifier\n}\n\nexport function addEventModifiers ({\n iEvent,\n interaction,\n}: {\n iEvent: InteractEvent\n interaction: Interaction\n}) {\n const result = interaction.modification!.result\n\n if (result) {\n iEvent.modifiers = result.eventProps\n }\n}\n\nconst modifiersBase: Plugin = {\n id: 'modifiers/base',\n before: ['actions'],\n install: (scope) => {\n scope.defaults.perAction.modifiers = []\n },\n listeners: {\n 'interactions:new': ({ interaction }) => {\n interaction.modification = new Modification(interaction)\n },\n\n 'interactions:before-action-start': (arg) => {\n const modification = arg.interaction.modification!\n\n modification.start(arg, arg.interaction.coords.start.page)\n arg.interaction.edges = modification.edges\n modification.applyToInteraction(arg)\n },\n\n 'interactions:before-action-move': (arg) => arg.interaction.modification.setAndApply(arg),\n\n 'interactions:before-action-end': (arg) => arg.interaction.modification.beforeEnd(arg),\n\n 'interactions:action-start': addEventModifiers,\n 'interactions:action-move': addEventModifiers,\n 'interactions:action-end': addEventModifiers,\n\n 'interactions:after-action-start': (arg) => arg.interaction.modification.restoreInteractionCoords(arg),\n 'interactions:after-action-move': (arg) => arg.interaction.modification.restoreInteractionCoords(arg),\n\n 'interactions:stop': (arg) => arg.interaction.modification.stop(arg),\n },\n}\n\nexport default modifiersBase\n", "import type { Point, Listeners, OrBoolean, Element } from '@interactjs/core/types'\n\nexport interface Defaults {\n base: BaseDefaults\n perAction: PerActionDefaults\n actions: ActionDefaults\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface ActionDefaults {}\n\nexport interface BaseDefaults {\n preventDefault?: 'auto' | 'never' | string\n deltaSource?: 'page' | 'client'\n context?: Node\n}\n\nexport interface PerActionDefaults {\n enabled?: boolean\n origin?: Point | string | Element\n listeners?: Listeners\n allowFrom?: string | Element\n ignoreFrom?: string | Element\n}\n\nexport type Options = Partial &\nPartial & {\n [P in keyof ActionDefaults]?: Partial\n}\n\nexport interface OptionsArg extends BaseDefaults, OrBoolean> {}\n\nexport const defaults: Defaults = {\n base: {\n preventDefault: 'auto',\n deltaSource: 'page',\n },\n\n perAction: {\n enabled: false,\n origin: { x: 0, y: 0 },\n },\n\n actions: {} as ActionDefaults,\n}\n", "import type { Point, FullRect, PointerEventType, Element } from '@interactjs/core/types'\nimport extend from '@interactjs/utils/extend'\nimport getOriginXY from '@interactjs/utils/getOriginXY'\nimport hypot from '@interactjs/utils/hypot'\n\nimport { BaseEvent } from './BaseEvent'\nimport type { Interaction } from './Interaction'\nimport { defaults } from './options'\nimport type { ActionName } from './types'\n\nexport type EventPhase = keyof PhaseMap\n\nexport interface PhaseMap {\n start: true\n move: true\n end: true\n}\n\n// defined outside of class definition to avoid assignment of undefined during\n// construction\nexport interface InteractEvent {\n pageX: number\n pageY: number\n\n clientX: number\n clientY: number\n\n dx: number\n dy: number\n\n velocityX: number\n velocityY: number\n}\n\nexport class InteractEvent<\n T extends ActionName = never,\n P extends EventPhase = EventPhase,\n> extends BaseEvent {\n declare target: Element\n declare currentTarget: Element\n relatedTarget: Element | null = null\n screenX?: number\n screenY?: number\n button: number\n buttons: number\n ctrlKey: boolean\n shiftKey: boolean\n altKey: boolean\n metaKey: boolean\n page: Point\n client: Point\n delta: Point\n rect: FullRect\n x0: number\n y0: number\n t0: number\n dt: number\n duration: number\n clientX0: number\n clientY0: number\n velocity: Point\n speed: number\n swipe: ReturnType['getSwipe']>\n // resize\n axes?: 'x' | 'y' | 'xy'\n preEnd?: boolean\n\n /** */\n constructor (\n interaction: Interaction,\n event: PointerEventType,\n actionName: T,\n phase: P,\n element: Element,\n preEnd?: boolean,\n type?: string,\n ) {\n super(interaction)\n\n element = element || interaction.element\n\n const target = interaction.interactable\n const deltaSource = (((target && target.options) || defaults) as any).deltaSource as 'page' | 'client'\n const origin = getOriginXY(target, element, actionName)\n const starting = phase === 'start'\n const ending = phase === 'end'\n const prevEvent = starting ? this : interaction.prevEvent\n const coords = starting\n ? interaction.coords.start\n : ending\n ? { page: prevEvent.page, client: prevEvent.client, timeStamp: interaction.coords.cur.timeStamp }\n : interaction.coords.cur\n\n this.page = extend({}, coords.page)\n this.client = extend({}, coords.client)\n this.rect = extend({}, interaction.rect)\n this.timeStamp = coords.timeStamp\n\n if (!ending) {\n this.page.x -= origin.x\n this.page.y -= origin.y\n\n this.client.x -= origin.x\n this.client.y -= origin.y\n }\n\n this.ctrlKey = event.ctrlKey\n this.altKey = event.altKey\n this.shiftKey = event.shiftKey\n this.metaKey = event.metaKey\n this.button = (event as MouseEvent).button\n this.buttons = (event as MouseEvent).buttons\n this.target = element\n this.currentTarget = element\n this.preEnd = preEnd\n this.type = type || actionName + (phase || '')\n this.interactable = target\n\n this.t0 = starting ? interaction.pointers[interaction.pointers.length - 1].downTime : prevEvent.t0\n\n this.x0 = interaction.coords.start.page.x - origin.x\n this.y0 = interaction.coords.start.page.y - origin.y\n this.clientX0 = interaction.coords.start.client.x - origin.x\n this.clientY0 = interaction.coords.start.client.y - origin.y\n\n if (starting || ending) {\n this.delta = { x: 0, y: 0 }\n } else {\n this.delta = {\n x: this[deltaSource].x - prevEvent[deltaSource].x,\n y: this[deltaSource].y - prevEvent[deltaSource].y,\n }\n }\n\n this.dt = interaction.coords.delta.timeStamp\n this.duration = this.timeStamp - this.t0\n\n // velocity and speed in pixels per second\n this.velocity = extend({}, interaction.coords.velocity[deltaSource])\n this.speed = hypot(this.velocity.x, this.velocity.y)\n\n this.swipe = ending || phase === 'inertiastart' ? this.getSwipe() : null\n }\n\n getSwipe () {\n const interaction = this._interaction\n\n if (interaction.prevEvent.speed < 600 || this.timeStamp - interaction.prevEvent.timeStamp > 150) {\n return null\n }\n\n let angle = (180 * Math.atan2(interaction.prevEvent.velocityY, interaction.prevEvent.velocityX)) / Math.PI\n const overlap = 22.5\n\n if (angle < 0) {\n angle += 360\n }\n\n const left = 135 - overlap <= angle && angle < 225 + overlap\n const up = 225 - overlap <= angle && angle < 315 + overlap\n\n const right = !left && (315 - overlap <= angle || angle < 45 + overlap)\n const down = !up && 45 - overlap <= angle && angle < 135 + overlap\n\n return {\n up,\n down,\n left,\n right,\n angle,\n speed: interaction.prevEvent.speed,\n velocity: {\n x: interaction.prevEvent.velocityX,\n y: interaction.prevEvent.velocityY,\n },\n }\n }\n\n preventDefault () {}\n\n /**\n * Don't call listeners on the remaining targets\n */\n stopImmediatePropagation () {\n this.immediatePropagationStopped = this.propagationStopped = true\n }\n\n /**\n * Don't call any other listeners (even on the current target)\n */\n stopPropagation () {\n this.propagationStopped = true\n }\n}\n\n// getters and setters defined here to support typescript 3.6 and below which\n// don't support getter and setters in .d.ts files\nObject.defineProperties(InteractEvent.prototype, {\n pageX: {\n get () {\n return this.page.x\n },\n set (value) {\n this.page.x = value\n },\n },\n pageY: {\n get () {\n return this.page.y\n },\n set (value) {\n this.page.y = value\n },\n },\n\n clientX: {\n get () {\n return this.client.x\n },\n set (value) {\n this.client.x = value\n },\n },\n clientY: {\n get () {\n return this.client.y\n },\n set (value) {\n this.client.y = value\n },\n },\n\n dx: {\n get () {\n return this.delta.x\n },\n set (value) {\n this.delta.x = value\n },\n },\n dy: {\n get () {\n return this.delta.y\n },\n set (value) {\n this.delta.y = value\n },\n },\n\n velocityX: {\n get () {\n return this.velocity.x\n },\n set (value) {\n this.velocity.x = value\n },\n },\n velocityY: {\n get () {\n return this.velocity.y\n },\n set (value) {\n this.velocity.y = value\n },\n },\n})\n", "import type { PointerEventType, PointerType } from '@interactjs/core/types'\n\nexport class PointerInfo {\n id: number\n pointer: PointerType\n event: PointerEventType\n downTime: number\n downTarget: Node\n\n constructor (id: number, pointer: PointerType, event: PointerEventType, downTime: number, downTarget: Node) {\n this.id = id\n this.pointer = pointer\n this.event = event\n this.downTime = downTime\n this.downTarget = downTarget\n }\n}\n", "import type {\n Element,\n EdgeOptions,\n PointerEventType,\n PointerType,\n FullRect,\n CoordsSet,\n} from '@interactjs/core/types'\nimport * as arr from '@interactjs/utils/arr'\nimport extend from '@interactjs/utils/extend'\nimport hypot from '@interactjs/utils/hypot'\nimport { warnOnce, copyAction } from '@interactjs/utils/misc'\nimport * as pointerUtils from '@interactjs/utils/pointerUtils'\nimport * as rectUtils from '@interactjs/utils/rect'\n\nimport type { EventPhase } from './InteractEvent'\nimport { InteractEvent } from './InteractEvent'\nimport type { Interactable } from './Interactable'\nimport { PointerInfo } from './PointerInfo'\nimport type { ActionDefaults } from './options'\nimport type { Scope } from './scope'\nimport type { ActionName, ActionProps } from './types'\n\nexport enum _ProxyValues {\n interactable = '',\n element = '',\n prepared = '',\n pointerIsDown = '',\n pointerWasMoved = '',\n _proxy = '',\n}\n\nexport enum _ProxyMethods {\n start = '',\n move = '',\n end = '',\n stop = '',\n interacting = '',\n}\n\nexport type PointerArgProps = {\n pointer: PointerType\n event: PointerEventType\n eventTarget: Node\n pointerIndex: number\n pointerInfo: PointerInfo\n interaction: Interaction\n} & T\n\nexport interface DoPhaseArg {\n event: PointerEventType\n phase: EventPhase\n interaction: Interaction\n iEvent: InteractEvent\n preEnd?: boolean\n type?: string\n}\n\nexport type DoAnyPhaseArg = DoPhaseArg\n\ndeclare module '@interactjs/core/scope' {\n interface SignalArgs {\n 'interactions:new': { interaction: Interaction }\n 'interactions:down': PointerArgProps<{\n type: 'down'\n }>\n 'interactions:move': PointerArgProps<{\n type: 'move'\n dx: number\n dy: number\n duplicate: boolean\n }>\n 'interactions:up': PointerArgProps<{\n type: 'up'\n curEventTarget: EventTarget\n }>\n 'interactions:cancel': SignalArgs['interactions:up'] & {\n type: 'cancel'\n curEventTarget: EventTarget\n }\n 'interactions:update-pointer': PointerArgProps<{\n down: boolean\n }>\n 'interactions:remove-pointer': PointerArgProps\n 'interactions:blur': { interaction: Interaction, event: Event, type: 'blur' }\n 'interactions:before-action-start': Omit\n 'interactions:action-start': DoAnyPhaseArg\n 'interactions:after-action-start': DoAnyPhaseArg\n 'interactions:before-action-move': Omit\n 'interactions:action-move': DoAnyPhaseArg\n 'interactions:after-action-move': DoAnyPhaseArg\n 'interactions:before-action-end': Omit\n 'interactions:action-end': DoAnyPhaseArg\n 'interactions:after-action-end': DoAnyPhaseArg\n 'interactions:stop': { interaction: Interaction }\n }\n}\n\nexport type InteractionProxy = Pick<\nInteraction,\nkeyof typeof _ProxyValues | keyof typeof _ProxyMethods\n>\n\nlet idCounter = 0\n\nexport class Interaction {\n // current interactable being interacted with\n interactable: Interactable | null = null\n\n // the target element of the interactable\n element: Element | null = null\n rect: FullRect | null = null\n _rects?: {\n start: FullRect\n corrected: FullRect\n previous: FullRect\n delta: FullRect\n }\n edges: EdgeOptions | null = null\n\n _scopeFire: Scope['fire']\n\n // action that's ready to be fired on next move event\n prepared: ActionProps = {\n name: null,\n axis: null,\n edges: null,\n }\n\n pointerType: string\n\n // keep track of added pointers\n pointers: PointerInfo[] = []\n\n // pointerdown/mousedown/touchstart event\n downEvent: PointerEventType | null = null\n\n downPointer: PointerType = {} as PointerType\n\n _latestPointer: {\n pointer: PointerType\n event: PointerEventType\n eventTarget: Node\n } = {\n pointer: null,\n event: null,\n eventTarget: null,\n }\n\n // previous action event\n prevEvent: InteractEvent = null\n\n pointerIsDown = false\n pointerWasMoved = false\n _interacting = false\n _ending = false\n _stopped = true\n _proxy: InteractionProxy | null = null\n\n simulation = null\n\n /** @internal */ get pointerMoveTolerance () {\n return 1\n }\n\n /**\n * @alias Interaction.prototype.move\n */\n doMove = warnOnce(function (this: Interaction, signalArg: any) {\n this.move(signalArg)\n }, 'The interaction.doMove() method has been renamed to interaction.move()')\n\n coords: CoordsSet = {\n // Starting InteractEvent pointer coordinates\n start: pointerUtils.newCoords(),\n // Previous native pointer move event coordinates\n prev: pointerUtils.newCoords(),\n // current native pointer move event coordinates\n cur: pointerUtils.newCoords(),\n // Change in coordinates and time of the pointer\n delta: pointerUtils.newCoords(),\n // pointer velocity\n velocity: pointerUtils.newCoords(),\n }\n\n readonly _id: number = idCounter++\n\n /** */\n constructor ({ pointerType, scopeFire }: { pointerType?: string, scopeFire: Scope['fire'] }) {\n this._scopeFire = scopeFire\n this.pointerType = pointerType\n\n const that = this\n\n this._proxy = {} as InteractionProxy\n\n for (const key in _ProxyValues) {\n Object.defineProperty(this._proxy, key, {\n get () {\n return that[key]\n },\n })\n }\n\n for (const key in _ProxyMethods) {\n Object.defineProperty(this._proxy, key, {\n value: (...args: any[]) => that[key](...args),\n })\n }\n\n this._scopeFire('interactions:new', { interaction: this })\n }\n\n pointerDown (pointer: PointerType, event: PointerEventType, eventTarget: Node) {\n const pointerIndex = this.updatePointer(pointer, event, eventTarget, true)\n const pointerInfo = this.pointers[pointerIndex]\n\n this._scopeFire('interactions:down', {\n pointer,\n event,\n eventTarget,\n pointerIndex,\n pointerInfo,\n type: 'down',\n interaction: this as unknown as Interaction,\n })\n }\n\n /**\n * ```js\n * interact(target)\n * .draggable({\n * // disable the default drag start by down->move\n * manualStart: true\n * })\n * // start dragging after the user holds the pointer down\n * .on('hold', function (event) {\n * var interaction = event.interaction\n *\n * if (!interaction.interacting()) {\n * interaction.start({ name: 'drag' },\n * event.interactable,\n * event.currentTarget)\n * }\n * })\n * ```\n *\n * Start an action with the given Interactable and Element as tartgets. The\n * action must be enabled for the target Interactable and an appropriate\n * number of pointers must be held down - 1 for drag/resize, 2 for gesture.\n *\n * Use it with `interactable.able({ manualStart: false })` to always\n * [start actions manually](https://github.com/taye/interact.js/issues/114)\n *\n * @param {object} action The action to be performed - drag, resize, etc.\n * @param {Interactable} target The Interactable to target\n * @param {Element} element The DOM Element to target\n * @return {Boolean} Whether the interaction was successfully started\n */\n start (action: ActionProps, interactable: Interactable, element: Element): boolean {\n if (\n this.interacting() ||\n !this.pointerIsDown ||\n this.pointers.length < (action.name === 'gesture' ? 2 : 1) ||\n !interactable.options[action.name as keyof ActionDefaults].enabled\n ) {\n return false\n }\n\n copyAction(this.prepared, action)\n\n this.interactable = interactable\n this.element = element\n this.rect = interactable.getRect(element)\n this.edges = this.prepared.edges\n ? extend({}, this.prepared.edges)\n : { left: true, right: true, top: true, bottom: true }\n this._stopped = false\n this._interacting =\n this._doPhase({\n interaction: this,\n event: this.downEvent,\n phase: 'start',\n }) && !this._stopped\n\n return this._interacting\n }\n\n pointerMove (pointer: PointerType, event: PointerEventType, eventTarget: Node) {\n if (!this.simulation && !(this.modification && this.modification.endResult)) {\n this.updatePointer(pointer, event, eventTarget, false)\n }\n\n const duplicateMove =\n this.coords.cur.page.x === this.coords.prev.page.x &&\n this.coords.cur.page.y === this.coords.prev.page.y &&\n this.coords.cur.client.x === this.coords.prev.client.x &&\n this.coords.cur.client.y === this.coords.prev.client.y\n\n let dx: number\n let dy: number\n\n // register movement greater than pointerMoveTolerance\n if (this.pointerIsDown && !this.pointerWasMoved) {\n dx = this.coords.cur.client.x - this.coords.start.client.x\n dy = this.coords.cur.client.y - this.coords.start.client.y\n\n this.pointerWasMoved = hypot(dx, dy) > this.pointerMoveTolerance\n }\n\n const pointerIndex = this.getPointerIndex(pointer)\n const signalArg = {\n pointer,\n pointerIndex,\n pointerInfo: this.pointers[pointerIndex],\n event,\n type: 'move' as const,\n eventTarget,\n dx,\n dy,\n duplicate: duplicateMove,\n interaction: this as unknown as Interaction,\n }\n\n if (!duplicateMove) {\n // set pointer coordinate, time changes and velocity\n pointerUtils.setCoordVelocity(this.coords.velocity, this.coords.delta)\n }\n\n this._scopeFire('interactions:move', signalArg)\n\n if (!duplicateMove && !this.simulation) {\n // if interacting, fire an 'action-move' signal etc\n if (this.interacting()) {\n signalArg.type = null\n this.move(signalArg)\n }\n\n if (this.pointerWasMoved) {\n pointerUtils.copyCoords(this.coords.prev, this.coords.cur)\n }\n }\n }\n\n /**\n * ```js\n * interact(target)\n * .draggable(true)\n * .on('dragmove', function (event) {\n * if (someCondition) {\n * // change the snap settings\n * event.interactable.draggable({ snap: { targets: [] }})\n * // fire another move event with re-calculated snap\n * event.interaction.move()\n * }\n * })\n * ```\n *\n * Force a move of the current action at the same coordinates. Useful if\n * snap/restrict has been changed and you want a movement with the new\n * settings.\n */\n move (signalArg?: any) {\n if (!signalArg || !signalArg.event) {\n pointerUtils.setZeroCoords(this.coords.delta)\n }\n\n signalArg = extend(\n {\n pointer: this._latestPointer.pointer,\n event: this._latestPointer.event,\n eventTarget: this._latestPointer.eventTarget,\n interaction: this,\n },\n signalArg || {},\n )\n\n signalArg.phase = 'move'\n\n this._doPhase(signalArg)\n }\n\n // End interact move events and stop auto-scroll unless simulation is running\n pointerUp (pointer: PointerType, event: PointerEventType, eventTarget: Node, curEventTarget: EventTarget) {\n let pointerIndex = this.getPointerIndex(pointer)\n\n if (pointerIndex === -1) {\n pointerIndex = this.updatePointer(pointer, event, eventTarget, false)\n }\n\n const type = /cancel$/i.test(event.type) ? 'cancel' : 'up'\n\n this._scopeFire(`interactions:${type}` as 'interactions:up' | 'interactions:cancel', {\n pointer,\n pointerIndex,\n pointerInfo: this.pointers[pointerIndex],\n event,\n eventTarget,\n type: type as any,\n curEventTarget,\n interaction: this as unknown as Interaction,\n })\n\n if (!this.simulation) {\n this.end(event)\n }\n\n this.removePointer(pointer, event)\n }\n\n documentBlur (event: Event) {\n this.end(event as any)\n this._scopeFire('interactions:blur', {\n event,\n type: 'blur',\n interaction: this as unknown as Interaction,\n })\n }\n\n /**\n * ```js\n * interact(target)\n * .draggable(true)\n * .on('move', function (event) {\n * if (event.pageX > 1000) {\n * // end the current action\n * event.interaction.end()\n * // stop all further listeners from being called\n * event.stopImmediatePropagation()\n * }\n * })\n * ```\n *\n * @param {PointerEvent} [event]\n */\n end (event?: PointerEventType) {\n this._ending = true\n event = event || this._latestPointer.event\n let endPhaseResult: boolean\n\n if (this.interacting()) {\n endPhaseResult = this._doPhase({\n event,\n interaction: this,\n phase: 'end',\n })\n }\n\n this._ending = false\n\n if (endPhaseResult === true) {\n this.stop()\n }\n }\n\n currentAction () {\n return this._interacting ? this.prepared.name : null\n }\n\n interacting () {\n return this._interacting\n }\n\n /** */\n stop () {\n this._scopeFire('interactions:stop', { interaction: this })\n\n this.interactable = this.element = null\n\n this._interacting = false\n this._stopped = true\n this.prepared.name = this.prevEvent = null\n }\n\n getPointerIndex (pointer: any) {\n const pointerId = pointerUtils.getPointerId(pointer)\n\n // mouse and pen interactions may have only one pointer\n return this.pointerType === 'mouse' || this.pointerType === 'pen'\n ? this.pointers.length - 1\n : arr.findIndex(this.pointers, (curPointer) => curPointer.id === pointerId)\n }\n\n getPointerInfo (pointer: any) {\n return this.pointers[this.getPointerIndex(pointer)]\n }\n\n updatePointer (pointer: PointerType, event: PointerEventType, eventTarget: Node, down?: boolean) {\n const id = pointerUtils.getPointerId(pointer)\n let pointerIndex = this.getPointerIndex(pointer)\n let pointerInfo = this.pointers[pointerIndex]\n\n down = down === false ? false : down || /(down|start)$/i.test(event.type)\n\n if (!pointerInfo) {\n pointerInfo = new PointerInfo(id, pointer, event, null, null)\n\n pointerIndex = this.pointers.length\n this.pointers.push(pointerInfo)\n } else {\n pointerInfo.pointer = pointer\n }\n\n pointerUtils.setCoords(\n this.coords.cur,\n this.pointers.map((p) => p.pointer),\n this._now(),\n )\n pointerUtils.setCoordDeltas(this.coords.delta, this.coords.prev, this.coords.cur)\n\n if (down) {\n this.pointerIsDown = true\n\n pointerInfo.downTime = this.coords.cur.timeStamp\n pointerInfo.downTarget = eventTarget\n pointerUtils.pointerExtend(this.downPointer, pointer)\n\n if (!this.interacting()) {\n pointerUtils.copyCoords(this.coords.start, this.coords.cur)\n pointerUtils.copyCoords(this.coords.prev, this.coords.cur)\n\n this.downEvent = event\n this.pointerWasMoved = false\n }\n }\n\n this._updateLatestPointer(pointer, event, eventTarget)\n\n this._scopeFire('interactions:update-pointer', {\n pointer,\n event,\n eventTarget,\n down,\n pointerInfo,\n pointerIndex,\n interaction: this as unknown as Interaction,\n })\n\n return pointerIndex\n }\n\n removePointer (pointer: PointerType, event: PointerEventType) {\n const pointerIndex = this.getPointerIndex(pointer)\n\n if (pointerIndex === -1) return\n\n const pointerInfo = this.pointers[pointerIndex]\n\n this._scopeFire('interactions:remove-pointer', {\n pointer,\n event,\n eventTarget: null,\n pointerIndex,\n pointerInfo,\n interaction: this as unknown as Interaction,\n })\n\n this.pointers.splice(pointerIndex, 1)\n this.pointerIsDown = false\n }\n\n _updateLatestPointer (pointer: PointerType, event: PointerEventType, eventTarget: Node) {\n this._latestPointer.pointer = pointer\n this._latestPointer.event = event\n this._latestPointer.eventTarget = eventTarget\n }\n\n destroy () {\n this._latestPointer.pointer = null\n this._latestPointer.event = null\n this._latestPointer.eventTarget = null\n }\n\n _createPreparedEvent

(\n event: PointerEventType,\n phase: P,\n preEnd?: boolean,\n type?: string,\n ) {\n return new InteractEvent(this, event, this.prepared.name, phase, this.element, preEnd, type)\n }\n\n _fireEvent

(iEvent: InteractEvent) {\n this.interactable?.fire(iEvent)\n\n if (!this.prevEvent || iEvent.timeStamp >= this.prevEvent.timeStamp) {\n this.prevEvent = iEvent\n }\n }\n\n _doPhase

(\n signalArg: Omit, 'iEvent'> & { iEvent?: InteractEvent },\n ) {\n const { event, phase, preEnd, type } = signalArg\n const { rect } = this\n\n if (rect && phase === 'move') {\n // update the rect changes due to pointer move\n rectUtils.addEdges(this.edges, rect, this.coords.delta[this.interactable.options.deltaSource])\n\n rect.width = rect.right - rect.left\n rect.height = rect.bottom - rect.top\n }\n\n const beforeResult = this._scopeFire(`interactions:before-action-${phase}` as any, signalArg)\n\n if (beforeResult === false) {\n return false\n }\n\n const iEvent = (signalArg.iEvent = this._createPreparedEvent(event, phase, preEnd, type))\n\n this._scopeFire(`interactions:action-${phase}` as any, signalArg)\n\n if (phase === 'start') {\n this.prevEvent = iEvent\n }\n\n this._fireEvent(iEvent)\n\n this._scopeFire(`interactions:after-action-${phase}` as any, signalArg)\n\n return true\n }\n\n _now () {\n return Date.now()\n }\n}\n\nexport default Interaction\nexport { PointerInfo }\n", "import type Interaction from '@interactjs/core/Interaction'\nimport { _ProxyMethods } from '@interactjs/core/Interaction'\nimport type { Plugin } from '@interactjs/core/scope'\nimport type { Point } from '@interactjs/core/types'\nimport * as rectUtils from '@interactjs/utils/rect'\n\ndeclare module '@interactjs/core/Interaction' {\n interface Interaction {\n offsetBy?: typeof offsetBy\n offset: {\n total: Point\n pending: Point\n }\n }\n\n enum _ProxyMethods {\n offsetBy = '',\n }\n}\n\n;(_ProxyMethods as any).offsetBy = ''\n\nexport function addTotal (interaction: Interaction) {\n if (!interaction.pointerIsDown) {\n return\n }\n\n addToCoords(interaction.coords.cur, interaction.offset.total)\n\n interaction.offset.pending.x = 0\n interaction.offset.pending.y = 0\n}\n\nfunction beforeAction ({ interaction }: { interaction: Interaction }) {\n applyPending(interaction)\n}\n\nfunction beforeEnd ({ interaction }: { interaction: Interaction }): boolean | void {\n const hadPending = applyPending(interaction)\n\n if (!hadPending) return\n\n interaction.move({ offset: true })\n interaction.end()\n\n return false\n}\n\nfunction end ({ interaction }: { interaction: Interaction }) {\n interaction.offset.total.x = 0\n interaction.offset.total.y = 0\n interaction.offset.pending.x = 0\n interaction.offset.pending.y = 0\n}\n\nexport function applyPending (interaction: Interaction) {\n if (!hasPending(interaction)) {\n return false\n }\n\n const { pending } = interaction.offset\n\n addToCoords(interaction.coords.cur, pending)\n addToCoords(interaction.coords.delta, pending)\n rectUtils.addEdges(interaction.edges, interaction.rect, pending)\n\n pending.x = 0\n pending.y = 0\n\n return true\n}\n\nfunction offsetBy (this: Interaction, { x, y }: Point) {\n this.offset.pending.x += x\n this.offset.pending.y += y\n\n this.offset.total.x += x\n this.offset.total.y += y\n}\n\nfunction addToCoords ({ page, client }, { x, y }: Point) {\n page.x += x\n page.y += y\n client.x += x\n client.y += y\n}\n\nfunction hasPending (interaction: Interaction) {\n return !!(interaction.offset.pending.x || interaction.offset.pending.y)\n}\n\nconst offset: Plugin = {\n id: 'offset',\n before: ['modifiers', 'pointer-events', 'actions', 'inertia'],\n install (scope) {\n scope.Interaction.prototype.offsetBy = offsetBy\n },\n listeners: {\n 'interactions:new': ({ interaction }) => {\n interaction.offset = {\n total: { x: 0, y: 0 },\n pending: { x: 0, y: 0 },\n }\n },\n 'interactions:update-pointer': ({ interaction }) => addTotal(interaction),\n 'interactions:before-action-start': beforeAction,\n 'interactions:before-action-move': beforeAction,\n 'interactions:before-action-end': beforeEnd,\n 'interactions:stop': end,\n },\n}\n\nexport default offset\n", "import type { Interaction, DoPhaseArg } from '@interactjs/core/Interaction'\nimport type { Scope, SignalArgs, Plugin } from '@interactjs/core/scope'\nimport type { ActionName, Point, PointerEventType } from '@interactjs/core/types'\nimport Modification from '@interactjs/modifiers/Modification'\nimport * as modifiers from '@interactjs/modifiers/base'\nimport offset from '@interactjs/offset/plugin'\nimport * as dom from '@interactjs/utils/domUtils'\nimport hypot from '@interactjs/utils/hypot'\nimport is from '@interactjs/utils/is'\nimport { copyCoords } from '@interactjs/utils/pointerUtils'\nimport raf from '@interactjs/utils/raf'\n\ndeclare module '@interactjs/core/InteractEvent' {\n interface PhaseMap {\n resume?: true\n inertiastart?: true\n }\n}\n\ndeclare module '@interactjs/core/Interaction' {\n interface Interaction {\n inertia?: InertiaState\n }\n}\n\ndeclare module '@interactjs/core/options' {\n interface PerActionDefaults {\n inertia?: {\n enabled?: boolean\n resistance?: number // the lambda in exponential decay\n minSpeed?: number // target speed must be above this for inertia to start\n endSpeed?: number // the speed at which inertia is slow enough to stop\n allowResume?: true // allow resuming an action in inertia phase\n smoothEndDuration?: number // animate to snap/restrict endOnly if there's no inertia\n }\n }\n}\n\ndeclare module '@interactjs/core/scope' {\n interface SignalArgs {\n 'interactions:before-action-inertiastart': Omit, 'iEvent'>\n 'interactions:action-inertiastart': DoPhaseArg\n 'interactions:after-action-inertiastart': DoPhaseArg\n 'interactions:before-action-resume': Omit, 'iEvent'>\n 'interactions:action-resume': DoPhaseArg\n 'interactions:after-action-resume': DoPhaseArg\n }\n}\n\nfunction install (scope: Scope) {\n const { defaults } = scope\n\n scope.usePlugin(offset)\n scope.usePlugin(modifiers.default)\n scope.actions.phases.inertiastart = true\n scope.actions.phases.resume = true\n\n defaults.perAction.inertia = {\n enabled: false,\n resistance: 10, // the lambda in exponential decay\n minSpeed: 100, // target speed must be above this for inertia to start\n endSpeed: 10, // the speed at which inertia is slow enough to stop\n allowResume: true, // allow resuming an action in inertia phase\n smoothEndDuration: 300, // animate to snap/restrict endOnly if there's no inertia\n }\n}\n\nexport class InertiaState {\n active = false\n isModified = false\n smoothEnd = false\n allowResume = false\n\n modification!: Modification\n modifierCount = 0\n modifierArg!: modifiers.ModifierArg\n\n startCoords!: Point\n t0 = 0\n v0 = 0\n\n te = 0\n targetOffset!: Point\n modifiedOffset!: Point\n currentOffset!: Point\n\n lambda_v0? = 0 // eslint-disable-line camelcase\n one_ve_v0? = 0 // eslint-disable-line camelcase\n timeout!: number\n readonly interaction: Interaction\n\n constructor (interaction: Interaction) {\n this.interaction = interaction\n }\n\n start (event: PointerEventType) {\n const { interaction } = this\n const options = getOptions(interaction)\n\n if (!options || !options.enabled) {\n return false\n }\n\n const { client: velocityClient } = interaction.coords.velocity\n const pointerSpeed = hypot(velocityClient.x, velocityClient.y)\n const modification = this.modification || (this.modification = new Modification(interaction))\n\n modification.copyFrom(interaction.modification)\n\n this.t0 = interaction._now()\n this.allowResume = options.allowResume\n this.v0 = pointerSpeed\n this.currentOffset = { x: 0, y: 0 }\n this.startCoords = interaction.coords.cur.page\n\n this.modifierArg = modification.fillArg({\n pageCoords: this.startCoords,\n preEnd: true,\n phase: 'inertiastart',\n })\n\n const thrown =\n this.t0 - interaction.coords.cur.timeStamp < 50 &&\n pointerSpeed > options.minSpeed &&\n pointerSpeed > options.endSpeed\n\n if (thrown) {\n this.startInertia()\n } else {\n modification.result = modification.setAll(this.modifierArg)\n\n if (!modification.result.changed) {\n return false\n }\n\n this.startSmoothEnd()\n }\n\n // force modification change\n interaction.modification.result.rect = null\n\n // bring inertiastart event to the target coords\n interaction.offsetBy(this.targetOffset)\n interaction._doPhase({\n interaction,\n event,\n phase: 'inertiastart',\n })\n interaction.offsetBy({ x: -this.targetOffset.x, y: -this.targetOffset.y })\n // force modification change\n interaction.modification.result.rect = null\n\n this.active = true\n interaction.simulation = this\n\n return true\n }\n\n startInertia () {\n const startVelocity = this.interaction.coords.velocity.client\n const options = getOptions(this.interaction)\n const lambda = options.resistance\n const inertiaDur = -Math.log(options.endSpeed / this.v0) / lambda\n\n this.targetOffset = {\n x: (startVelocity.x - inertiaDur) / lambda,\n y: (startVelocity.y - inertiaDur) / lambda,\n }\n\n this.te = inertiaDur\n this.lambda_v0 = lambda / this.v0\n this.one_ve_v0 = 1 - options.endSpeed / this.v0\n\n const { modification, modifierArg } = this\n\n modifierArg.pageCoords = {\n x: this.startCoords.x + this.targetOffset.x,\n y: this.startCoords.y + this.targetOffset.y,\n }\n\n modification.result = modification.setAll(modifierArg)\n\n if (modification.result.changed) {\n this.isModified = true\n this.modifiedOffset = {\n x: this.targetOffset.x + modification.result.delta.x,\n y: this.targetOffset.y + modification.result.delta.y,\n }\n }\n\n this.onNextFrame(() => this.inertiaTick())\n }\n\n startSmoothEnd () {\n this.smoothEnd = true\n this.isModified = true\n this.targetOffset = {\n x: this.modification.result.delta.x,\n y: this.modification.result.delta.y,\n }\n\n this.onNextFrame(() => this.smoothEndTick())\n }\n\n onNextFrame (tickFn: () => void) {\n this.timeout = raf.request(() => {\n if (this.active) {\n tickFn()\n }\n })\n }\n\n inertiaTick () {\n const { interaction } = this\n const options = getOptions(interaction)\n const lambda = options.resistance\n const t = (interaction._now() - this.t0) / 1000\n\n if (t < this.te) {\n const progress = 1 - (Math.exp(-lambda * t) - this.lambda_v0) / this.one_ve_v0\n let newOffset: Point\n\n if (this.isModified) {\n newOffset = getQuadraticCurvePoint(\n 0,\n 0,\n this.targetOffset.x,\n this.targetOffset.y,\n this.modifiedOffset.x,\n this.modifiedOffset.y,\n progress,\n )\n } else {\n newOffset = {\n x: this.targetOffset.x * progress,\n y: this.targetOffset.y * progress,\n }\n }\n\n const delta = { x: newOffset.x - this.currentOffset.x, y: newOffset.y - this.currentOffset.y }\n\n this.currentOffset.x += delta.x\n this.currentOffset.y += delta.y\n\n interaction.offsetBy(delta)\n interaction.move()\n\n this.onNextFrame(() => this.inertiaTick())\n } else {\n interaction.offsetBy({\n x: this.modifiedOffset.x - this.currentOffset.x,\n y: this.modifiedOffset.y - this.currentOffset.y,\n })\n\n this.end()\n }\n }\n\n smoothEndTick () {\n const { interaction } = this\n const t = interaction._now() - this.t0\n const { smoothEndDuration: duration } = getOptions(interaction)\n\n if (t < duration) {\n const newOffset = {\n x: easeOutQuad(t, 0, this.targetOffset.x, duration),\n y: easeOutQuad(t, 0, this.targetOffset.y, duration),\n }\n const delta = {\n x: newOffset.x - this.currentOffset.x,\n y: newOffset.y - this.currentOffset.y,\n }\n\n this.currentOffset.x += delta.x\n this.currentOffset.y += delta.y\n\n interaction.offsetBy(delta)\n interaction.move({ skipModifiers: this.modifierCount })\n\n this.onNextFrame(() => this.smoothEndTick())\n } else {\n interaction.offsetBy({\n x: this.targetOffset.x - this.currentOffset.x,\n y: this.targetOffset.y - this.currentOffset.y,\n })\n\n this.end()\n }\n }\n\n resume ({ pointer, event, eventTarget }: SignalArgs['interactions:down']) {\n const { interaction } = this\n\n // undo inertia changes to interaction coords\n interaction.offsetBy({\n x: -this.currentOffset.x,\n y: -this.currentOffset.y,\n })\n\n // update pointer at pointer down position\n interaction.updatePointer(pointer, event, eventTarget, true)\n\n // fire resume signals and event\n interaction._doPhase({\n interaction,\n event,\n phase: 'resume',\n })\n copyCoords(interaction.coords.prev, interaction.coords.cur)\n\n this.stop()\n }\n\n end () {\n this.interaction.move()\n this.interaction.end()\n this.stop()\n }\n\n stop () {\n this.active = this.smoothEnd = false\n this.interaction.simulation = null\n raf.cancel(this.timeout)\n }\n}\n\nfunction start ({ interaction, event }: DoPhaseArg) {\n if (!interaction._interacting || interaction.simulation) {\n return null\n }\n\n const started = interaction.inertia.start(event)\n\n // prevent action end if inertia or smoothEnd\n return started ? false : null\n}\n\n// Check if the down event hits the current inertia target\n// control should be return to the user\nfunction resume (arg: SignalArgs['interactions:down']) {\n const { interaction, eventTarget } = arg\n const state = interaction.inertia\n\n if (!state.active) return\n\n let element = eventTarget as Node\n\n // climb up the DOM tree from the event target\n while (is.element(element)) {\n // if interaction element is the current inertia target element\n if (element === interaction.element) {\n state.resume(arg)\n break\n }\n\n element = dom.parentNode(element)\n }\n}\n\nfunction stop ({ interaction }: { interaction: Interaction }) {\n const state = interaction.inertia\n\n if (state.active) {\n state.stop()\n }\n}\n\nfunction getOptions ({ interactable, prepared }: Interaction) {\n return interactable && interactable.options && prepared.name && interactable.options[prepared.name].inertia\n}\n\nconst inertia: Plugin = {\n id: 'inertia',\n before: ['modifiers', 'actions'],\n install,\n listeners: {\n 'interactions:new': ({ interaction }) => {\n interaction.inertia = new InertiaState(interaction)\n },\n\n 'interactions:before-action-end': start,\n 'interactions:down': resume,\n 'interactions:stop': stop,\n\n 'interactions:before-action-resume': (arg) => {\n const { modification } = arg.interaction\n\n modification.stop(arg)\n modification.start(arg, arg.interaction.coords.cur.page)\n modification.applyToInteraction(arg)\n },\n\n 'interactions:before-action-inertiastart': (arg) => arg.interaction.modification.setAndApply(arg),\n 'interactions:action-resume': modifiers.addEventModifiers,\n 'interactions:action-inertiastart': modifiers.addEventModifiers,\n 'interactions:after-action-inertiastart': (arg) =>\n arg.interaction.modification.restoreInteractionCoords(arg),\n 'interactions:after-action-resume': (arg) => arg.interaction.modification.restoreInteractionCoords(arg),\n },\n}\n\n// http://stackoverflow.com/a/5634528/2280888\nfunction _getQBezierValue (t: number, p1: number, p2: number, p3: number) {\n const iT = 1 - t\n return iT * iT * p1 + 2 * iT * t * p2 + t * t * p3\n}\n\nfunction getQuadraticCurvePoint (\n startX: number,\n startY: number,\n cpX: number,\n cpY: number,\n endX: number,\n endY: number,\n position: number,\n) {\n return {\n x: _getQBezierValue(position, startX, cpX, endX),\n y: _getQBezierValue(position, startY, cpY, endY),\n }\n}\n\n// http://gizma.com/easing/\nfunction easeOutQuad (t: number, b: number, c: number, d: number) {\n t /= d\n return -c * t * (t - 2) + b\n}\n\nexport default inertia\n", "import type { Listener, ListenersArg, Rect } from '@interactjs/core/types'\nimport * as arr from '@interactjs/utils/arr'\nimport extend from '@interactjs/utils/extend'\nimport type { NormalizedListeners } from '@interactjs/utils/normalizeListeners'\nimport normalize from '@interactjs/utils/normalizeListeners'\n\nfunction fireUntilImmediateStopped (event: any, listeners: Listener[]) {\n for (const listener of listeners) {\n if (event.immediatePropagationStopped) {\n break\n }\n\n listener(event)\n }\n}\n\nexport class Eventable {\n options: any\n types: NormalizedListeners = {}\n propagationStopped = false\n immediatePropagationStopped = false\n global: any\n\n constructor (options?: { [index: string]: any }) {\n this.options = extend({}, options || {})\n }\n\n fire (event: T) {\n let listeners: Listener[]\n const global = this.global\n\n // Interactable#on() listeners\n // tslint:disable no-conditional-assignment\n if ((listeners = this.types[event.type])) {\n fireUntilImmediateStopped(event, listeners)\n }\n\n // interact.on() listeners\n if (!event.propagationStopped && global && (listeners = global[event.type])) {\n fireUntilImmediateStopped(event, listeners)\n }\n }\n\n on (type: string, listener: ListenersArg) {\n const listeners = normalize(type, listener)\n\n for (type in listeners) {\n this.types[type] = arr.merge(this.types[type] || [], listeners[type])\n }\n }\n\n off (type: string, listener: ListenersArg) {\n const listeners = normalize(type, listener)\n\n for (type in listeners) {\n const eventList = this.types[type]\n\n if (!eventList || !eventList.length) {\n continue\n }\n\n for (const subListener of listeners[type]) {\n const index = eventList.indexOf(subListener)\n\n if (index !== -1) {\n eventList.splice(index, 1)\n }\n }\n }\n }\n\n getRect (_element: Element): Rect {\n return null\n }\n}\n", "import type { Actions } from '@interactjs/core/types'\n\nexport default function isNonNativeEvent (type: string, actions: Actions) {\n if (actions.phaselessTypes[type]) {\n return true\n }\n\n for (const name in actions.map) {\n if (type.indexOf(name) === 0 && type.substr(name.length) in actions.phases) {\n return true\n }\n }\n\n return false\n}\n", "/** @module interact */\nimport type { Scope, Plugin } from '@interactjs/core/scope'\nimport type { Context, EventTypes, Listener, ListenersArg, Target } from '@interactjs/core/types'\nimport browser from '@interactjs/utils/browser'\nimport * as domUtils from '@interactjs/utils/domUtils'\nimport is from '@interactjs/utils/is'\nimport { warnOnce } from '@interactjs/utils/misc'\nimport * as pointerUtils from '@interactjs/utils/pointerUtils'\n\nimport type { Interactable } from './Interactable'\nimport isNonNativeEvent from './isNonNativeEvent'\nimport type { Options } from './options'\n\ndeclare module '@interactjs/core/InteractStatic' {\n export interface InteractStatic {\n (target: Target, options?: Options): Interactable\n getPointerAverage: typeof pointerUtils.pointerAverage\n getTouchBBox: typeof pointerUtils.touchBBox\n getTouchDistance: typeof pointerUtils.touchDistance\n getTouchAngle: typeof pointerUtils.touchAngle\n getElementRect: typeof domUtils.getElementRect\n getElementClientRect: typeof domUtils.getElementClientRect\n matchesSelector: typeof domUtils.matchesSelector\n closest: typeof domUtils.closest\n /** @internal */ globalEvents: any\n version: string\n /** @internal */ scope: Scope\n use(\n plugin: Plugin,\n options?: {\n [key: string]: any\n },\n ): any\n isSet(target: Target, options?: any): boolean\n on(type: string | EventTypes, listener: ListenersArg, options?: object): any\n off(type: EventTypes, listener: any, options?: object): any\n debug(): any\n supportsTouch(): boolean\n supportsPointerEvent(): boolean\n stop(): any\n pointerMoveTolerance(newValue?: number): any\n addDocument(doc: Document, options?: object): void\n removeDocument(doc: Document): void\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-imports\ntype _InteractStatic = import('@interactjs/core/InteractStatic').InteractStatic\n\nexport function createInteractStatic (scope: Scope): _InteractStatic {\n /**\n * ```js\n * interact('#draggable').draggable(true)\n *\n * var rectables = interact('rect')\n * rectables\n * .gesturable(true)\n * .on('gesturemove', function (event) {\n * // ...\n * })\n * ```\n *\n * The methods of this variable can be used to set elements as interactables\n * and also to change various default settings.\n *\n * Calling it as a function and passing an element or a valid CSS selector\n * string returns an Interactable object which has various methods to configure\n * it.\n *\n * @global\n *\n * @param {Element | string} target The HTML or SVG Element to interact with\n * or CSS selector\n * @return {Interactable}\n */\n const interact = ((target: Target, options: Options) => {\n let interactable = scope.interactables.get(target, options)\n\n if (!interactable) {\n interactable = scope.interactables.new(target, options)\n interactable.events.global = interact.globalEvents\n }\n\n return interactable\n }) as _InteractStatic\n\n // expose the functions used to calculate multi-touch properties\n interact.getPointerAverage = pointerUtils.pointerAverage\n interact.getTouchBBox = pointerUtils.touchBBox\n interact.getTouchDistance = pointerUtils.touchDistance\n interact.getTouchAngle = pointerUtils.touchAngle\n\n interact.getElementRect = domUtils.getElementRect\n interact.getElementClientRect = domUtils.getElementClientRect\n interact.matchesSelector = domUtils.matchesSelector\n interact.closest = domUtils.closest\n\n interact.globalEvents = {} as any\n\n // eslint-disable-next-line no-undef\n interact.version = process.env.npm_package_version\n interact.scope = scope\n /**\n * Use a plugin\n *\n * @alias module:interact.use\n *\n */\n interact.use = function (plugin, options) {\n this.scope.usePlugin(plugin, options)\n\n return this\n }\n\n /**\n * Check if an element or selector has been set with the {@link interact}\n * function\n *\n * @alias module:interact.isSet\n *\n * @param {Target} target The Element or string being searched for\n * @param {object} options\n * @return {boolean} Indicates if the element or CSS selector was previously\n * passed to interact\n */\n interact.isSet = function (target: Target, options?: { context?: Context }): boolean {\n return !!this.scope.interactables.get(target, options && options.context)\n }\n\n /**\n * @deprecated\n * Add a global listener for an InteractEvent or adds a DOM event to `document`\n *\n * @alias module:interact.on\n *\n * @param {string | array | object} type The types of events to listen for\n * @param {function} listener The function event (s)\n * @param {object | boolean} [options] object or useCapture flag for\n * addEventListener\n * @return {object} interact\n */\n interact.on = warnOnce(function on (type: string | EventTypes, listener: ListenersArg, options?: object) {\n if (is.string(type) && type.search(' ') !== -1) {\n type = type.trim().split(/ +/)\n }\n\n if (is.array(type)) {\n for (const eventType of type as any[]) {\n this.on(eventType, listener, options)\n }\n\n return this\n }\n\n if (is.object(type)) {\n for (const prop in type) {\n this.on(prop, (type as any)[prop], listener)\n }\n\n return this\n }\n\n // if it is an InteractEvent type, add listener to globalEvents\n if (isNonNativeEvent(type, this.scope.actions)) {\n // if this type of event was never bound\n if (!this.globalEvents[type]) {\n this.globalEvents[type] = [listener]\n } else {\n this.globalEvents[type].push(listener)\n }\n }\n // If non InteractEvent type, addEventListener to document\n else {\n this.scope.events.add(this.scope.document, type, listener as Listener, { options })\n }\n\n return this\n }, 'The interact.on() method is being deprecated')\n\n /**\n * @deprecated\n * Removes a global InteractEvent listener or DOM event from `document`\n *\n * @alias module:interact.off\n *\n * @param {string | array | object} type The types of events that were listened\n * for\n * @param {function} listener The listener function to be removed\n * @param {object | boolean} options [options] object or useCapture flag for\n * removeEventListener\n * @return {object} interact\n */\n interact.off = warnOnce(function off (type: EventTypes, listener: any, options?: object) {\n if (is.string(type) && type.search(' ') !== -1) {\n type = type.trim().split(/ +/)\n }\n\n if (is.array(type)) {\n for (const eventType of type) {\n this.off(eventType, listener, options)\n }\n\n return this\n }\n\n if (is.object(type)) {\n for (const prop in type) {\n this.off(prop, type[prop], listener)\n }\n\n return this\n }\n\n if (isNonNativeEvent(type, this.scope.actions)) {\n let index: number\n\n if (type in this.globalEvents && (index = this.globalEvents[type].indexOf(listener)) !== -1) {\n this.globalEvents[type].splice(index, 1)\n }\n } else {\n this.scope.events.remove(this.scope.document, type, listener, options)\n }\n\n return this\n }, 'The interact.off() method is being deprecated')\n\n interact.debug = function () {\n return this.scope\n }\n\n /**\n * @alias module:interact.supportsTouch\n *\n * @return {boolean} Whether or not the browser supports touch input\n */\n interact.supportsTouch = function () {\n return browser.supportsTouch\n }\n\n /**\n * @alias module:interact.supportsPointerEvent\n *\n * @return {boolean} Whether or not the browser supports PointerEvents\n */\n interact.supportsPointerEvent = function () {\n return browser.supportsPointerEvent\n }\n\n /**\n * Cancels all interactions (end events are not fired)\n *\n * @alias module:interact.stop\n *\n * @return {object} interact\n */\n interact.stop = function () {\n for (const interaction of this.scope.interactions.list) {\n interaction.stop()\n }\n\n return this\n }\n\n /**\n * Returns or sets the distance the pointer must be moved before an action\n * sequence occurs. This also affects tolerance for tap events.\n *\n * @alias module:interact.pointerMoveTolerance\n *\n * @param {number} [newValue] The movement from the start position must be greater than this value\n * @return {interact | number}\n */\n interact.pointerMoveTolerance = function (newValue?: number) {\n if (is.number(newValue)) {\n this.scope.interactions.pointerMoveTolerance = newValue\n\n return this\n }\n\n return this.scope.interactions.pointerMoveTolerance\n }\n\n interact.addDocument = function (doc: Document, options?: object) {\n this.scope.addDocument(doc, options)\n }\n\n interact.removeDocument = function (doc: Document) {\n this.scope.removeDocument(doc)\n }\n\n return interact\n}\n", "/* eslint-disable no-dupe-class-members */\nimport type { Scope } from '@interactjs/core/scope'\nimport type {\n ActionMap,\n ActionMethod,\n ActionName,\n Actions,\n Context,\n Element,\n EventTypes,\n Listeners,\n ListenersArg,\n OrBoolean,\n Target,\n} from '@interactjs/core/types'\nimport * as arr from '@interactjs/utils/arr'\nimport browser from '@interactjs/utils/browser'\nimport clone from '@interactjs/utils/clone'\nimport { getElementRect, matchesUpTo, nodeContains, trySelector } from '@interactjs/utils/domUtils'\nimport extend from '@interactjs/utils/extend'\nimport is from '@interactjs/utils/is'\nimport normalizeListeners from '@interactjs/utils/normalizeListeners'\nimport { getWindow } from '@interactjs/utils/window'\n\nimport { Eventable } from './Eventable'\nimport isNonNativeEvent from './isNonNativeEvent'\nimport type { ActionDefaults, Defaults, OptionsArg, PerActionDefaults, Options } from './options'\n\ntype IgnoreValue = string | Element | boolean\ntype DeltaSource = 'page' | 'client'\n\n/** */\nexport class Interactable implements Partial {\n /** @internal */ get _defaults (): Defaults {\n return {\n base: {},\n perAction: {},\n actions: {} as ActionDefaults,\n }\n }\n\n readonly options!: Required\n readonly _actions: Actions\n readonly target: Target\n readonly events = new Eventable()\n readonly _context: Context\n readonly _win: Window\n readonly _doc: Document\n readonly _scopeEvents: Scope['events']\n\n /** @internal */ _rectChecker?: typeof Interactable.prototype.getRect\n\n /** */\n constructor (\n target: Target,\n options: any,\n defaultContext: Document | Element,\n scopeEvents: Scope['events'],\n ) {\n this._actions = options.actions\n this.target = target\n this._context = options.context || defaultContext\n this._win = getWindow(trySelector(target) ? this._context : target)\n this._doc = this._win.document\n this._scopeEvents = scopeEvents\n\n this.set(options)\n }\n\n setOnEvents (actionName: ActionName, phases: NonNullable) {\n if (is.func(phases.onstart)) {\n this.on(`${actionName}start`, phases.onstart)\n }\n if (is.func(phases.onmove)) {\n this.on(`${actionName}move`, phases.onmove)\n }\n if (is.func(phases.onend)) {\n this.on(`${actionName}end`, phases.onend)\n }\n if (is.func(phases.oninertiastart)) {\n this.on(`${actionName}inertiastart`, phases.oninertiastart)\n }\n\n return this\n }\n\n updatePerActionListeners (actionName: ActionName, prev: Listeners, cur: Listeners) {\n if (is.array(prev) || is.object(prev)) {\n this.off(actionName, prev)\n }\n\n if (is.array(cur) || is.object(cur)) {\n this.on(actionName, cur)\n }\n }\n\n setPerAction (actionName: ActionName, options: OrBoolean) {\n const defaults = this._defaults\n\n // for all the default per-action options\n for (const optionName_ in options) {\n const optionName = optionName_ as keyof PerActionDefaults\n const actionOptions = this.options[actionName]\n const optionValue: any = options[optionName]\n\n // remove old event listeners and add new ones\n if (optionName === 'listeners') {\n this.updatePerActionListeners(actionName, actionOptions.listeners, optionValue as Listeners)\n }\n\n // if the option value is an array\n if (is.array(optionValue)) {\n ;(actionOptions[optionName] as any) = arr.from(optionValue)\n }\n // if the option value is an object\n else if (is.plainObject(optionValue)) {\n // copy the object\n ;(actionOptions[optionName] as any) = extend(\n actionOptions[optionName] || ({} as any),\n clone(optionValue),\n )\n\n // set anabled field to true if it exists in the defaults\n if (\n is.object(defaults.perAction[optionName]) &&\n 'enabled' in (defaults.perAction[optionName] as any)\n ) {\n ;(actionOptions[optionName] as any).enabled = optionValue.enabled !== false\n }\n }\n // if the option value is a boolean and the default is an object\n else if (is.bool(optionValue) && is.object(defaults.perAction[optionName])) {\n ;(actionOptions[optionName] as any).enabled = optionValue\n }\n // if it's anything else, do a plain assignment\n else {\n ;(actionOptions[optionName] as any) = optionValue\n }\n }\n }\n\n /**\n * The default function to get an Interactables bounding rect. Can be\n * overridden using {@link Interactable.rectChecker}.\n *\n * @param {Element} [element] The element to measure.\n * @return {Rect} The object's bounding rectangle.\n */\n getRect (element: Element) {\n element = element || (is.element(this.target) ? this.target : null)\n\n if (is.string(this.target)) {\n element = element || this._context.querySelector(this.target)\n }\n\n return getElementRect(element)\n }\n\n /**\n * Returns or sets the function used to calculate the interactable's\n * element's rectangle\n *\n * @param {function} [checker] A function which returns this Interactable's\n * bounding rectangle. See {@link Interactable.getRect}\n * @return {function | object} The checker function or this Interactable\n */\n rectChecker(): (element: Element) => any | null\n rectChecker(checker: (element: Element) => any): this\n rectChecker (checker?: (element: Element) => any) {\n if (is.func(checker)) {\n this._rectChecker = checker\n\n this.getRect = (element) => {\n const rect = extend({}, this._rectChecker(element))\n\n if (!(('width' in rect) as unknown)) {\n rect.width = rect.right - rect.left\n rect.height = rect.bottom - rect.top\n }\n\n return rect\n }\n\n return this\n }\n\n if (checker === null) {\n delete this.getRect\n delete this._rectChecker\n\n return this\n }\n\n return this.getRect\n }\n\n _backCompatOption (optionName: keyof Options, newValue: any) {\n if (trySelector(newValue) || is.object(newValue)) {\n ;(this.options[optionName] as any) = newValue\n\n for (const action in this._actions.map) {\n ;(this.options[action as keyof ActionMap] as any)[optionName] = newValue\n }\n\n return this\n }\n\n return this.options[optionName]\n }\n\n /**\n * Gets or sets the origin of the Interactable's element. The x and y\n * of the origin will be subtracted from action event coordinates.\n *\n * @param {Element | object | string} [origin] An HTML or SVG Element whose\n * rect will be used, an object eg. { x: 0, y: 0 } or string 'parent', 'self'\n * or any CSS selector\n *\n * @return {object} The current origin or this Interactable\n */\n origin (newValue: any) {\n return this._backCompatOption('origin', newValue)\n }\n\n /**\n * Returns or sets the mouse coordinate types used to calculate the\n * movement of the pointer.\n *\n * @param {string} [newValue] Use 'client' if you will be scrolling while\n * interacting; Use 'page' if you want autoScroll to work\n * @return {string | object} The current deltaSource or this Interactable\n */\n deltaSource(): DeltaSource\n deltaSource(newValue: DeltaSource): this\n deltaSource (newValue?: DeltaSource) {\n if (newValue === 'page' || newValue === 'client') {\n this.options.deltaSource = newValue\n\n return this\n }\n\n return this.options.deltaSource\n }\n\n /**\n * Gets the selector context Node of the Interactable. The default is\n * `window.document`.\n *\n * @return {Node} The context Node of this Interactable\n */\n context () {\n return this._context\n }\n\n inContext (element: Document | Node) {\n return this._context === element.ownerDocument || nodeContains(this._context, element)\n }\n\n testIgnoreAllow (\n this: Interactable,\n options: { ignoreFrom?: IgnoreValue, allowFrom?: IgnoreValue },\n targetNode: Node,\n eventTarget: Node,\n ) {\n return (\n !this.testIgnore(options.ignoreFrom, targetNode, eventTarget) &&\n this.testAllow(options.allowFrom, targetNode, eventTarget)\n )\n }\n\n testAllow (this: Interactable, allowFrom: IgnoreValue, targetNode: Node, element: Node) {\n if (!allowFrom) {\n return true\n }\n\n if (!is.element(element)) {\n return false\n }\n\n if (is.string(allowFrom)) {\n return matchesUpTo(element, allowFrom, targetNode)\n } else if (is.element(allowFrom)) {\n return nodeContains(allowFrom, element)\n }\n\n return false\n }\n\n testIgnore (this: Interactable, ignoreFrom: IgnoreValue, targetNode: Node, element: Node) {\n if (!ignoreFrom || !is.element(element)) {\n return false\n }\n\n if (is.string(ignoreFrom)) {\n return matchesUpTo(element, ignoreFrom, targetNode)\n } else if (is.element(ignoreFrom)) {\n return nodeContains(ignoreFrom, element)\n }\n\n return false\n }\n\n /**\n * Calls listeners for the given InteractEvent type bound globally\n * and directly to this Interactable\n *\n * @param {InteractEvent} iEvent The InteractEvent object to be fired on this\n * Interactable\n * @return {Interactable} this Interactable\n */\n fire (iEvent: E) {\n this.events.fire(iEvent)\n\n return this\n }\n\n _onOff (method: 'on' | 'off', typeArg: EventTypes, listenerArg?: ListenersArg | null, options?: any) {\n if (is.object(typeArg) && !is.array(typeArg)) {\n options = listenerArg\n listenerArg = null\n }\n\n const addRemove = method === 'on' ? 'add' : 'remove'\n const listeners = normalizeListeners(typeArg, listenerArg)\n\n for (let type in listeners) {\n if (type === 'wheel') {\n type = browser.wheelEvent\n }\n\n for (const listener of listeners[type]) {\n // if it is an action event type\n if (isNonNativeEvent(type, this._actions)) {\n this.events[method](type, listener)\n }\n // delegated event\n else if (is.string(this.target)) {\n this._scopeEvents[`${addRemove}Delegate` as 'addDelegate' | 'removeDelegate'](\n this.target,\n this._context,\n type,\n listener,\n options,\n )\n }\n // remove listener from this Interactable's element\n else {\n this._scopeEvents[addRemove](this.target, type, listener, options)\n }\n }\n }\n\n return this\n }\n\n /**\n * Binds a listener for an InteractEvent, pointerEvent or DOM event.\n *\n * @param {string | array | object} types The types of events to listen\n * for\n * @param {function | array | object} [listener] The event listener function(s)\n * @param {object | boolean} [options] options object or useCapture flag for\n * addEventListener\n * @return {Interactable} This Interactable\n */\n on (types: EventTypes, listener?: ListenersArg, options?: any) {\n return this._onOff('on', types, listener, options)\n }\n\n /**\n * Removes an InteractEvent, pointerEvent or DOM event listener.\n *\n * @param {string | array | object} types The types of events that were\n * listened for\n * @param {function | array | object} [listener] The event listener function(s)\n * @param {object | boolean} [options] options object or useCapture flag for\n * removeEventListener\n * @return {Interactable} This Interactable\n */\n off (types: string | string[] | EventTypes, listener?: ListenersArg, options?: any) {\n return this._onOff('off', types, listener, options)\n }\n\n /**\n * Reset the options of this Interactable\n *\n * @param {object} options The new settings to apply\n * @return {object} This Interactable\n */\n set (options: OptionsArg) {\n const defaults = this._defaults\n\n if (!is.object(options)) {\n options = {}\n }\n\n ;(this.options as Required) = clone(defaults.base) as Required\n\n for (const actionName_ in this._actions.methodDict) {\n const actionName = actionName_ as ActionName\n const methodName = this._actions.methodDict[actionName]\n\n this.options[actionName] = {}\n this.setPerAction(actionName, extend(extend({}, defaults.perAction), defaults.actions[actionName]))\n ;(this[methodName] as ActionMethod)(options[actionName])\n }\n\n for (const setting in options) {\n if (is.func((this as any)[setting])) {\n ;(this as any)[setting](options[setting as keyof typeof options])\n }\n }\n\n return this\n }\n\n /**\n * Remove this interactable from the list of interactables and remove it's\n * action capabilities and event listeners\n */\n unset () {\n if (is.string(this.target)) {\n // remove delegated events\n for (const type in this._scopeEvents.delegatedEvents) {\n const delegated = this._scopeEvents.delegatedEvents[type]\n\n for (let i = delegated.length - 1; i >= 0; i--) {\n const { selector, context, listeners } = delegated[i]\n\n if (selector === this.target && context === this._context) {\n delegated.splice(i, 1)\n }\n\n for (let l = listeners.length - 1; l >= 0; l--) {\n this._scopeEvents.removeDelegate(\n this.target,\n this._context,\n type,\n listeners[l][0],\n listeners[l][1],\n )\n }\n }\n }\n } else {\n this._scopeEvents.remove(this.target as Node, 'all')\n }\n }\n}\n", "import type { Interactable } from '@interactjs/core/Interactable'\nimport type { OptionsArg, Options } from '@interactjs/core/options'\nimport type { Scope } from '@interactjs/core/scope'\nimport type { Target, Context } from '@interactjs/core/types'\nimport * as arr from '@interactjs/utils/arr'\nimport * as domUtils from '@interactjs/utils/domUtils'\nimport extend from '@interactjs/utils/extend'\nimport is from '@interactjs/utils/is'\n\ndeclare module '@interactjs/core/scope' {\n interface SignalArgs {\n 'interactable:new': {\n interactable: Interactable\n target: Target\n options: OptionsArg\n win: Window\n }\n }\n}\n\ninterface InteractableScopeProp {\n context: Context\n interactable: Interactable\n}\n\nexport class InteractableSet {\n // all set interactables\n list: Interactable[] = []\n\n selectorMap: {\n [selector: string]: InteractableScopeProp[]\n } = {}\n\n scope: Scope\n\n constructor (scope: Scope) {\n this.scope = scope\n scope.addListeners({\n 'interactable:unset': ({ interactable }) => {\n const { target, _context: context } = interactable\n const targetMappings: InteractableScopeProp[] = is.string(target)\n ? this.selectorMap[target]\n : (target as any)[this.scope.id]\n\n const targetIndex = arr.findIndex(targetMappings, (m) => m.context === context)\n if (targetMappings[targetIndex]) {\n // Destroying mappingInfo's context and interactable\n targetMappings[targetIndex].context = null\n targetMappings[targetIndex].interactable = null\n }\n targetMappings.splice(targetIndex, 1)\n },\n })\n }\n\n new (target: Target, options?: any): Interactable {\n options = extend(options || {}, {\n actions: this.scope.actions,\n })\n const interactable = new this.scope.Interactable(target, options, this.scope.document, this.scope.events)\n const mappingInfo = { context: interactable._context, interactable }\n\n this.scope.addDocument(interactable._doc)\n this.list.push(interactable)\n\n if (is.string(target)) {\n if (!this.selectorMap[target]) {\n this.selectorMap[target] = []\n }\n this.selectorMap[target].push(mappingInfo)\n } else {\n if (!(interactable.target as any)[this.scope.id]) {\n Object.defineProperty(target, this.scope.id, {\n value: [],\n configurable: true,\n })\n }\n\n ;(target as any)[this.scope.id].push(mappingInfo)\n }\n\n this.scope.fire('interactable:new', {\n target,\n options,\n interactable,\n win: this.scope._win,\n })\n\n return interactable\n }\n\n get (target: Target, options?: Options) {\n const context = (options && options.context) || this.scope.document\n const isSelector = is.string(target)\n const targetMappings: InteractableScopeProp[] = isSelector\n ? this.selectorMap[target as string]\n : (target as any)[this.scope.id]\n\n if (!targetMappings) {\n return null\n }\n\n const found = arr.find(\n targetMappings,\n (m) => m.context === context && (isSelector || m.interactable.inContext(target as any)),\n )\n\n return found && found.interactable\n }\n\n forEachMatch (node: Node, callback: (interactable: Interactable) => T) {\n for (const interactable of this.list) {\n let ret: void | T\n\n if (\n (is.string(interactable.target)\n ? // target is a selector and the element matches\n is.element(node) && domUtils.matchesSelector(node, interactable.target)\n : // target is the element\n node === interactable.target) &&\n // the element is in context\n interactable.inContext(node)\n ) {\n ret = callback(interactable)\n }\n\n if (ret !== undefined) {\n return ret\n }\n }\n }\n}\n", "import type { Scope } from '@interactjs/core/scope'\nimport type { Element } from '@interactjs/core/types'\nimport * as arr from '@interactjs/utils/arr'\nimport * as domUtils from '@interactjs/utils/domUtils'\nimport extend from '@interactjs/utils/extend'\nimport is from '@interactjs/utils/is'\nimport pExtend from '@interactjs/utils/pointerExtend'\nimport * as pointerUtils from '@interactjs/utils/pointerUtils'\n\ndeclare module '@interactjs/core/scope' {\n interface Scope {\n events: ReturnType\n }\n}\n\ntype Listener = (event: Event | FakeEvent) => any\n\nfunction install (scope: Scope) {\n const targets: Array<{\n eventTarget: EventTarget\n events: { [type: string]: Listener[] }\n }> = []\n\n const delegatedEvents: {\n [type: string]: Array<{\n selector: string\n context: Node\n listeners: Array<[Listener, { capture: boolean, passive: boolean }]>\n }>\n } = {}\n const documents: Document[] = []\n\n const eventsMethods = {\n add,\n remove,\n\n addDelegate,\n removeDelegate,\n\n delegateListener,\n delegateUseCapture,\n delegatedEvents,\n documents,\n\n targets,\n\n supportsOptions: false,\n supportsPassive: false,\n }\n\n // check if browser supports passive events and options arg\n scope.document?.createElement('div').addEventListener('test', null, {\n get capture () {\n return (eventsMethods.supportsOptions = true)\n },\n get passive () {\n return (eventsMethods.supportsPassive = true)\n },\n })\n\n scope.events = eventsMethods\n\n function add (eventTarget: EventTarget, type: string, listener: Listener, optionalArg?: boolean | any) {\n const options = getOptions(optionalArg)\n let target = arr.find(targets, (t) => t.eventTarget === eventTarget)\n\n if (!target) {\n target = {\n eventTarget,\n events: {},\n }\n\n targets.push(target)\n }\n\n if (!target.events[type]) {\n target.events[type] = []\n }\n\n if (eventTarget.addEventListener && !arr.contains(target.events[type], listener)) {\n eventTarget.addEventListener(\n type,\n listener as any,\n eventsMethods.supportsOptions ? options : options.capture,\n )\n target.events[type].push(listener)\n }\n }\n\n function remove (\n eventTarget: EventTarget,\n type: string,\n listener?: 'all' | Listener,\n optionalArg?: boolean | any,\n ) {\n const options = getOptions(optionalArg)\n const targetIndex = arr.findIndex(targets, (t) => t.eventTarget === eventTarget)\n const target = targets[targetIndex]\n\n if (!target || !target.events) {\n return\n }\n\n if (type === 'all') {\n for (type in target.events) {\n if (target.events.hasOwnProperty(type)) {\n remove(eventTarget, type, 'all')\n }\n }\n return\n }\n\n let typeIsEmpty = false\n const typeListeners = target.events[type]\n\n if (typeListeners) {\n if (listener === 'all') {\n for (let i = typeListeners.length - 1; i >= 0; i--) {\n remove(eventTarget, type, typeListeners[i], options)\n }\n return\n } else {\n for (let i = 0; i < typeListeners.length; i++) {\n if (typeListeners[i] === listener) {\n eventTarget.removeEventListener(\n type,\n listener as any,\n eventsMethods.supportsOptions ? options : options.capture,\n )\n typeListeners.splice(i, 1)\n\n if (typeListeners.length === 0) {\n delete target.events[type]\n typeIsEmpty = true\n }\n\n break\n }\n }\n }\n }\n\n if (typeIsEmpty && !Object.keys(target.events).length) {\n targets.splice(targetIndex, 1)\n }\n }\n\n function addDelegate (selector: string, context: Node, type: string, listener: Listener, optionalArg?: any) {\n const options = getOptions(optionalArg)\n if (!delegatedEvents[type]) {\n delegatedEvents[type] = []\n\n // add delegate listener functions\n for (const doc of documents) {\n add(doc, type, delegateListener)\n add(doc, type, delegateUseCapture, true)\n }\n }\n\n const delegates = delegatedEvents[type]\n let delegate = arr.find(delegates, (d) => d.selector === selector && d.context === context)\n\n if (!delegate) {\n delegate = { selector, context, listeners: [] }\n delegates.push(delegate)\n }\n\n delegate.listeners.push([listener, options])\n }\n\n function removeDelegate (\n selector: string,\n context: Document | Element,\n type: string,\n listener?: Listener,\n optionalArg?: any,\n ) {\n const options = getOptions(optionalArg)\n const delegates = delegatedEvents[type]\n let matchFound = false\n let index: number\n\n if (!delegates) return\n\n // count from last index of delegated to 0\n for (index = delegates.length - 1; index >= 0; index--) {\n const cur = delegates[index]\n // look for matching selector and context Node\n if (cur.selector === selector && cur.context === context) {\n const { listeners } = cur\n\n // each item of the listeners array is an array: [function, capture, passive]\n for (let i = listeners.length - 1; i >= 0; i--) {\n const [fn, { capture, passive }] = listeners[i]\n\n // check if the listener functions and capture and passive flags match\n if (fn === listener && capture === options.capture && passive === options.passive) {\n // remove the listener from the array of listeners\n listeners.splice(i, 1)\n\n // if all listeners for this target have been removed\n // remove the target from the delegates array\n if (!listeners.length) {\n delegates.splice(index, 1)\n\n // remove delegate function from context\n remove(context, type, delegateListener)\n remove(context, type, delegateUseCapture, true)\n }\n\n // only remove one listener\n matchFound = true\n break\n }\n }\n\n if (matchFound) {\n break\n }\n }\n }\n }\n\n // bound to the interactable context when a DOM event\n // listener is added to a selector interactable\n function delegateListener (event: Event | FakeEvent, optionalArg?: any) {\n const options = getOptions(optionalArg)\n const fakeEvent = new FakeEvent(event as Event)\n const delegates = delegatedEvents[event.type]\n const [eventTarget] = pointerUtils.getEventTargets(event as Event)\n let element: Node = eventTarget\n\n // climb up document tree looking for selector matches\n while (is.element(element)) {\n for (let i = 0; i < delegates.length; i++) {\n const cur = delegates[i]\n const { selector, context } = cur\n\n if (\n domUtils.matchesSelector(element, selector) &&\n domUtils.nodeContains(context, eventTarget) &&\n domUtils.nodeContains(context, element)\n ) {\n const { listeners } = cur\n\n fakeEvent.currentTarget = element\n\n for (const [fn, { capture, passive }] of listeners) {\n if (capture === options.capture && passive === options.passive) {\n fn(fakeEvent)\n }\n }\n }\n }\n\n element = domUtils.parentNode(element)\n }\n }\n\n function delegateUseCapture (this: Element, event: Event | FakeEvent) {\n return delegateListener.call(this, event, true)\n }\n\n // for type inferrence\n return eventsMethods\n}\n\nclass FakeEvent implements Partial {\n currentTarget: Node\n originalEvent: Event\n type: string\n\n constructor (originalEvent: Event) {\n this.originalEvent = originalEvent\n // duplicate the event so that currentTarget can be changed\n pExtend(this, originalEvent)\n }\n\n preventOriginalDefault () {\n this.originalEvent.preventDefault()\n }\n\n stopPropagation () {\n this.originalEvent.stopPropagation()\n }\n\n stopImmediatePropagation () {\n this.originalEvent.stopImmediatePropagation()\n }\n}\n\nfunction getOptions (param: { [index: string]: any } | boolean): { capture: boolean, passive: boolean } {\n if (!is.object(param)) {\n return { capture: !!param, passive: false }\n }\n\n const options = extend({}, param) as any\n\n options.capture = !!param.capture\n options.passive = !!param.passive\n\n return options\n}\n\nexport default {\n id: 'events',\n install,\n}\n", "import type Interaction from '@interactjs/core/Interaction'\nimport type { Scope } from '@interactjs/core/scope'\nimport type { PointerType } from '@interactjs/core/types'\nimport * as dom from '@interactjs/utils/domUtils'\n\nexport interface SearchDetails {\n pointer: PointerType\n pointerId: number\n pointerType: string\n eventType: string\n eventTarget: EventTarget\n curEventTarget: EventTarget\n scope: Scope\n}\n\nconst finder = {\n methodOrder: ['simulationResume', 'mouseOrPen', 'hasPointer', 'idle'] as const,\n\n search (details: SearchDetails) {\n for (const method of finder.methodOrder) {\n const interaction = finder[method](details)\n\n if (interaction) {\n return interaction\n }\n }\n\n return null\n },\n\n // try to resume simulation with a new pointer\n simulationResume ({ pointerType, eventType, eventTarget, scope }: SearchDetails) {\n if (!/down|start/i.test(eventType)) {\n return null\n }\n\n for (const interaction of scope.interactions.list) {\n let element = eventTarget as Node\n\n if (\n interaction.simulation &&\n interaction.simulation.allowResume &&\n interaction.pointerType === pointerType\n ) {\n while (element) {\n // if the element is the interaction element\n if (element === interaction.element) {\n return interaction\n }\n element = dom.parentNode(element)\n }\n }\n }\n\n return null\n },\n\n // if it's a mouse or pen interaction\n mouseOrPen ({ pointerId, pointerType, eventType, scope }: SearchDetails) {\n if (pointerType !== 'mouse' && pointerType !== 'pen') {\n return null\n }\n\n let firstNonActive\n\n for (const interaction of scope.interactions.list) {\n if (interaction.pointerType === pointerType) {\n // if it's a down event, skip interactions with running simulations\n if (interaction.simulation && !hasPointerId(interaction, pointerId)) {\n continue\n }\n\n // if the interaction is active, return it immediately\n if (interaction.interacting()) {\n return interaction\n }\n // otherwise save it and look for another active interaction\n else if (!firstNonActive) {\n firstNonActive = interaction\n }\n }\n }\n\n // if no active mouse interaction was found use the first inactive mouse\n // interaction\n if (firstNonActive) {\n return firstNonActive\n }\n\n // find any mouse or pen interaction.\n // ignore the interaction if the eventType is a *down, and a simulation\n // is active\n for (const interaction of scope.interactions.list) {\n if (interaction.pointerType === pointerType && !(/down/i.test(eventType) && interaction.simulation)) {\n return interaction\n }\n }\n\n return null\n },\n\n // get interaction that has this pointer\n hasPointer ({ pointerId, scope }: SearchDetails) {\n for (const interaction of scope.interactions.list) {\n if (hasPointerId(interaction, pointerId)) {\n return interaction\n }\n }\n\n return null\n },\n\n // get first idle interaction with a matching pointerType\n idle ({ pointerType, scope }: SearchDetails) {\n for (const interaction of scope.interactions.list) {\n // if there's already a pointer held down\n if (interaction.pointers.length === 1) {\n const target = interaction.interactable\n // don't add this pointer if there is a target interactable and it\n // isn't gesturable\n if (target && !(target.options.gesture && target.options.gesture.enabled)) {\n continue\n }\n }\n // maximum of 2 pointers per interaction\n else if (interaction.pointers.length >= 2) {\n continue\n }\n\n if (!interaction.interacting() && pointerType === interaction.pointerType) {\n return interaction\n }\n }\n\n return null\n },\n}\n\nfunction hasPointerId (interaction: Interaction, pointerId: number) {\n return interaction.pointers.some(({ id }) => id === pointerId)\n}\n\nexport default finder\n", "import type { Scope, SignalArgs, Plugin } from '@interactjs/core/scope'\nimport type { ActionName, Listener } from '@interactjs/core/types'\nimport browser from '@interactjs/utils/browser'\nimport domObjects from '@interactjs/utils/domObjects'\nimport { nodeContains } from '@interactjs/utils/domUtils'\nimport * as pointerUtils from '@interactjs/utils/pointerUtils'\n\nimport InteractionBase from './Interaction'\nimport interactablePreventDefault from './interactablePreventDefault'\nimport type { SearchDetails } from './interactionFinder'\nimport finder from './interactionFinder'\n\ndeclare module '@interactjs/core/scope' {\n interface Scope {\n Interaction: typeof InteractionBase\n interactions: {\n new: (options: any) => InteractionBase\n list: Array>\n listeners: { [type: string]: Listener }\n docEvents: Array<{ type: string, listener: Listener }>\n pointerMoveTolerance: number\n }\n prevTouchTime: number\n }\n\n interface SignalArgs {\n 'interactions:find': {\n interaction: InteractionBase\n searchDetails: SearchDetails\n }\n }\n}\n\nconst methodNames = [\n 'pointerDown',\n 'pointerMove',\n 'pointerUp',\n 'updatePointer',\n 'removePointer',\n 'windowBlur',\n]\n\nfunction install (scope: Scope) {\n const listeners = {} as any\n\n for (const method of methodNames) {\n listeners[method] = doOnInteractions(method, scope)\n }\n\n const pEventTypes = browser.pEventTypes\n let docEvents: typeof scope.interactions.docEvents\n\n if (domObjects.PointerEvent) {\n docEvents = [\n { type: pEventTypes.down, listener: releasePointersOnRemovedEls },\n { type: pEventTypes.down, listener: listeners.pointerDown },\n { type: pEventTypes.move, listener: listeners.pointerMove },\n { type: pEventTypes.up, listener: listeners.pointerUp },\n { type: pEventTypes.cancel, listener: listeners.pointerUp },\n ]\n } else {\n docEvents = [\n { type: 'mousedown', listener: listeners.pointerDown },\n { type: 'mousemove', listener: listeners.pointerMove },\n { type: 'mouseup', listener: listeners.pointerUp },\n\n { type: 'touchstart', listener: releasePointersOnRemovedEls },\n { type: 'touchstart', listener: listeners.pointerDown },\n { type: 'touchmove', listener: listeners.pointerMove },\n { type: 'touchend', listener: listeners.pointerUp },\n { type: 'touchcancel', listener: listeners.pointerUp },\n ]\n }\n\n docEvents.push({\n type: 'blur',\n listener (event) {\n for (const interaction of scope.interactions.list) {\n interaction.documentBlur(event)\n }\n },\n })\n\n // for ignoring browser's simulated mouse events\n scope.prevTouchTime = 0\n\n scope.Interaction = class extends InteractionBase {\n get pointerMoveTolerance () {\n return scope.interactions.pointerMoveTolerance\n }\n\n set pointerMoveTolerance (value) {\n scope.interactions.pointerMoveTolerance = value\n }\n\n _now () {\n return scope.now()\n }\n }\n\n scope.interactions = {\n // all active and idle interactions\n list: [],\n new (options: { pointerType?: string, scopeFire?: Scope['fire'] }) {\n options.scopeFire = (name, arg) => scope.fire(name, arg)\n\n const interaction = new scope.Interaction(options as Required)\n\n scope.interactions.list.push(interaction)\n return interaction\n },\n listeners,\n docEvents,\n pointerMoveTolerance: 1,\n }\n\n function releasePointersOnRemovedEls () {\n // for all inactive touch interactions with pointers down\n for (const interaction of scope.interactions.list) {\n if (!interaction.pointerIsDown || interaction.pointerType !== 'touch' || interaction._interacting) {\n continue\n }\n\n // if a pointer is down on an element that is no longer in the DOM tree\n for (const pointer of interaction.pointers) {\n if (!scope.documents.some(({ doc }) => nodeContains(doc, pointer.downTarget))) {\n // remove the pointer from the interaction\n interaction.removePointer(pointer.pointer, pointer.event)\n }\n }\n }\n }\n\n scope.usePlugin(interactablePreventDefault)\n}\n\nfunction doOnInteractions (method: string, scope: Scope) {\n return function (event: Event) {\n const interactions = scope.interactions.list\n\n const pointerType = pointerUtils.getPointerType(event)\n const [eventTarget, curEventTarget] = pointerUtils.getEventTargets(event)\n const matches: any[] = [] // [ [pointer, interaction], ...]\n\n if (/^touch/.test(event.type)) {\n scope.prevTouchTime = scope.now()\n\n // @ts-expect-error\n for (const changedTouch of event.changedTouches) {\n const pointer = changedTouch\n const pointerId = pointerUtils.getPointerId(pointer)\n const searchDetails: SearchDetails = {\n pointer,\n pointerId,\n pointerType,\n eventType: event.type,\n eventTarget,\n curEventTarget,\n scope,\n }\n const interaction = getInteraction(searchDetails)\n\n matches.push([\n searchDetails.pointer,\n searchDetails.eventTarget,\n searchDetails.curEventTarget,\n interaction,\n ])\n }\n } else {\n let invalidPointer = false\n\n if (!browser.supportsPointerEvent && /mouse/.test(event.type)) {\n // ignore mouse events while touch interactions are active\n for (let i = 0; i < interactions.length && !invalidPointer; i++) {\n invalidPointer = interactions[i].pointerType !== 'mouse' && interactions[i].pointerIsDown\n }\n\n // try to ignore mouse events that are simulated by the browser\n // after a touch event\n invalidPointer =\n invalidPointer ||\n scope.now() - scope.prevTouchTime < 500 ||\n // on iOS and Firefox Mobile, MouseEvent.timeStamp is zero if simulated\n event.timeStamp === 0\n }\n\n if (!invalidPointer) {\n const searchDetails = {\n pointer: event as PointerEvent,\n pointerId: pointerUtils.getPointerId(event as PointerEvent),\n pointerType,\n eventType: event.type,\n curEventTarget,\n eventTarget,\n scope,\n }\n\n const interaction = getInteraction(searchDetails)\n\n matches.push([\n searchDetails.pointer,\n searchDetails.eventTarget,\n searchDetails.curEventTarget,\n interaction,\n ])\n }\n }\n\n // eslint-disable-next-line no-shadow\n for (const [pointer, eventTarget, curEventTarget, interaction] of matches) {\n interaction[method](pointer, event, eventTarget, curEventTarget)\n }\n }\n}\n\nfunction getInteraction (searchDetails: SearchDetails) {\n const { pointerType, scope } = searchDetails\n\n const foundInteraction = finder.search(searchDetails)\n const signalArg = { interaction: foundInteraction, searchDetails }\n\n scope.fire('interactions:find', signalArg)\n\n return signalArg.interaction || scope.interactions.new({ pointerType })\n}\n\nfunction onDocSignal (\n { doc, scope, options }: SignalArgs[T],\n eventMethodName: 'add' | 'remove',\n) {\n const {\n interactions: { docEvents },\n events,\n } = scope\n const eventMethod = events[eventMethodName]\n\n if (scope.browser.isIOS && !options.events) {\n options.events = { passive: false }\n }\n\n // delegate event listener\n for (const eventType in events.delegatedEvents) {\n eventMethod(doc, eventType, events.delegateListener)\n eventMethod(doc, eventType, events.delegateUseCapture, true)\n }\n\n const eventOptions = options && options.events\n\n for (const { type, listener } of docEvents) {\n eventMethod(doc, type, listener, eventOptions)\n }\n}\n\nconst interactions: Plugin = {\n id: 'core/interactions',\n install,\n listeners: {\n 'scope:add-document': (arg) => onDocSignal(arg, 'add'),\n 'scope:remove-document': (arg) => onDocSignal(arg, 'remove'),\n 'interactable:unset': ({ interactable }, scope) => {\n // Stop and destroy related interactions when an Interactable is unset\n for (let i = scope.interactions.list.length - 1; i >= 0; i--) {\n const interaction = scope.interactions.list[i]\n\n if (interaction.interactable !== interactable) {\n continue\n }\n\n interaction.stop()\n scope.fire('interactions:destroy', { interaction })\n interaction.destroy()\n\n if (scope.interactions.list.length > 2) {\n scope.interactions.list.splice(i, 1)\n }\n }\n },\n },\n onDocSignal,\n doOnInteractions,\n methodNames,\n}\n\nexport default interactions\n", "import type Interaction from '@interactjs/core/Interaction'\nimport browser from '@interactjs/utils/browser'\nimport clone from '@interactjs/utils/clone'\nimport domObjects from '@interactjs/utils/domObjects'\nimport extend from '@interactjs/utils/extend'\nimport is from '@interactjs/utils/is'\nimport raf from '@interactjs/utils/raf'\nimport * as win from '@interactjs/utils/window'\n\nimport { Eventable } from './Eventable'\nimport { InteractEvent } from './InteractEvent'\nimport { createInteractStatic } from './InteractStatic'\nimport { Interactable as InteractableBase } from './Interactable'\nimport { InteractableSet } from './InteractableSet'\nimport events from './events'\nimport interactions from './interactions'\nimport type { OptionsArg } from './options'\nimport { defaults } from './options'\nimport type { Actions } from './types'\n\nexport interface SignalArgs {\n 'scope:add-document': DocSignalArg\n 'scope:remove-document': DocSignalArg\n 'interactable:unset': { interactable: InteractableBase }\n 'interactable:set': { interactable: InteractableBase, options: OptionsArg }\n 'interactions:destroy': { interaction: Interaction }\n}\n\nexport type ListenerName = keyof SignalArgs\n\nexport type ListenerMap = {\n [P in ListenerName]?: (arg: SignalArgs[P], scope: Scope, signalName: P) => void | boolean\n}\n\ninterface DocSignalArg {\n doc: Document\n window: Window\n scope: Scope\n options: Record\n}\n\nexport interface Plugin {\n [key: string]: any\n id?: string\n listeners?: ListenerMap\n before?: string[]\n install?(scope: Scope, options?: any): void\n}\n\nexport class Scope {\n id = `__interact_scope_${Math.floor(Math.random() * 100)}`\n isInitialized = false\n listenerMaps: Array<{\n map: ListenerMap\n id: string\n }> = []\n\n browser = browser\n defaults = clone(defaults) as typeof defaults\n Eventable = Eventable\n actions: Actions = {\n map: {},\n phases: {\n start: true,\n move: true,\n end: true,\n },\n methodDict: {} as any,\n phaselessTypes: {},\n }\n\n interactStatic = createInteractStatic(this)\n InteractEvent = InteractEvent\n Interactable: typeof InteractableBase\n interactables = new InteractableSet(this)\n\n // main window\n _win!: Window\n\n // main document\n document!: Document\n\n // main window\n window!: Window\n\n // all documents being listened to\n documents: Array<{ doc: Document, options: any }> = []\n\n _plugins: {\n list: Plugin[]\n map: { [id: string]: Plugin }\n } = {\n list: [],\n map: {},\n }\n\n constructor () {\n const scope = this\n\n this.Interactable = class extends InteractableBase {\n get _defaults () {\n return scope.defaults\n }\n\n set (this: T, options: OptionsArg) {\n super.set(options)\n\n scope.fire('interactable:set', {\n options,\n interactable: this,\n })\n\n return this\n }\n\n unset (this: InteractableBase) {\n super.unset()\n\n const index = scope.interactables.list.indexOf(this)\n if (index < 0) return\n\n super.unset()\n scope.interactables.list.splice(index, 1)\n scope.fire('interactable:unset', { interactable: this })\n }\n }\n }\n\n addListeners (map: ListenerMap, id?: string) {\n this.listenerMaps.push({ id, map })\n }\n\n fire (name: T, arg: SignalArgs[T]): void | false {\n for (const {\n map: { [name]: listener },\n } of this.listenerMaps) {\n if (!!listener && listener(arg as any, this, name as never) === false) {\n return false\n }\n }\n }\n\n onWindowUnload = (event: BeforeUnloadEvent) => this.removeDocument(event.target as Document)\n\n init (window: Window | typeof globalThis) {\n return this.isInitialized ? this : initScope(this, window)\n }\n\n pluginIsInstalled (plugin: Plugin) {\n return this._plugins.map[plugin.id] || this._plugins.list.indexOf(plugin) !== -1\n }\n\n usePlugin (plugin: Plugin, options?: { [key: string]: any }) {\n if (!this.isInitialized) {\n return this\n }\n\n if (this.pluginIsInstalled(plugin)) {\n return this\n }\n\n if (plugin.id) {\n this._plugins.map[plugin.id] = plugin\n }\n this._plugins.list.push(plugin)\n\n if (plugin.install) {\n plugin.install(this, options)\n }\n\n if (plugin.listeners && plugin.before) {\n let index = 0\n const len = this.listenerMaps.length\n const before = plugin.before.reduce((acc, id) => {\n acc[id] = true\n acc[pluginIdRoot(id)] = true\n return acc\n }, {})\n\n for (; index < len; index++) {\n const otherId = this.listenerMaps[index].id\n\n if (before[otherId] || before[pluginIdRoot(otherId)]) {\n break\n }\n }\n\n this.listenerMaps.splice(index, 0, { id: plugin.id, map: plugin.listeners })\n } else if (plugin.listeners) {\n this.listenerMaps.push({ id: plugin.id, map: plugin.listeners })\n }\n\n return this\n }\n\n addDocument (doc: Document, options?: any): void | false {\n // do nothing if document is already known\n if (this.getDocIndex(doc) !== -1) {\n return false\n }\n\n const window = win.getWindow(doc)\n\n options = options ? extend({}, options) : {}\n\n this.documents.push({ doc, options })\n this.events.documents.push(doc)\n\n // don't add an unload event for the main document\n // so that the page may be cached in browser history\n if (doc !== this.document) {\n this.events.add(window, 'unload', this.onWindowUnload)\n }\n\n this.fire('scope:add-document', { doc, window, scope: this, options })\n }\n\n removeDocument (doc: Document) {\n const index = this.getDocIndex(doc)\n\n const window = win.getWindow(doc)\n const options = this.documents[index].options\n\n this.events.remove(window, 'unload', this.onWindowUnload)\n\n this.documents.splice(index, 1)\n this.events.documents.splice(index, 1)\n\n this.fire('scope:remove-document', { doc, window, scope: this, options })\n }\n\n getDocIndex (doc: Document) {\n for (let i = 0; i < this.documents.length; i++) {\n if (this.documents[i].doc === doc) {\n return i\n }\n }\n\n return -1\n }\n\n getDocOptions (doc: Document) {\n const docIndex = this.getDocIndex(doc)\n\n return docIndex === -1 ? null : this.documents[docIndex].options\n }\n\n now () {\n return (((this.window as any).Date as typeof Date) || Date).now()\n }\n}\n\nexport function initScope (scope: Scope, window: Window | typeof globalThis) {\n scope.isInitialized = true\n\n if (is.window(window)) {\n win.init(window)\n }\n\n domObjects.init(window)\n browser.init(window)\n raf.init(window)\n\n // @ts-expect-error\n scope.window = window\n scope.document = window.document\n\n scope.usePlugin(interactions)\n scope.usePlugin(events)\n\n return scope\n}\n\nfunction pluginIdRoot (id: string) {\n return id && id.replace(/\\/.*$/, '')\n}\n", "var _$types_28 = {};\n\"use strict\";\n\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsInNvdXJjZXNDb250ZW50IjpbXX0=", "import { Scope } from '@interactjs/core/scope'\nexport * from '@interactjs/core/types'\n\nconst scope = new Scope()\n\nconst interact = scope.interactStatic\n\nexport default interact\n\nconst _global = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : this\nscope.init(_global)\n", "export default () => {}\n", "export default () => {}\n", "import type { Rect, Point } from '@interactjs/core/types'\nimport type { SnapFunction, SnapTarget } from '@interactjs/modifiers/snap/pointer'\n\nexport type GridOptions = (Partial | Point) & {\n range?: number\n limits?: Rect\n offset?: Point\n}\n\nexport default (grid: GridOptions) => {\n const coordFields = (\n [\n ['x', 'y'],\n ['left', 'top'],\n ['right', 'bottom'],\n ['width', 'height'],\n ] as const\n ).filter(([xField, yField]) => xField in grid || yField in grid)\n\n const gridFunc: SnapFunction & {\n grid: typeof grid\n coordFields: typeof coordFields\n } = (x, y) => {\n const {\n range,\n limits = {\n left: -Infinity,\n right: Infinity,\n top: -Infinity,\n bottom: Infinity,\n },\n offset = { x: 0, y: 0 },\n } = grid\n\n const result: SnapTarget & {\n grid: typeof grid\n } = { range, grid, x: null as number, y: null as number }\n\n for (const [xField, yField] of coordFields) {\n const gridx = Math.round((x - offset.x) / (grid as any)[xField])\n const gridy = Math.round((y - offset.y) / (grid as any)[yField])\n\n result[xField] = Math.max(limits.left, Math.min(limits.right, gridx * (grid as any)[xField] + offset.x))\n result[yField] = Math.max(limits.top, Math.min(limits.bottom, gridy * (grid as any)[yField] + offset.y))\n }\n\n return result\n }\n\n gridFunc.grid = grid\n gridFunc.coordFields = coordFields\n\n return gridFunc\n}\n", "import type { Plugin } from '@interactjs/core/scope'\nimport extend from '@interactjs/utils/extend'\n\nimport * as allSnappers from './all'\n\ndeclare module '@interactjs/core/InteractStatic' {\n export interface InteractStatic {\n snappers: typeof allSnappers\n createSnapGrid: typeof allSnappers.grid\n }\n}\n\nconst snappersPlugin: Plugin = {\n id: 'snappers',\n install (scope) {\n const { interactStatic: interact } = scope\n\n interact.snappers = extend(interact.snappers || {}, allSnappers)\n interact.createSnapGrid = interact.snappers.grid\n },\n}\n\nexport default snappersPlugin\n", "/**\n * @module modifiers/aspectRatio\n *\n * @description\n * This module forces elements to be resized with a specified dx/dy ratio.\n *\n * ```js\n * interact(target).resizable({\n * modifiers: [\n * interact.modifiers.snapSize({\n * targets: [ interact.snappers.grid({ x: 20, y: 20 }) ],\n * }),\n * interact.aspectRatio({ ratio: 'preserve' }),\n * ],\n * });\n * ```\n */\n\nimport type { Point, Rect, EdgeOptions } from '@interactjs/core/types'\nimport extend from '@interactjs/utils/extend'\nimport { addEdges } from '@interactjs/utils/rect'\n\nimport Modification from './Modification'\nimport type { Modifier, ModifierModule, ModifierState } from './base'\nimport { makeModifier } from './base'\n\nexport interface AspectRatioOptions {\n ratio?: number | 'preserve'\n equalDelta?: boolean\n modifiers?: Modifier[]\n enabled?: boolean\n}\n\nexport type AspectRatioState = ModifierState<\nAspectRatioOptions,\n{\n startCoords: Point\n startRect: Rect\n linkedEdges: EdgeOptions\n ratio: number\n equalDelta: boolean\n xIsPrimaryAxis: boolean\n edgeSign: {\n x: number\n y: number\n }\n subModification: Modification\n}\n>\n\nconst aspectRatio: ModifierModule = {\n start (arg) {\n const { state, rect, edges: originalEdges, pageCoords: coords } = arg\n let { ratio } = state.options\n const { equalDelta, modifiers } = state.options\n\n if (ratio === 'preserve') {\n ratio = rect.width / rect.height\n }\n\n state.startCoords = extend({}, coords)\n state.startRect = extend({}, rect)\n state.ratio = ratio\n state.equalDelta = equalDelta\n\n const linkedEdges = (state.linkedEdges = {\n top: originalEdges.top || (originalEdges.left && !originalEdges.bottom),\n left: originalEdges.left || (originalEdges.top && !originalEdges.right),\n bottom: originalEdges.bottom || (originalEdges.right && !originalEdges.top),\n right: originalEdges.right || (originalEdges.bottom && !originalEdges.left),\n })\n\n state.xIsPrimaryAxis = !!(originalEdges.left || originalEdges.right)\n\n if (state.equalDelta) {\n const sign = (linkedEdges.left ? 1 : -1) * (linkedEdges.top ? 1 : -1)\n state.edgeSign = {\n x: sign,\n y: sign,\n }\n } else {\n state.edgeSign = {\n x: linkedEdges.left ? -1 : 1,\n y: linkedEdges.top ? -1 : 1,\n }\n }\n\n extend(arg.edges, linkedEdges)\n\n if (!modifiers || !modifiers.length) return\n\n const subModification = new Modification(arg.interaction)\n\n subModification.copyFrom(arg.interaction.modification)\n subModification.prepareStates(modifiers)\n\n state.subModification = subModification\n subModification.startAll({ ...arg })\n },\n\n set (arg) {\n const { state, rect, coords } = arg\n const initialCoords = extend({}, coords)\n const aspectMethod = state.equalDelta ? setEqualDelta : setRatio\n\n aspectMethod(state, state.xIsPrimaryAxis, coords, rect)\n\n if (!state.subModification) {\n return null\n }\n\n const correctedRect = extend({}, rect)\n\n addEdges(state.linkedEdges, correctedRect, {\n x: coords.x - initialCoords.x,\n y: coords.y - initialCoords.y,\n })\n\n const result = state.subModification.setAll({\n ...arg,\n rect: correctedRect,\n edges: state.linkedEdges,\n pageCoords: coords,\n prevCoords: coords,\n prevRect: correctedRect,\n })\n\n const { delta } = result\n\n if (result.changed) {\n const xIsCriticalAxis = Math.abs(delta.x) > Math.abs(delta.y)\n\n // do aspect modification again with critical edge axis as primary\n aspectMethod(state, xIsCriticalAxis, result.coords, result.rect)\n extend(coords, result.coords)\n }\n\n return result.eventProps\n },\n\n defaults: {\n ratio: 'preserve',\n equalDelta: false,\n modifiers: [],\n enabled: false,\n },\n}\n\nfunction setEqualDelta ({ startCoords, edgeSign }: AspectRatioState, xIsPrimaryAxis: boolean, coords: Point) {\n if (xIsPrimaryAxis) {\n coords.y = startCoords.y + (coords.x - startCoords.x) * edgeSign.y\n } else {\n coords.x = startCoords.x + (coords.y - startCoords.y) * edgeSign.x\n }\n}\n\nfunction setRatio (\n { startRect, startCoords, ratio, edgeSign }: AspectRatioState,\n xIsPrimaryAxis: boolean,\n coords: Point,\n rect: Rect,\n) {\n if (xIsPrimaryAxis) {\n const newHeight = rect.width / ratio\n\n coords.y = startCoords.y + (newHeight - startRect.height) * edgeSign.y\n } else {\n const newWidth = rect.height * ratio\n\n coords.x = startCoords.x + (newWidth - startRect.width) * edgeSign.x\n }\n}\n\nexport default makeModifier(aspectRatio, 'aspectRatio')\nexport { aspectRatio }\n", "import type { ModifierFunction } from '@interactjs/modifiers/base'\n\nconst noop = (() => {}) as unknown as ModifierFunction\n\nnoop._defaults = {}\n\nexport default noop\n", "import type Interaction from '@interactjs/core/Interaction'\nimport type { RectResolvable, Rect, Point } from '@interactjs/core/types'\nimport extend from '@interactjs/utils/extend'\nimport is from '@interactjs/utils/is'\nimport * as rectUtils from '@interactjs/utils/rect'\n\nimport type { ModifierArg, ModifierModule, ModifierState } from '../base'\nimport { makeModifier } from '../base'\n\nexport interface RestrictOptions {\n // where to drag over\n restriction: RectResolvable<[number, number, Interaction]>\n // what part of self is allowed to drag over\n elementRect: Rect\n offset: Rect\n // restrict just before the end drag\n endOnly: boolean\n enabled?: boolean\n}\n\nexport type RestrictState = ModifierState<\nRestrictOptions,\n{\n offset: Rect\n}\n>\n\nfunction start ({ rect, startOffset, state, interaction, pageCoords }: ModifierArg) {\n const { options } = state\n const { elementRect } = options\n const offset: Rect = extend(\n {\n left: 0,\n top: 0,\n right: 0,\n bottom: 0,\n },\n options.offset || {},\n )\n\n if (rect && elementRect) {\n const restriction = getRestrictionRect(options.restriction, interaction, pageCoords)\n\n if (restriction) {\n const widthDiff = restriction.right - restriction.left - rect.width\n const heightDiff = restriction.bottom - restriction.top - rect.height\n\n if (widthDiff < 0) {\n offset.left += widthDiff\n offset.right += widthDiff\n }\n if (heightDiff < 0) {\n offset.top += heightDiff\n offset.bottom += heightDiff\n }\n }\n\n offset.left += startOffset.left - rect.width * elementRect.left\n offset.top += startOffset.top - rect.height * elementRect.top\n\n offset.right += startOffset.right - rect.width * (1 - elementRect.right)\n offset.bottom += startOffset.bottom - rect.height * (1 - elementRect.bottom)\n }\n\n state.offset = offset\n}\n\nfunction set ({ coords, interaction, state }: ModifierArg) {\n const { options, offset } = state\n\n const restriction = getRestrictionRect(options.restriction, interaction, coords)\n\n if (!restriction) return\n\n const rect = rectUtils.xywhToTlbr(restriction)\n\n coords.x = Math.max(Math.min(rect.right - offset.right, coords.x), rect.left + offset.left)\n coords.y = Math.max(Math.min(rect.bottom - offset.bottom, coords.y), rect.top + offset.top)\n}\n\nexport function getRestrictionRect (\n value: RectResolvable<[number, number, Interaction]>,\n interaction: Interaction,\n coords?: Point,\n) {\n if (is.func(value)) {\n return rectUtils.resolveRectLike(value, interaction.interactable, interaction.element, [\n coords.x,\n coords.y,\n interaction,\n ])\n } else {\n return rectUtils.resolveRectLike(value, interaction.interactable, interaction.element)\n }\n}\n\nconst defaults: RestrictOptions = {\n restriction: null,\n elementRect: null,\n offset: null,\n endOnly: false,\n enabled: false,\n}\n\nconst restrict: ModifierModule = {\n start,\n set,\n defaults,\n}\n\nexport default makeModifier(restrict, 'restrict')\nexport { restrict }\n", "// This module adds the options.resize.restrictEdges setting which sets min and\n// max for the top, left, bottom and right edges of the target being resized.\n//\n// interact(target).resize({\n// edges: { top: true, left: true },\n// restrictEdges: {\n// inner: { top: 200, left: 200, right: 400, bottom: 400 },\n// outer: { top: 0, left: 0, right: 600, bottom: 600 },\n// },\n// })\n\nimport type { Point, Rect } from '@interactjs/core/types'\nimport extend from '@interactjs/utils/extend'\nimport * as rectUtils from '@interactjs/utils/rect'\n\nimport type { ModifierArg, ModifierState } from '../base'\nimport { makeModifier } from '../base'\n\nimport type { RestrictOptions } from './pointer'\nimport { getRestrictionRect } from './pointer'\n\nexport interface RestrictEdgesOptions {\n inner: RestrictOptions['restriction']\n outer: RestrictOptions['restriction']\n offset?: RestrictOptions['offset']\n endOnly: boolean\n enabled?: boolean\n}\n\nexport type RestrictEdgesState = ModifierState<\nRestrictEdgesOptions,\n{\n inner: Rect\n outer: Rect\n offset: RestrictEdgesOptions['offset']\n}\n>\n\nconst noInner = { top: +Infinity, left: +Infinity, bottom: -Infinity, right: -Infinity }\nconst noOuter = { top: -Infinity, left: -Infinity, bottom: +Infinity, right: +Infinity }\n\nfunction start ({ interaction, startOffset, state }: ModifierArg) {\n const { options } = state\n let offset: Point\n\n if (options) {\n const offsetRect = getRestrictionRect(options.offset, interaction, interaction.coords.start.page)\n\n offset = rectUtils.rectToXY(offsetRect)\n }\n\n offset = offset || { x: 0, y: 0 }\n\n state.offset = {\n top: offset.y + startOffset.top,\n left: offset.x + startOffset.left,\n bottom: offset.y - startOffset.bottom,\n right: offset.x - startOffset.right,\n }\n}\n\nfunction set ({ coords, edges, interaction, state }: ModifierArg) {\n const { offset, options } = state\n\n if (!edges) {\n return\n }\n\n const page = extend({}, coords)\n const inner = getRestrictionRect(options.inner, interaction, page) || ({} as Rect)\n const outer = getRestrictionRect(options.outer, interaction, page) || ({} as Rect)\n\n fixRect(inner, noInner)\n fixRect(outer, noOuter)\n\n if (edges.top) {\n coords.y = Math.min(Math.max(outer.top + offset.top, page.y), inner.top + offset.top)\n } else if (edges.bottom) {\n coords.y = Math.max(Math.min(outer.bottom + offset.bottom, page.y), inner.bottom + offset.bottom)\n }\n if (edges.left) {\n coords.x = Math.min(Math.max(outer.left + offset.left, page.x), inner.left + offset.left)\n } else if (edges.right) {\n coords.x = Math.max(Math.min(outer.right + offset.right, page.x), inner.right + offset.right)\n }\n}\n\nfunction fixRect (rect: Rect, defaults: Rect) {\n for (const edge of ['top', 'left', 'bottom', 'right']) {\n if (!(edge in rect)) {\n rect[edge] = defaults[edge]\n }\n }\n\n return rect\n}\n\nconst defaults: RestrictEdgesOptions = {\n inner: null,\n outer: null,\n offset: null,\n endOnly: false,\n enabled: false,\n}\n\nconst restrictEdges = {\n noInner,\n noOuter,\n start,\n set,\n defaults,\n}\n\nexport default makeModifier(restrictEdges, 'restrictEdges')\nexport { restrictEdges }\n", "import extend from '@interactjs/utils/extend'\n\nimport { makeModifier } from '../base'\n\nimport { restrict } from './pointer'\n\nconst defaults = extend(\n {\n get elementRect () {\n return { top: 0, left: 0, bottom: 1, right: 1 }\n },\n set elementRect (_) {},\n },\n restrict.defaults,\n)\n\nconst restrictRect = {\n start: restrict.start,\n set: restrict.set,\n defaults,\n}\n\nexport default makeModifier(restrictRect, 'restrictRect')\nexport { restrictRect }\n", "import type { Point, Rect, Size } from '@interactjs/core/types'\nimport extend from '@interactjs/utils/extend'\nimport * as rectUtils from '@interactjs/utils/rect'\n\nimport type { ModifierArg, ModifierState } from '../base'\nimport { makeModifier } from '../base'\n\nimport type { RestrictEdgesState } from './edges'\nimport { restrictEdges } from './edges'\nimport type { RestrictOptions } from './pointer'\nimport { getRestrictionRect } from './pointer'\n\nconst noMin = { width: -Infinity, height: -Infinity }\nconst noMax = { width: +Infinity, height: +Infinity }\n\nexport interface RestrictSizeOptions {\n min?: Size | Point | RestrictOptions['restriction']\n max?: Size | Point | RestrictOptions['restriction']\n endOnly: boolean\n enabled?: boolean\n}\n\nfunction start (arg: ModifierArg) {\n return restrictEdges.start(arg)\n}\n\nexport type RestrictSizeState = RestrictEdgesState &\nModifierState<\nRestrictSizeOptions & { inner: Rect, outer: Rect },\n{\n min: Rect\n max: Rect\n}\n>\n\nfunction set (arg: ModifierArg) {\n const { interaction, state, rect, edges } = arg\n const { options } = state\n\n if (!edges) {\n return\n }\n\n const minSize =\n rectUtils.tlbrToXywh(getRestrictionRect(options.min as any, interaction, arg.coords)) || noMin\n const maxSize =\n rectUtils.tlbrToXywh(getRestrictionRect(options.max as any, interaction, arg.coords)) || noMax\n\n state.options = {\n endOnly: options.endOnly,\n inner: extend({}, restrictEdges.noInner),\n outer: extend({}, restrictEdges.noOuter),\n }\n\n if (edges.top) {\n state.options.inner.top = rect.bottom - minSize.height\n state.options.outer.top = rect.bottom - maxSize.height\n } else if (edges.bottom) {\n state.options.inner.bottom = rect.top + minSize.height\n state.options.outer.bottom = rect.top + maxSize.height\n }\n if (edges.left) {\n state.options.inner.left = rect.right - minSize.width\n state.options.outer.left = rect.right - maxSize.width\n } else if (edges.right) {\n state.options.inner.right = rect.left + minSize.width\n state.options.outer.right = rect.left + maxSize.width\n }\n\n restrictEdges.set(arg)\n\n state.options = options\n}\n\nconst defaults: RestrictSizeOptions = {\n min: null,\n max: null,\n endOnly: false,\n enabled: false,\n}\n\nconst restrictSize = {\n start,\n set,\n defaults,\n}\n\nexport default makeModifier(restrictSize, 'restrictSize')\nexport { restrictSize }\n", "import type { Interaction, InteractionProxy } from '@interactjs/core/Interaction'\nimport type { ActionName, Point, RectResolvable, Element } from '@interactjs/core/types'\nimport extend from '@interactjs/utils/extend'\nimport getOriginXY from '@interactjs/utils/getOriginXY'\nimport hypot from '@interactjs/utils/hypot'\nimport is from '@interactjs/utils/is'\nimport { resolveRectLike, rectToXY } from '@interactjs/utils/rect'\n\nimport type { ModifierArg, ModifierState } from '../base'\nimport { makeModifier } from '../base'\n\nexport interface Offset {\n x: number\n y: number\n index: number\n relativePoint?: Point | null\n}\n\nexport interface SnapPosition {\n x?: number\n y?: number\n range?: number\n offset?: Offset\n [index: string]: any\n}\n\nexport type SnapFunction = (\n x: number,\n y: number,\n interaction: InteractionProxy,\n offset: Offset,\n index: number,\n) => SnapPosition\nexport type SnapTarget = SnapPosition | SnapFunction\nexport interface SnapOptions {\n targets: SnapTarget[] | null\n // target range\n range: number\n // self points for snapping. [0,0] = top left, [1,1] = bottom right\n relativePoints: Point[] | null\n // startCoords = offset snapping from drag start page position\n offset: Point | RectResolvable<[Interaction]> | 'startCoords' | null\n offsetWithOrigin?: boolean\n origin: RectResolvable<[Element]> | Point | null\n endOnly?: boolean\n enabled?: boolean\n}\n\nexport type SnapState = ModifierState<\nSnapOptions,\n{\n offsets?: Offset[]\n closest?: any\n targetFields?: string[][]\n}\n>\n\nfunction start (arg: ModifierArg) {\n const { interaction, interactable, element, rect, state, startOffset } = arg\n const { options } = state\n const origin = options.offsetWithOrigin ? getOrigin(arg) : { x: 0, y: 0 }\n\n let snapOffset: Point\n\n if (options.offset === 'startCoords') {\n snapOffset = {\n x: interaction.coords.start.page.x,\n y: interaction.coords.start.page.y,\n }\n } else {\n const offsetRect = resolveRectLike(options.offset as any, interactable, element, [interaction])\n\n snapOffset = rectToXY(offsetRect) || { x: 0, y: 0 }\n snapOffset.x += origin.x\n snapOffset.y += origin.y\n }\n\n const { relativePoints } = options\n\n state.offsets =\n rect && relativePoints && relativePoints.length\n ? relativePoints.map((relativePoint, index) => ({\n index,\n relativePoint,\n x: startOffset.left - rect.width * relativePoint.x + snapOffset.x,\n y: startOffset.top - rect.height * relativePoint.y + snapOffset.y,\n }))\n : [\n {\n index: 0,\n relativePoint: null,\n x: snapOffset.x,\n y: snapOffset.y,\n },\n ]\n}\n\nfunction set (arg: ModifierArg) {\n const { interaction, coords, state } = arg\n const { options, offsets } = state\n\n const origin = getOriginXY(interaction.interactable, interaction.element, interaction.prepared.name)\n const page = extend({}, coords)\n const targets = []\n\n if (!options.offsetWithOrigin) {\n page.x -= origin.x\n page.y -= origin.y\n }\n\n for (const offset of offsets) {\n const relativeX = page.x - offset.x\n const relativeY = page.y - offset.y\n\n for (let index = 0, len = options.targets.length; index < len; index++) {\n const snapTarget = options.targets[index]\n let target: SnapPosition\n\n if (is.func(snapTarget)) {\n target = snapTarget(relativeX, relativeY, interaction._proxy, offset, index)\n } else {\n target = snapTarget\n }\n\n if (!target) {\n continue\n }\n\n targets.push({\n x: (is.number(target.x) ? target.x : relativeX) + offset.x,\n y: (is.number(target.y) ? target.y : relativeY) + offset.y,\n\n range: is.number(target.range) ? target.range : options.range,\n source: snapTarget,\n index,\n offset,\n })\n }\n }\n\n const closest = {\n target: null,\n inRange: false,\n distance: 0,\n range: 0,\n delta: { x: 0, y: 0 },\n }\n\n for (const target of targets) {\n const range = target.range\n const dx = target.x - page.x\n const dy = target.y - page.y\n const distance = hypot(dx, dy)\n let inRange = distance <= range\n\n // Infinite targets count as being out of range\n // compared to non infinite ones that are in range\n if (range === Infinity && closest.inRange && closest.range !== Infinity) {\n inRange = false\n }\n\n if (\n !closest.target ||\n (inRange\n ? // is the closest target in range?\n closest.inRange && range !== Infinity\n ? // the pointer is relatively deeper in this target\n distance / range < closest.distance / closest.range\n : // this target has Infinite range and the closest doesn't\n (range === Infinity && closest.range !== Infinity) ||\n // OR this target is closer that the previous closest\n distance < closest.distance\n : // The other is not in range and the pointer is closer to this target\n !closest.inRange && distance < closest.distance)\n ) {\n closest.target = target\n closest.distance = distance\n closest.range = range\n closest.inRange = inRange\n closest.delta.x = dx\n closest.delta.y = dy\n }\n }\n\n if (closest.inRange) {\n coords.x = closest.target.x\n coords.y = closest.target.y\n }\n\n state.closest = closest\n return closest\n}\n\nfunction getOrigin (arg: Partial>) {\n const { element } = arg.interaction\n const optionsOrigin = rectToXY(resolveRectLike(arg.state.options.origin as any, null, null, [element]))\n const origin = optionsOrigin || getOriginXY(arg.interactable, element, arg.interaction.prepared.name)\n\n return origin\n}\n\nconst defaults: SnapOptions = {\n range: Infinity,\n targets: null,\n offset: null,\n offsetWithOrigin: true,\n origin: null,\n relativePoints: null,\n endOnly: false,\n enabled: false,\n}\nconst snap = {\n start,\n set,\n defaults,\n}\n\nexport default makeModifier(snap, 'snap')\nexport { snap }\n", "// This module allows snapping of the size of targets during resize\n// interactions.\n\nimport extend from '@interactjs/utils/extend'\nimport is from '@interactjs/utils/is'\n\nimport type { ModifierArg } from '../base'\nimport { makeModifier } from '../base'\n\nimport type { SnapOptions, SnapState } from './pointer'\nimport { snap } from './pointer'\n\nexport type SnapSizeOptions = Pick\n\nfunction start (arg: ModifierArg) {\n const { state, edges } = arg\n const { options } = state\n\n if (!edges) {\n return null\n }\n\n arg.state = {\n options: {\n targets: null,\n relativePoints: [\n {\n x: edges.left ? 0 : 1,\n y: edges.top ? 0 : 1,\n },\n ],\n offset: options.offset || 'self',\n origin: { x: 0, y: 0 },\n range: options.range,\n },\n }\n\n state.targetFields = state.targetFields || [\n ['width', 'height'],\n ['x', 'y'],\n ]\n\n snap.start(arg)\n state.offsets = arg.state.offsets\n\n arg.state = state\n}\n\nfunction set (arg) {\n const { interaction, state, coords } = arg\n const { options, offsets } = state\n const relative = {\n x: coords.x - offsets[0].x,\n y: coords.y - offsets[0].y,\n }\n\n state.options = extend({}, options)\n state.options.targets = []\n\n for (const snapTarget of options.targets || []) {\n let target\n\n if (is.func(snapTarget)) {\n target = snapTarget(relative.x, relative.y, interaction)\n } else {\n target = snapTarget\n }\n\n if (!target) {\n continue\n }\n\n for (const [xField, yField] of state.targetFields) {\n if (xField in target || yField in target) {\n target.x = target[xField]\n target.y = target[yField]\n\n break\n }\n }\n\n state.options.targets.push(target)\n }\n\n const returnValue = snap.set(arg)\n\n state.options = options\n\n return returnValue\n}\n\nconst defaults: SnapSizeOptions = {\n range: Infinity,\n targets: null,\n offset: null,\n endOnly: false,\n enabled: false,\n}\n\nconst snapSize = {\n start,\n set,\n defaults,\n}\n\nexport default makeModifier(snapSize, 'snapSize')\nexport { snapSize }\n", "/**\n * @module modifiers/snapEdges\n *\n * @description\n * WOW> This module allows snapping of the edges of targets during resize\n * interactions.\n *\n * ```js\n * interact(target).resizable({\n * snapEdges: {\n * targets: [interact.snappers.grid({ x: 100, y: 50 })],\n * },\n * })\n *\n * interact(target).resizable({\n * snapEdges: {\n * targets: [\n * interact.snappers.grid({\n * top: 50,\n * left: 50,\n * bottom: 100,\n * right: 100,\n * }),\n * ],\n * },\n * })\n * ```\n */\n\nimport clone from '@interactjs/utils/clone'\nimport extend from '@interactjs/utils/extend'\n\nimport type { ModifierArg, ModifierModule } from '../base'\nimport { makeModifier } from '../base'\n\nimport type { SnapOptions, SnapState } from './pointer'\nimport { snapSize } from './size'\n\nexport type SnapEdgesOptions = Pick\n\nfunction start (arg: ModifierArg) {\n const { edges } = arg\n\n if (!edges) {\n return null\n }\n\n arg.state.targetFields = arg.state.targetFields || [\n [edges.left ? 'left' : 'right', edges.top ? 'top' : 'bottom'],\n ]\n\n return snapSize.start(arg)\n}\n\nconst snapEdges: ModifierModule> = {\n start,\n set: snapSize.set,\n defaults: extend(clone(snapSize.defaults), {\n targets: null,\n range: null,\n offset: { x: 0, y: 0 },\n } as const),\n}\n\nexport default makeModifier(snapEdges, 'snapEdges')\nexport { snapEdges }\n", "/* eslint-disable n/no-extraneous-import, import/no-unresolved */\nimport aspectRatio from './aspectRatio'\nimport avoid from './avoid/avoid'\nimport restrictEdges from './restrict/edges'\nimport restrict from './restrict/pointer'\nimport restrictRect from './restrict/rect'\nimport restrictSize from './restrict/size'\nimport rubberband from './rubberband/rubberband'\nimport snapEdges from './snap/edges'\nimport snap from './snap/pointer'\nimport snapSize from './snap/size'\nimport spring from './spring/spring'\nimport transform from './transform/transform'\n\nexport default {\n aspectRatio,\n restrictEdges,\n restrict,\n restrictRect,\n restrictSize,\n snapEdges,\n snap,\n snapSize,\n\n spring,\n avoid,\n transform,\n rubberband,\n}\n", "import type { Plugin } from '@interactjs/core/scope'\nimport snappers from '@interactjs/snappers/plugin'\n\nimport all from './all'\nimport base from './base'\n\ndeclare module '@interactjs/core/InteractStatic' {\n export interface InteractStatic {\n modifiers: typeof all\n }\n}\n\nconst modifiers: Plugin = {\n id: 'modifiers',\n install (scope) {\n const { interactStatic: interact } = scope\n\n scope.usePlugin(base)\n scope.usePlugin(snappers)\n\n interact.modifiers = all\n\n // for backwrads compatibility\n for (const type in all) {\n const { _defaults, _methods } = all[type as keyof typeof all]\n\n ;(_defaults as any)._methods = _methods\n ;(scope.defaults.perAction as any)[type] = _defaults\n }\n },\n}\n\nexport default modifiers\n", "import { BaseEvent } from '@interactjs/core/BaseEvent'\nimport type Interaction from '@interactjs/core/Interaction'\nimport type { PointerEventType, PointerType, Point } from '@interactjs/core/types'\nimport * as pointerUtils from '@interactjs/utils/pointerUtils'\n\nexport default class PointerEvent extends BaseEvent {\n declare type: T\n declare originalEvent: PointerEventType\n declare pointerId: number\n declare pointerType: string\n declare double: boolean\n declare pageX: number\n declare pageY: number\n declare clientX: number\n declare clientY: number\n declare dt: number\n declare eventable: any;\n [key: string]: any\n\n /** */\n constructor (\n type: T,\n pointer: PointerType | PointerEvent,\n event: PointerEventType,\n eventTarget: Node,\n interaction: Interaction,\n timeStamp: number,\n ) {\n super(interaction)\n pointerUtils.pointerExtend(this, event)\n\n if (event !== pointer) {\n pointerUtils.pointerExtend(this, pointer)\n }\n\n this.timeStamp = timeStamp\n this.originalEvent = event\n this.type = type\n this.pointerId = pointerUtils.getPointerId(pointer)\n this.pointerType = pointerUtils.getPointerType(pointer)\n this.target = eventTarget\n this.currentTarget = null\n\n if (type === 'tap') {\n const pointerIndex = interaction.getPointerIndex(pointer)\n this.dt = this.timeStamp - interaction.pointers[pointerIndex].downTime\n\n const interval = this.timeStamp - interaction.tapTime\n\n this.double =\n !!interaction.prevTap &&\n interaction.prevTap.type !== 'doubletap' &&\n interaction.prevTap.target === this.target &&\n interval < 500\n } else if (type === 'doubletap') {\n this.dt = (pointer as PointerEvent<'tap'>).timeStamp - interaction.tapTime\n this.double = true\n }\n }\n\n _subtractOrigin ({ x: originX, y: originY }: Point) {\n this.pageX -= originX\n this.pageY -= originY\n this.clientX -= originX\n this.clientY -= originY\n\n return this\n }\n\n _addOrigin ({ x: originX, y: originY }: Point) {\n this.pageX += originX\n this.pageY += originY\n this.clientX += originX\n this.clientY += originY\n\n return this\n }\n\n /**\n * Prevent the default behaviour of the original Event\n */\n preventDefault () {\n this.originalEvent.preventDefault()\n }\n}\n\nexport { PointerEvent }\n", "import type { Eventable } from '@interactjs/core/Eventable'\nimport type { Interaction } from '@interactjs/core/Interaction'\nimport type { PerActionDefaults } from '@interactjs/core/options'\nimport type { Scope, SignalArgs, Plugin } from '@interactjs/core/scope'\nimport type { Point, PointerType, PointerEventType, Element } from '@interactjs/core/types'\nimport * as domUtils from '@interactjs/utils/domUtils'\nimport extend from '@interactjs/utils/extend'\nimport getOriginXY from '@interactjs/utils/getOriginXY'\n\nimport { PointerEvent } from './PointerEvent'\n\nexport type EventTargetList = Array<{\n node: Node\n eventable: Eventable\n props: { [key: string]: any }\n}>\n\nexport interface PointerEventOptions extends PerActionDefaults {\n enabled?: undefined // not used\n holdDuration?: number\n ignoreFrom?: any\n allowFrom?: any\n origin?: Point | string | Element\n}\n\ndeclare module '@interactjs/core/scope' {\n interface Scope {\n pointerEvents: typeof pointerEvents\n }\n}\n\ndeclare module '@interactjs/core/Interaction' {\n interface Interaction {\n prevTap?: PointerEvent\n tapTime?: number\n }\n}\n\ndeclare module '@interactjs/core/PointerInfo' {\n interface PointerInfo {\n hold?: {\n duration: number\n timeout: any\n }\n }\n}\n\ndeclare module '@interactjs/core/options' {\n interface ActionDefaults {\n pointerEvents: Options\n }\n}\n\ndeclare module '@interactjs/core/scope' {\n interface SignalArgs {\n 'pointerEvents:new': { pointerEvent: PointerEvent }\n 'pointerEvents:fired': {\n interaction: Interaction\n pointer: PointerType | PointerEvent\n event: PointerEventType | PointerEvent\n eventTarget: Node\n pointerEvent: PointerEvent\n targets?: EventTargetList\n type: string\n }\n 'pointerEvents:collect-targets': {\n interaction: Interaction\n pointer: PointerType | PointerEvent\n event: PointerEventType | PointerEvent\n eventTarget: Node\n targets?: EventTargetList\n type: string\n path: Node[]\n node: null\n }\n }\n}\n\nconst defaults: PointerEventOptions = {\n holdDuration: 600,\n ignoreFrom: null,\n allowFrom: null,\n origin: { x: 0, y: 0 },\n}\n\nconst pointerEvents: Plugin = {\n id: 'pointer-events/base',\n before: ['inertia', 'modifiers', 'auto-start', 'actions'],\n install,\n listeners: {\n 'interactions:new': addInteractionProps,\n 'interactions:update-pointer': addHoldInfo,\n 'interactions:move': moveAndClearHold,\n 'interactions:down': (arg, scope) => {\n downAndStartHold(arg, scope)\n fire(arg, scope)\n },\n 'interactions:up': (arg, scope) => {\n clearHold(arg)\n fire(arg, scope)\n tapAfterUp(arg, scope)\n },\n 'interactions:cancel': (arg, scope) => {\n clearHold(arg)\n fire(arg, scope)\n },\n },\n PointerEvent,\n fire,\n collectEventTargets,\n defaults,\n types: {\n down: true,\n move: true,\n up: true,\n cancel: true,\n tap: true,\n doubletap: true,\n hold: true,\n } as { [type: string]: true },\n}\n\nfunction fire (\n arg: {\n pointer: PointerType | PointerEvent\n event: PointerEventType | PointerEvent\n eventTarget: Node\n interaction: Interaction\n type: T\n targets?: EventTargetList\n },\n scope: Scope,\n) {\n const { interaction, pointer, event, eventTarget, type, targets = collectEventTargets(arg, scope) } = arg\n\n const pointerEvent = new PointerEvent(type, pointer, event, eventTarget, interaction, scope.now())\n\n scope.fire('pointerEvents:new', { pointerEvent })\n\n const signalArg = {\n interaction,\n pointer,\n event,\n eventTarget,\n targets,\n type,\n pointerEvent,\n }\n\n for (let i = 0; i < targets.length; i++) {\n const target = targets[i]\n\n for (const prop in target.props || {}) {\n ;(pointerEvent as any)[prop] = target.props[prop]\n }\n\n const origin = getOriginXY(target.eventable, target.node)\n\n pointerEvent._subtractOrigin(origin)\n pointerEvent.eventable = target.eventable\n pointerEvent.currentTarget = target.node\n\n target.eventable.fire(pointerEvent)\n\n pointerEvent._addOrigin(origin)\n\n if (\n pointerEvent.immediatePropagationStopped ||\n (pointerEvent.propagationStopped &&\n i + 1 < targets.length &&\n targets[i + 1].node !== pointerEvent.currentTarget)\n ) {\n break\n }\n }\n\n scope.fire('pointerEvents:fired', signalArg)\n\n if (type === 'tap') {\n // if pointerEvent should make a double tap, create and fire a doubletap\n // PointerEvent and use that as the prevTap\n const prevTap = pointerEvent.double\n ? fire(\n {\n interaction,\n pointer,\n event,\n eventTarget,\n type: 'doubletap',\n },\n scope,\n )\n : pointerEvent\n\n interaction.prevTap = prevTap\n interaction.tapTime = prevTap.timeStamp\n }\n\n return pointerEvent\n}\n\nfunction collectEventTargets (\n {\n interaction,\n pointer,\n event,\n eventTarget,\n type,\n }: {\n interaction: Interaction\n pointer: PointerType | PointerEvent\n event: PointerEventType | PointerEvent\n eventTarget: Node\n type: T\n },\n scope: Scope,\n) {\n const pointerIndex = interaction.getPointerIndex(pointer)\n const pointerInfo = interaction.pointers[pointerIndex]\n\n // do not fire a tap event if the pointer was moved before being lifted\n if (\n type === 'tap' &&\n (interaction.pointerWasMoved ||\n // or if the pointerup target is different to the pointerdown target\n !(pointerInfo && pointerInfo.downTarget === eventTarget))\n ) {\n return []\n }\n\n const path = domUtils.getPath(eventTarget as Element | Document)\n const signalArg = {\n interaction,\n pointer,\n event,\n eventTarget,\n type,\n path,\n targets: [] as EventTargetList,\n node: null,\n }\n\n for (const node of path) {\n signalArg.node = node\n\n scope.fire('pointerEvents:collect-targets', signalArg)\n }\n\n if (type === 'hold') {\n signalArg.targets = signalArg.targets.filter(\n (target) => target.eventable.options.holdDuration === interaction.pointers[pointerIndex]?.hold.duration,\n )\n }\n\n return signalArg.targets\n}\n\nfunction addInteractionProps ({ interaction }) {\n interaction.prevTap = null // the most recent tap event on this interaction\n interaction.tapTime = 0 // time of the most recent tap event\n}\n\nfunction addHoldInfo ({ down, pointerInfo }: SignalArgs['interactions:update-pointer']) {\n if (!down && pointerInfo.hold) {\n return\n }\n\n pointerInfo.hold = { duration: Infinity, timeout: null }\n}\n\nfunction clearHold ({ interaction, pointerIndex }) {\n const hold = interaction.pointers[pointerIndex].hold\n\n if (hold && hold.timeout) {\n clearTimeout(hold.timeout)\n hold.timeout = null\n }\n}\n\nfunction moveAndClearHold (arg: SignalArgs['interactions:move'], scope: Scope) {\n const { interaction, pointer, event, eventTarget, duplicate } = arg\n\n if (!duplicate && (!interaction.pointerIsDown || interaction.pointerWasMoved)) {\n if (interaction.pointerIsDown) {\n clearHold(arg)\n }\n\n fire(\n {\n interaction,\n pointer,\n event,\n eventTarget: eventTarget as Element,\n type: 'move',\n },\n scope,\n )\n }\n}\n\nfunction downAndStartHold (\n { interaction, pointer, event, eventTarget, pointerIndex }: SignalArgs['interactions:down'],\n scope: Scope,\n) {\n const timer = interaction.pointers[pointerIndex].hold\n const path = domUtils.getPath(eventTarget as Element | Document)\n const signalArg = {\n interaction,\n pointer,\n event,\n eventTarget,\n type: 'hold',\n targets: [] as EventTargetList,\n path,\n node: null,\n }\n\n for (const node of path) {\n signalArg.node = node\n\n scope.fire('pointerEvents:collect-targets', signalArg)\n }\n\n if (!signalArg.targets.length) return\n\n let minDuration = Infinity\n\n for (const target of signalArg.targets) {\n const holdDuration = target.eventable.options.holdDuration\n\n if (holdDuration < minDuration) {\n minDuration = holdDuration\n }\n }\n\n timer.duration = minDuration\n timer.timeout = setTimeout(() => {\n fire(\n {\n interaction,\n eventTarget,\n pointer,\n event,\n type: 'hold',\n },\n scope,\n )\n }, minDuration)\n}\n\nfunction tapAfterUp (\n { interaction, pointer, event, eventTarget }: SignalArgs['interactions:up'],\n scope: Scope,\n) {\n if (!interaction.pointerWasMoved) {\n fire({ interaction, eventTarget, pointer, event, type: 'tap' }, scope)\n }\n}\n\nfunction install (scope: Scope) {\n scope.pointerEvents = pointerEvents\n scope.defaults.actions.pointerEvents = pointerEvents.defaults\n extend(scope.actions.phaselessTypes, pointerEvents.types)\n}\n\nexport default pointerEvents\n", "import type Interaction from '@interactjs/core/Interaction'\nimport type { ListenerMap, Scope, SignalArgs, Plugin } from '@interactjs/core/scope'\n\nimport type PointerEvent from './PointerEvent'\nimport basePlugin from './base'\n\ndeclare module '@interactjs/core/Interaction' {\n interface Interaction {\n holdIntervalHandle?: any\n }\n}\n\ndeclare module '@interactjs/pointer-events/PointerEvent' {\n interface PointerEvent {\n count?: number\n }\n}\n\ndeclare module '@interactjs/pointer-events/base' {\n interface PointerEventOptions {\n holdRepeatInterval?: number\n }\n}\n\nfunction install (scope: Scope) {\n scope.usePlugin(basePlugin)\n\n const { pointerEvents } = scope\n\n // don't repeat by default\n pointerEvents.defaults.holdRepeatInterval = 0\n pointerEvents.types.holdrepeat = scope.actions.phaselessTypes.holdrepeat = true\n}\n\nfunction onNew ({ pointerEvent }: { pointerEvent: PointerEvent }) {\n if (pointerEvent.type !== 'hold') return\n\n pointerEvent.count = (pointerEvent.count || 0) + 1\n}\n\nfunction onFired (\n { interaction, pointerEvent, eventTarget, targets }: SignalArgs['pointerEvents:fired'],\n scope: Scope,\n) {\n if (pointerEvent.type !== 'hold' || !targets.length) return\n\n // get the repeat interval from the first eventable\n const interval = targets[0].eventable.options.holdRepeatInterval\n\n // don't repeat if the interval is 0 or less\n if (interval <= 0) return\n\n // set a timeout to fire the holdrepeat event\n interaction.holdIntervalHandle = setTimeout(() => {\n scope.pointerEvents.fire(\n {\n interaction,\n eventTarget,\n type: 'hold',\n pointer: pointerEvent,\n event: pointerEvent,\n },\n scope,\n )\n }, interval)\n}\n\nfunction endHoldRepeat ({ interaction }: { interaction: Interaction }) {\n // set the interaction's holdStopTime property\n // to stop further holdRepeat events\n if (interaction.holdIntervalHandle) {\n clearInterval(interaction.holdIntervalHandle)\n interaction.holdIntervalHandle = null\n }\n}\n\nconst holdRepeat: Plugin = {\n id: 'pointer-events/holdRepeat',\n install,\n listeners: ['move', 'up', 'cancel', 'endall'].reduce(\n (acc, enderTypes) => {\n ;(acc as any)[`pointerEvents:${enderTypes}`] = endHoldRepeat\n return acc\n },\n {\n 'pointerEvents:new': onNew,\n 'pointerEvents:fired': onFired,\n } as ListenerMap,\n ),\n}\n\nexport default holdRepeat\n", "import type { Interactable } from '@interactjs/core/Interactable'\nimport type { Scope, Plugin } from '@interactjs/core/scope'\nimport type { Element } from '@interactjs/core/types'\nimport extend from '@interactjs/utils/extend'\n\ndeclare module '@interactjs/core/Interactable' {\n interface Interactable {\n pointerEvents: typeof pointerEventsMethod\n __backCompatOption: (optionName: string, newValue: any) => any\n }\n}\n\nfunction install (scope: Scope) {\n const { Interactable } = scope\n\n Interactable.prototype.pointerEvents = pointerEventsMethod\n\n const __backCompatOption = Interactable.prototype._backCompatOption\n\n Interactable.prototype._backCompatOption = function (optionName, newValue) {\n const ret = __backCompatOption.call(this, optionName, newValue)\n\n if (ret === this) {\n this.events.options[optionName] = newValue\n }\n\n return ret\n }\n}\n\nfunction pointerEventsMethod (this: Interactable, options: any) {\n extend(this.events.options, options)\n\n return this\n}\n\nconst plugin: Plugin = {\n id: 'pointer-events/interactableTargets',\n install,\n listeners: {\n 'pointerEvents:collect-targets': ({ targets, node, type, eventTarget }, scope) => {\n scope.interactables.forEachMatch(node, (interactable: Interactable) => {\n const eventable = interactable.events\n const options = eventable.options\n\n if (\n eventable.types[type] &&\n eventable.types[type].length &&\n interactable.testIgnoreAllow(options, node, eventTarget)\n ) {\n targets.push({\n node,\n eventable,\n props: { interactable },\n })\n }\n })\n },\n\n 'interactable:new': ({ interactable }) => {\n interactable.events.getRect = function (element: Element) {\n return interactable.getRect(element)\n }\n },\n\n 'interactable:set': ({ interactable, options }, scope) => {\n extend(interactable.events.options, scope.pointerEvents.defaults)\n extend(interactable.events.options, options.pointerEvents || {})\n },\n },\n}\n\nexport default plugin\n", "import type { Plugin } from '@interactjs/core/scope'\n\nimport * as pointerEvents from './base'\nimport holdRepeat from './holdRepeat'\nimport interactableTargets from './interactableTargets'\n\nconst plugin: Plugin = {\n id: 'pointer-events',\n install (scope) {\n scope.usePlugin(pointerEvents)\n scope.usePlugin(holdRepeat)\n scope.usePlugin(interactableTargets)\n },\n}\n\nexport default plugin\n", "import type { Interactable } from '@interactjs/core/Interactable'\nimport type { DoAnyPhaseArg, Interaction } from '@interactjs/core/Interaction'\nimport type { Scope, Plugin } from '@interactjs/core/scope'\nimport type { ActionName, ActionProps, Element } from '@interactjs/core/types'\nimport * as arr from '@interactjs/utils/arr'\nimport is from '@interactjs/utils/is'\nimport { copyAction } from '@interactjs/utils/misc'\nimport * as pointerUtils from '@interactjs/utils/pointerUtils'\nimport { tlbrToXywh } from '@interactjs/utils/rect'\n\ndeclare module '@interactjs/core/scope' {\n interface SignalArgs {\n 'interactions:before-action-reflow': Omit\n 'interactions:action-reflow': DoAnyPhaseArg\n 'interactions:after-action-reflow': DoAnyPhaseArg\n }\n}\n\ndeclare module '@interactjs/core/Interactable' {\n interface Interactable {\n reflow: (action: ActionProps) => ReturnType\n }\n}\n\ndeclare module '@interactjs/core/Interaction' {\n interface Interaction {\n _reflowPromise: Promise\n _reflowResolve: (...args: unknown[]) => void\n }\n}\n\ndeclare module '@interactjs/core/InteractEvent' {\n interface PhaseMap {\n reflow?: true\n }\n}\n\nexport function install (scope: Scope) {\n const {\n /** @lends Interactable */\n Interactable,\n } = scope\n\n scope.actions.phases.reflow = true\n\n /**\n * ```js\n * const interactable = interact(target)\n * const drag = { name: drag, axis: 'x' }\n * const resize = { name: resize, edges: { left: true, bottom: true }\n *\n * interactable.reflow(drag)\n * interactable.reflow(resize)\n * ```\n *\n * Start an action sequence to re-apply modifiers, check drops, etc.\n *\n * @param { Object } action The action to begin\n * @param { string } action.name The name of the action\n * @returns { Promise } A promise that resolves to the `Interactable` when actions on all targets have ended\n */\n Interactable.prototype.reflow = function (action: ActionProps) {\n return doReflow(this, action, scope)\n }\n}\n\nfunction doReflow (\n interactable: Interactable,\n action: ActionProps,\n scope: Scope,\n): Promise {\n const elements = (\n is.string(interactable.target)\n ? arr.from(interactable._context.querySelectorAll(interactable.target))\n : [interactable.target]\n ) as Element[]\n\n // tslint:disable-next-line variable-name\n const Promise = (scope.window as any).Promise\n const promises: Array> | null = Promise ? [] : null\n\n for (const element of elements) {\n const rect = interactable.getRect(element as HTMLElement | SVGElement)\n\n if (!rect) {\n break\n }\n\n const runningInteraction = arr.find(scope.interactions.list, (interaction: Interaction) => {\n return (\n interaction.interacting() &&\n interaction.interactable === interactable &&\n interaction.element === element &&\n interaction.prepared.name === action.name\n )\n })\n let reflowPromise: Promise\n\n if (runningInteraction) {\n runningInteraction.move()\n\n if (promises) {\n reflowPromise =\n runningInteraction._reflowPromise ||\n new Promise((resolve: any) => {\n runningInteraction._reflowResolve = resolve\n })\n }\n } else {\n const xywh = tlbrToXywh(rect)\n const coords = {\n page: { x: xywh.x, y: xywh.y },\n client: { x: xywh.x, y: xywh.y },\n timeStamp: scope.now(),\n }\n\n const event = pointerUtils.coordsToEvent(coords)\n reflowPromise = startReflow(scope, interactable, element, action, event)\n }\n\n if (promises) {\n promises.push(reflowPromise)\n }\n }\n\n return promises && Promise.all(promises).then(() => interactable)\n}\n\nfunction startReflow (\n scope: Scope,\n interactable: Interactable,\n element: Element,\n action: ActionProps,\n event: any,\n) {\n const interaction = scope.interactions.new({ pointerType: 'reflow' })\n const signalArg = {\n interaction,\n event,\n pointer: event,\n eventTarget: element,\n phase: 'reflow',\n } as const\n\n interaction.interactable = interactable\n interaction.element = element\n interaction.prevEvent = event\n interaction.updatePointer(event, event, element, true)\n pointerUtils.setZeroCoords(interaction.coords.delta)\n\n copyAction(interaction.prepared, action)\n interaction._doPhase(signalArg)\n\n const { Promise } = scope.window as unknown as { Promise: PromiseConstructor }\n const reflowPromise = Promise\n ? new Promise((resolve) => {\n interaction._reflowResolve = resolve\n })\n : undefined\n\n interaction._reflowPromise = reflowPromise\n interaction.start(action, interactable, element)\n\n if (interaction._interacting) {\n interaction.move(signalArg)\n interaction.end(event)\n } else {\n interaction.stop()\n interaction._reflowResolve()\n }\n\n interaction.removePointer(event, event)\n\n return reflowPromise\n}\n\nconst reflow: Plugin = {\n id: 'reflow',\n install,\n listeners: {\n // remove completed reflow interactions\n 'interactions:stop': ({ interaction }, scope) => {\n if (interaction.pointerType === 'reflow') {\n if (interaction._reflowResolve) {\n interaction._reflowResolve()\n }\n\n arr.remove(scope.interactions.list, interaction)\n }\n },\n },\n}\n\nexport default reflow\n", "import actions from '@interactjs/actions/plugin'\nimport autoScroll from '@interactjs/auto-scroll/plugin'\nimport autoStart from '@interactjs/auto-start/plugin'\nimport interactablePreventDefault from '@interactjs/core/interactablePreventDefault'\nimport devTools from '@interactjs/dev-tools/plugin'\nimport inertia from '@interactjs/inertia/plugin'\nimport interact from '@interactjs/interact'\nimport modifiers from '@interactjs/modifiers/plugin'\nimport offset from '@interactjs/offset/plugin'\nimport pointerEvents from '@interactjs/pointer-events/plugin'\nimport reflow from '@interactjs/reflow/plugin'\n\ninteract.use(interactablePreventDefault)\n\ninteract.use(offset)\n\n// pointerEvents\ninteract.use(pointerEvents)\n\n// inertia\ninteract.use(inertia)\n\n// snap, resize, etc.\ninteract.use(modifiers)\n\n// autoStart, hold\ninteract.use(autoStart)\n\n// drag and drop, resize, gesture\ninteract.use(actions)\n\n// autoScroll\ninteract.use(autoScroll)\n\n// reflow\ninteract.use(reflow)\n\n// eslint-disable-next-line no-undef\nif (process.env.NODE_ENV !== 'production') {\n interact.use(devTools)\n}\n\nexport default interact\n\nif (typeof module === 'object' && !!module) {\n try {\n module.exports = interact\n } catch {}\n}\n\n;(interact as any).default = interact\n", "// eslint-disable-next-line import/no-extraneous-dependencies\nimport interact from '@interactjs/interactjs/index'\n\nexport default interact\n\nif (typeof module === 'object' && !!module) {\n try {\n module.exports = interact\n } catch {}\n}\n\n;(interact as any).default = interact\n", "\nreturn _$index_80;\n\n});\n", "!(function(win) {\n\n/**\n * FastDom\n *\n * Eliminates layout thrashing\n * by batching DOM read/write\n * interactions.\n *\n * @author Wilson Page \n * @author Kornel Lesinski \n */\n\n'use strict';\n\n/**\n * Mini logger\n *\n * @return {Function}\n */\nvar debug = 0 ? console.log.bind(console, '[fastdom]') : function() {};\n\n/**\n * Normalized rAF\n *\n * @type {Function}\n */\nvar raf = win.requestAnimationFrame\n || win.webkitRequestAnimationFrame\n || win.mozRequestAnimationFrame\n || win.msRequestAnimationFrame\n || function(cb) { return setTimeout(cb, 16); };\n\n/**\n * Initialize a `FastDom`.\n *\n * @constructor\n */\nfunction FastDom() {\n var self = this;\n self.reads = [];\n self.writes = [];\n self.raf = raf.bind(win); // test hook\n debug('initialized', self);\n}\n\nFastDom.prototype = {\n constructor: FastDom,\n\n /**\n * We run this inside a try catch\n * so that if any jobs error, we\n * are able to recover and continue\n * to flush the batch until it's empty.\n *\n * @param {Array} tasks\n */\n runTasks: function(tasks) {\n debug('run tasks');\n var task; while (task = tasks.shift()) task();\n },\n\n /**\n * Adds a job to the read batch and\n * schedules a new frame if need be.\n *\n * @param {Function} fn\n * @param {Object} ctx the context to be bound to `fn` (optional).\n * @public\n */\n measure: function(fn, ctx) {\n debug('measure');\n var task = !ctx ? fn : fn.bind(ctx);\n this.reads.push(task);\n scheduleFlush(this);\n return task;\n },\n\n /**\n * Adds a job to the\n * write batch and schedules\n * a new frame if need be.\n *\n * @param {Function} fn\n * @param {Object} ctx the context to be bound to `fn` (optional).\n * @public\n */\n mutate: function(fn, ctx) {\n debug('mutate');\n var task = !ctx ? fn : fn.bind(ctx);\n this.writes.push(task);\n scheduleFlush(this);\n return task;\n },\n\n /**\n * Clears a scheduled 'read' or 'write' task.\n *\n * @param {Object} task\n * @return {Boolean} success\n * @public\n */\n clear: function(task) {\n debug('clear', task);\n return remove(this.reads, task) || remove(this.writes, task);\n },\n\n /**\n * Extend this FastDom with some\n * custom functionality.\n *\n * Because fastdom must *always* be a\n * singleton, we're actually extending\n * the fastdom instance. This means tasks\n * scheduled by an extension still enter\n * fastdom's global task queue.\n *\n * The 'super' instance can be accessed\n * from `this.fastdom`.\n *\n * @example\n *\n * var myFastdom = fastdom.extend({\n * initialize: function() {\n * // runs on creation\n * },\n *\n * // override a method\n * measure: function(fn) {\n * // do extra stuff ...\n *\n * // then call the original\n * return this.fastdom.measure(fn);\n * },\n *\n * ...\n * });\n *\n * @param {Object} props properties to mixin\n * @return {FastDom}\n */\n extend: function(props) {\n debug('extend', props);\n if (typeof props != 'object') throw new Error('expected object');\n\n var child = Object.create(this);\n mixin(child, props);\n child.fastdom = this;\n\n // run optional creation hook\n if (child.initialize) child.initialize();\n\n return child;\n },\n\n // override this with a function\n // to prevent Errors in console\n // when tasks throw\n catch: null\n};\n\n/**\n * Schedules a new read/write\n * batch if one isn't pending.\n *\n * @private\n */\nfunction scheduleFlush(fastdom) {\n if (!fastdom.scheduled) {\n fastdom.scheduled = true;\n fastdom.raf(flush.bind(null, fastdom));\n debug('flush scheduled');\n }\n}\n\n/**\n * Runs queued `read` and `write` tasks.\n *\n * Errors are caught and thrown by default.\n * If a `.catch` function has been defined\n * it is called instead.\n *\n * @private\n */\nfunction flush(fastdom) {\n debug('flush');\n\n var writes = fastdom.writes;\n var reads = fastdom.reads;\n var error;\n\n try {\n debug('flushing reads', reads.length);\n fastdom.runTasks(reads);\n debug('flushing writes', writes.length);\n fastdom.runTasks(writes);\n } catch (e) { error = e; }\n\n fastdom.scheduled = false;\n\n // If the batch errored we may still have tasks queued\n if (reads.length || writes.length) scheduleFlush(fastdom);\n\n if (error) {\n debug('task errored', error.message);\n if (fastdom.catch) fastdom.catch(error);\n else throw error;\n }\n}\n\n/**\n * Remove an item from an Array.\n *\n * @param {Array} array\n * @param {*} item\n * @return {Boolean}\n */\nfunction remove(array, item) {\n var index = array.indexOf(item);\n return !!~index && !!array.splice(index, 1);\n}\n\n/**\n * Mixin own properties of source\n * object into the target.\n *\n * @param {Object} target\n * @param {Object} source\n */\nfunction mixin(target, source) {\n for (var key in source) {\n if (source.hasOwnProperty(key)) target[key] = source[key];\n }\n}\n\n// There should never be more than\n// one instance of `FastDom` in an app\nvar exports = win.fastdom = (win.fastdom || new FastDom()); // jshint ignore:line\n\n// Expose to CJS & AMD\nif ((typeof define) == 'function') define(function() { return exports; });\nelse if ((typeof module) == 'object') module.exports = exports;\n\n})( typeof window !== 'undefined' ? window : this);\n", "/**\n * @license Complex.js v2.1.1 12/05/2020\n *\n * Copyright (c) 2020, Robert Eisele (robert@xarg.org)\n * Dual licensed under the MIT or GPL Version 2 licenses.\n **/\n\n/**\n *\n * This class allows the manipulation of complex numbers.\n * You can pass a complex number in different formats. Either as object, double, string or two integer parameters.\n *\n * Object form\n * { re: , im: }\n * { arg: , abs: }\n * { phi: , r: }\n *\n * Array / Vector form\n * [ real, imaginary ]\n *\n * Double form\n * 99.3 - Single double value\n *\n * String form\n * '23.1337' - Simple real number\n * '15+3i' - a simple complex number\n * '3-i' - a simple complex number\n *\n * Example:\n *\n * var c = new Complex('99.3+8i');\n * c.mul({r: 3, i: 9}).div(4.9).sub(3, 2);\n *\n */\n\n(function(root) {\n\n 'use strict';\n\n var cosh = Math.cosh || function(x) {\n return Math.abs(x) < 1e-9 ? 1 - x : (Math.exp(x) + Math.exp(-x)) * 0.5;\n };\n\n var sinh = Math.sinh || function(x) {\n return Math.abs(x) < 1e-9 ? x : (Math.exp(x) - Math.exp(-x)) * 0.5;\n };\n\n /**\n * Calculates cos(x) - 1 using Taylor series if x is small (-\u00BC\u03C0 \u2264 x \u2264 \u00BC\u03C0).\n *\n * @param {number} x\n * @returns {number} cos(x) - 1\n */\n var cosm1 = function(x) {\n\n var b = Math.PI / 4;\n if (-b > x || x > b) {\n return Math.cos(x) - 1.0;\n }\n\n /* Calculate horner form of polynomial of taylor series in Q\n var fac = 1, alt = 1, pol = {};\n for (var i = 0; i <= 16; i++) {\n fac*= i || 1;\n if (i % 2 == 0) {\n pol[i] = new Fraction(1, alt * fac);\n alt = -alt;\n }\n }\n console.log(new Polynomial(pol).toHorner()); // (((((((1/20922789888000x^2-1/87178291200)x^2+1/479001600)x^2-1/3628800)x^2+1/40320)x^2-1/720)x^2+1/24)x^2-1/2)x^2+1\n */\n\n var xx = x * x;\n return xx * (\n xx * (\n xx * (\n xx * (\n xx * (\n xx * (\n xx * (\n xx / 20922789888000\n - 1 / 87178291200)\n + 1 / 479001600)\n - 1 / 3628800)\n + 1 / 40320)\n - 1 / 720)\n + 1 / 24)\n - 1 / 2);\n };\n\n var hypot = function(x, y) {\n\n var a = Math.abs(x);\n var b = Math.abs(y);\n\n if (a < 3000 && b < 3000) {\n return Math.sqrt(a * a + b * b);\n }\n\n if (a < b) {\n a = b;\n b = x / y;\n } else {\n b = y / x;\n }\n return a * Math.sqrt(1 + b * b);\n };\n\n var parser_exit = function() {\n throw SyntaxError('Invalid Param');\n };\n\n /**\n * Calculates log(sqrt(a^2+b^2)) in a way to avoid overflows\n *\n * @param {number} a\n * @param {number} b\n * @returns {number}\n */\n function logHypot(a, b) {\n\n var _a = Math.abs(a);\n var _b = Math.abs(b);\n\n if (a === 0) {\n return Math.log(_b);\n }\n\n if (b === 0) {\n return Math.log(_a);\n }\n\n if (_a < 3000 && _b < 3000) {\n return Math.log(a * a + b * b) * 0.5;\n }\n\n /* I got 4 ideas to compute this property without overflow:\n *\n * Testing 1000000 times with random samples for a,b \u2208 [1, 1000000000] against a big decimal library to get an error estimate\n *\n * 1. Only eliminate the square root: (OVERALL ERROR: 3.9122483030951116e-11)\n\n Math.log(a * a + b * b) / 2\n\n *\n *\n * 2. Try to use the non-overflowing pythagoras: (OVERALL ERROR: 8.889760039210159e-10)\n\n var fn = function(a, b) {\n a = Math.abs(a);\n b = Math.abs(b);\n var t = Math.min(a, b);\n a = Math.max(a, b);\n t = t / a;\n\n return Math.log(a) + Math.log(1 + t * t) / 2;\n };\n\n * 3. Abuse the identity cos(atan(y/x) = x / sqrt(x^2+y^2): (OVERALL ERROR: 3.4780178737037204e-10)\n\n Math.log(a / Math.cos(Math.atan2(b, a)))\n\n * 4. Use 3. and apply log rules: (OVERALL ERROR: 1.2014087502620896e-9)\n\n Math.log(a) - Math.log(Math.cos(Math.atan2(b, a)))\n\n */\n\n a = a / 2;\n b = b / 2;\n\n return 0.5 * Math.log(a * a + b * b) + Math.LN2;\n }\n\n var parse = function(a, b) {\n\n var z = { 're': 0, 'im': 0 };\n\n if (a === undefined || a === null) {\n z['re'] =\n z['im'] = 0;\n } else if (b !== undefined) {\n z['re'] = a;\n z['im'] = b;\n } else\n switch (typeof a) {\n\n case 'object':\n\n if ('im' in a && 're' in a) {\n z['re'] = a['re'];\n z['im'] = a['im'];\n } else if ('abs' in a && 'arg' in a) {\n if (!Number.isFinite(a['abs']) && Number.isFinite(a['arg'])) {\n return Complex['INFINITY'];\n }\n z['re'] = a['abs'] * Math.cos(a['arg']);\n z['im'] = a['abs'] * Math.sin(a['arg']);\n } else if ('r' in a && 'phi' in a) {\n if (!Number.isFinite(a['r']) && Number.isFinite(a['phi'])) {\n return Complex['INFINITY'];\n }\n z['re'] = a['r'] * Math.cos(a['phi']);\n z['im'] = a['r'] * Math.sin(a['phi']);\n } else if (a.length === 2) { // Quick array check\n z['re'] = a[0];\n z['im'] = a[1];\n } else {\n parser_exit();\n }\n break;\n\n case 'string':\n\n z['im'] = /* void */\n z['re'] = 0;\n\n var tokens = a.match(/\\d+\\.?\\d*e[+-]?\\d+|\\d+\\.?\\d*|\\.\\d+|./g);\n var plus = 1;\n var minus = 0;\n\n if (tokens === null) {\n parser_exit();\n }\n\n for (var i = 0; i < tokens.length; i++) {\n\n var c = tokens[i];\n\n if (c === ' ' || c === '\\t' || c === '\\n') {\n /* void */\n } else if (c === '+') {\n plus++;\n } else if (c === '-') {\n minus++;\n } else if (c === 'i' || c === 'I') {\n\n if (plus + minus === 0) {\n parser_exit();\n }\n\n if (tokens[i + 1] !== ' ' && !isNaN(tokens[i + 1])) {\n z['im'] += parseFloat((minus % 2 ? '-' : '') + tokens[i + 1]);\n i++;\n } else {\n z['im'] += parseFloat((minus % 2 ? '-' : '') + '1');\n }\n plus = minus = 0;\n\n } else {\n\n if (plus + minus === 0 || isNaN(c)) {\n parser_exit();\n }\n\n if (tokens[i + 1] === 'i' || tokens[i + 1] === 'I') {\n z['im'] += parseFloat((minus % 2 ? '-' : '') + c);\n i++;\n } else {\n z['re'] += parseFloat((minus % 2 ? '-' : '') + c);\n }\n plus = minus = 0;\n }\n }\n\n // Still something on the stack\n if (plus + minus > 0) {\n parser_exit();\n }\n break;\n\n case 'number':\n z['im'] = 0;\n z['re'] = a;\n break;\n\n default:\n parser_exit();\n }\n\n if (isNaN(z['re']) || isNaN(z['im'])) {\n // If a calculation is NaN, we treat it as NaN and don't throw\n //parser_exit();\n }\n\n return z;\n };\n\n /**\n * @constructor\n * @returns {Complex}\n */\n function Complex(a, b) {\n\n if (!(this instanceof Complex)) {\n return new Complex(a, b);\n }\n\n var z = parse(a, b);\n\n this['re'] = z['re'];\n this['im'] = z['im'];\n }\n\n Complex.prototype = {\n\n 're': 0,\n 'im': 0,\n\n /**\n * Calculates the sign of a complex number, which is a normalized complex\n *\n * @returns {Complex}\n */\n 'sign': function() {\n\n var abs = this['abs']();\n\n return new Complex(\n this['re'] / abs,\n this['im'] / abs);\n },\n\n /**\n * Adds two complex numbers\n *\n * @returns {Complex}\n */\n 'add': function(a, b) {\n\n var z = new Complex(a, b);\n\n // Infinity + Infinity = NaN\n if (this['isInfinite']() && z['isInfinite']()) {\n return Complex['NAN'];\n }\n\n // Infinity + z = Infinity { where z != Infinity }\n if (this['isInfinite']() || z['isInfinite']()) {\n return Complex['INFINITY'];\n }\n\n return new Complex(\n this['re'] + z['re'],\n this['im'] + z['im']);\n },\n\n /**\n * Subtracts two complex numbers\n *\n * @returns {Complex}\n */\n 'sub': function(a, b) {\n\n var z = new Complex(a, b);\n\n // Infinity - Infinity = NaN\n if (this['isInfinite']() && z['isInfinite']()) {\n return Complex['NAN'];\n }\n\n // Infinity - z = Infinity { where z != Infinity }\n if (this['isInfinite']() || z['isInfinite']()) {\n return Complex['INFINITY'];\n }\n\n return new Complex(\n this['re'] - z['re'],\n this['im'] - z['im']);\n },\n\n /**\n * Multiplies two complex numbers\n *\n * @returns {Complex}\n */\n 'mul': function(a, b) {\n\n var z = new Complex(a, b);\n\n // Infinity * 0 = NaN\n if ((this['isInfinite']() && z['isZero']()) || (this['isZero']() && z['isInfinite']())) {\n return Complex['NAN'];\n }\n\n // Infinity * z = Infinity { where z != 0 }\n if (this['isInfinite']() || z['isInfinite']()) {\n return Complex['INFINITY'];\n }\n\n // Short circuit for real values\n if (z['im'] === 0 && this['im'] === 0) {\n return new Complex(this['re'] * z['re'], 0);\n }\n\n return new Complex(\n this['re'] * z['re'] - this['im'] * z['im'],\n this['re'] * z['im'] + this['im'] * z['re']);\n },\n\n /**\n * Divides two complex numbers\n *\n * @returns {Complex}\n */\n 'div': function(a, b) {\n\n var z = new Complex(a, b);\n\n // 0 / 0 = NaN and Infinity / Infinity = NaN\n if ((this['isZero']() && z['isZero']()) || (this['isInfinite']() && z['isInfinite']())) {\n return Complex['NAN'];\n }\n\n // Infinity / 0 = Infinity\n if (this['isInfinite']() || z['isZero']()) {\n return Complex['INFINITY'];\n }\n\n // 0 / Infinity = 0\n if (this['isZero']() || z['isInfinite']()) {\n return Complex['ZERO'];\n }\n\n a = this['re'];\n b = this['im'];\n\n var c = z['re'];\n var d = z['im'];\n var t, x;\n\n if (0 === d) {\n // Divisor is real\n return new Complex(a / c, b / c);\n }\n\n if (Math.abs(c) < Math.abs(d)) {\n\n x = c / d;\n t = c * x + d;\n\n return new Complex(\n (a * x + b) / t,\n (b * x - a) / t);\n\n } else {\n\n x = d / c;\n t = d * x + c;\n\n return new Complex(\n (a + b * x) / t,\n (b - a * x) / t);\n }\n },\n\n /**\n * Calculate the power of two complex numbers\n *\n * @returns {Complex}\n */\n 'pow': function(a, b) {\n\n var z = new Complex(a, b);\n\n a = this['re'];\n b = this['im'];\n\n if (z['isZero']()) {\n return Complex['ONE'];\n }\n\n // If the exponent is real\n if (z['im'] === 0) {\n\n if (b === 0 && a > 0) {\n\n return new Complex(Math.pow(a, z['re']), 0);\n\n } else if (a === 0) { // If base is fully imaginary\n\n switch ((z['re'] % 4 + 4) % 4) {\n case 0:\n return new Complex(Math.pow(b, z['re']), 0);\n case 1:\n return new Complex(0, Math.pow(b, z['re']));\n case 2:\n return new Complex(-Math.pow(b, z['re']), 0);\n case 3:\n return new Complex(0, -Math.pow(b, z['re']));\n }\n }\n }\n\n /* I couldn't find a good formula, so here is a derivation and optimization\n *\n * z_1^z_2 = (a + bi)^(c + di)\n * = exp((c + di) * log(a + bi)\n * = pow(a^2 + b^2, (c + di) / 2) * exp(i(c + di)atan2(b, a))\n * =>...\n * Re = (pow(a^2 + b^2, c / 2) * exp(-d * atan2(b, a))) * cos(d * log(a^2 + b^2) / 2 + c * atan2(b, a))\n * Im = (pow(a^2 + b^2, c / 2) * exp(-d * atan2(b, a))) * sin(d * log(a^2 + b^2) / 2 + c * atan2(b, a))\n *\n * =>...\n * Re = exp(c * log(sqrt(a^2 + b^2)) - d * atan2(b, a)) * cos(d * log(sqrt(a^2 + b^2)) + c * atan2(b, a))\n * Im = exp(c * log(sqrt(a^2 + b^2)) - d * atan2(b, a)) * sin(d * log(sqrt(a^2 + b^2)) + c * atan2(b, a))\n *\n * =>\n * Re = exp(c * logsq2 - d * arg(z_1)) * cos(d * logsq2 + c * arg(z_1))\n * Im = exp(c * logsq2 - d * arg(z_1)) * sin(d * logsq2 + c * arg(z_1))\n *\n */\n\n if (a === 0 && b === 0 && z['re'] > 0 && z['im'] >= 0) {\n return Complex['ZERO'];\n }\n\n var arg = Math.atan2(b, a);\n var loh = logHypot(a, b);\n\n a = Math.exp(z['re'] * loh - z['im'] * arg);\n b = z['im'] * loh + z['re'] * arg;\n return new Complex(\n a * Math.cos(b),\n a * Math.sin(b));\n },\n\n /**\n * Calculate the complex square root\n *\n * @returns {Complex}\n */\n 'sqrt': function() {\n\n var a = this['re'];\n var b = this['im'];\n var r = this['abs']();\n\n var re, im;\n\n if (a >= 0) {\n\n if (b === 0) {\n return new Complex(Math.sqrt(a), 0);\n }\n\n re = 0.5 * Math.sqrt(2.0 * (r + a));\n } else {\n re = Math.abs(b) / Math.sqrt(2 * (r - a));\n }\n\n if (a <= 0) {\n im = 0.5 * Math.sqrt(2.0 * (r - a));\n } else {\n im = Math.abs(b) / Math.sqrt(2 * (r + a));\n }\n\n return new Complex(re, b < 0 ? -im : im);\n },\n\n /**\n * Calculate the complex exponent\n *\n * @returns {Complex}\n */\n 'exp': function() {\n\n var tmp = Math.exp(this['re']);\n\n if (this['im'] === 0) {\n //return new Complex(tmp, 0);\n }\n return new Complex(\n tmp * Math.cos(this['im']),\n tmp * Math.sin(this['im']));\n },\n\n /**\n * Calculate the complex exponent and subtracts one.\n *\n * This may be more accurate than `Complex(x).exp().sub(1)` if\n * `x` is small.\n *\n * @returns {Complex}\n */\n 'expm1': function() {\n\n /**\n * exp(a + i*b) - 1\n = exp(a) * (cos(b) + j*sin(b)) - 1\n = expm1(a)*cos(b) + cosm1(b) + j*exp(a)*sin(b)\n */\n\n var a = this['re'];\n var b = this['im'];\n\n return new Complex(\n Math.expm1(a) * Math.cos(b) + cosm1(b),\n Math.exp(a) * Math.sin(b));\n },\n\n /**\n * Calculate the natural log\n *\n * @returns {Complex}\n */\n 'log': function() {\n\n var a = this['re'];\n var b = this['im'];\n\n if (b === 0 && a > 0) {\n //return new Complex(Math.log(a), 0);\n }\n\n return new Complex(\n logHypot(a, b),\n Math.atan2(b, a));\n },\n\n /**\n * Calculate the magnitude of the complex number\n *\n * @returns {number}\n */\n 'abs': function() {\n\n return hypot(this['re'], this['im']);\n },\n\n /**\n * Calculate the angle of the complex number\n *\n * @returns {number}\n */\n 'arg': function() {\n\n return Math.atan2(this['im'], this['re']);\n },\n\n /**\n * Calculate the sine of the complex number\n *\n * @returns {Complex}\n */\n 'sin': function() {\n\n // sin(z) = ( e^iz - e^-iz ) / 2i \n // = sin(a)cosh(b) + i cos(a)sinh(b)\n\n var a = this['re'];\n var b = this['im'];\n\n return new Complex(\n Math.sin(a) * cosh(b),\n Math.cos(a) * sinh(b));\n },\n\n /**\n * Calculate the cosine\n *\n * @returns {Complex}\n */\n 'cos': function() {\n\n // cos(z) = ( e^iz + e^-iz ) / 2 \n // = cos(a)cosh(b) - i sin(a)sinh(b)\n\n var a = this['re'];\n var b = this['im'];\n\n return new Complex(\n Math.cos(a) * cosh(b),\n -Math.sin(a) * sinh(b));\n },\n\n /**\n * Calculate the tangent\n *\n * @returns {Complex}\n */\n 'tan': function() {\n\n // tan(z) = sin(z) / cos(z) \n // = ( e^iz - e^-iz ) / ( i( e^iz + e^-iz ) )\n // = ( e^2iz - 1 ) / i( e^2iz + 1 )\n // = ( sin(2a) + i sinh(2b) ) / ( cos(2a) + cosh(2b) )\n\n var a = 2 * this['re'];\n var b = 2 * this['im'];\n var d = Math.cos(a) + cosh(b);\n\n return new Complex(\n Math.sin(a) / d,\n sinh(b) / d);\n },\n\n /**\n * Calculate the cotangent\n *\n * @returns {Complex}\n */\n 'cot': function() {\n\n // cot(c) = i(e^(ci) + e^(-ci)) / (e^(ci) - e^(-ci))\n\n var a = 2 * this['re'];\n var b = 2 * this['im'];\n var d = Math.cos(a) - cosh(b);\n\n return new Complex(\n -Math.sin(a) / d,\n sinh(b) / d);\n },\n\n /**\n * Calculate the secant\n *\n * @returns {Complex}\n */\n 'sec': function() {\n\n // sec(c) = 2 / (e^(ci) + e^(-ci))\n\n var a = this['re'];\n var b = this['im'];\n var d = 0.5 * cosh(2 * b) + 0.5 * Math.cos(2 * a);\n\n return new Complex(\n Math.cos(a) * cosh(b) / d,\n Math.sin(a) * sinh(b) / d);\n },\n\n /**\n * Calculate the cosecans\n *\n * @returns {Complex}\n */\n 'csc': function() {\n\n // csc(c) = 2i / (e^(ci) - e^(-ci))\n\n var a = this['re'];\n var b = this['im'];\n var d = 0.5 * cosh(2 * b) - 0.5 * Math.cos(2 * a);\n\n return new Complex(\n Math.sin(a) * cosh(b) / d,\n -Math.cos(a) * sinh(b) / d);\n },\n\n /**\n * Calculate the complex arcus sinus\n *\n * @returns {Complex}\n */\n 'asin': function() {\n\n // asin(c) = -i * log(ci + sqrt(1 - c^2))\n\n var a = this['re'];\n var b = this['im'];\n\n var t1 = new Complex(\n b * b - a * a + 1,\n -2 * a * b)['sqrt']();\n\n var t2 = new Complex(\n t1['re'] - b,\n t1['im'] + a)['log']();\n\n return new Complex(t2['im'], -t2['re']);\n },\n\n /**\n * Calculate the complex arcus cosinus\n *\n * @returns {Complex}\n */\n 'acos': function() {\n\n // acos(c) = i * log(c - i * sqrt(1 - c^2))\n\n var a = this['re'];\n var b = this['im'];\n\n var t1 = new Complex(\n b * b - a * a + 1,\n -2 * a * b)['sqrt']();\n\n var t2 = new Complex(\n t1['re'] - b,\n t1['im'] + a)['log']();\n\n return new Complex(Math.PI / 2 - t2['im'], t2['re']);\n },\n\n /**\n * Calculate the complex arcus tangent\n *\n * @returns {Complex}\n */\n 'atan': function() {\n\n // atan(c) = i / 2 log((i + x) / (i - x))\n\n var a = this['re'];\n var b = this['im'];\n\n if (a === 0) {\n\n if (b === 1) {\n return new Complex(0, Infinity);\n }\n\n if (b === -1) {\n return new Complex(0, -Infinity);\n }\n }\n\n var d = a * a + (1.0 - b) * (1.0 - b);\n\n var t1 = new Complex(\n (1 - b * b - a * a) / d,\n -2 * a / d).log();\n\n return new Complex(-0.5 * t1['im'], 0.5 * t1['re']);\n },\n\n /**\n * Calculate the complex arcus cotangent\n *\n * @returns {Complex}\n */\n 'acot': function() {\n\n // acot(c) = i / 2 log((c - i) / (c + i))\n\n var a = this['re'];\n var b = this['im'];\n\n if (b === 0) {\n return new Complex(Math.atan2(1, a), 0);\n }\n\n var d = a * a + b * b;\n return (d !== 0)\n ? new Complex(\n a / d,\n -b / d).atan()\n : new Complex(\n (a !== 0) ? a / 0 : 0,\n (b !== 0) ? -b / 0 : 0).atan();\n },\n\n /**\n * Calculate the complex arcus secant\n *\n * @returns {Complex}\n */\n 'asec': function() {\n\n // asec(c) = -i * log(1 / c + sqrt(1 - i / c^2))\n\n var a = this['re'];\n var b = this['im'];\n\n if (a === 0 && b === 0) {\n return new Complex(0, Infinity);\n }\n\n var d = a * a + b * b;\n return (d !== 0)\n ? new Complex(\n a / d,\n -b / d).acos()\n : new Complex(\n (a !== 0) ? a / 0 : 0,\n (b !== 0) ? -b / 0 : 0).acos();\n },\n\n /**\n * Calculate the complex arcus cosecans\n *\n * @returns {Complex}\n */\n 'acsc': function() {\n\n // acsc(c) = -i * log(i / c + sqrt(1 - 1 / c^2))\n\n var a = this['re'];\n var b = this['im'];\n\n if (a === 0 && b === 0) {\n return new Complex(Math.PI / 2, Infinity);\n }\n\n var d = a * a + b * b;\n return (d !== 0)\n ? new Complex(\n a / d,\n -b / d).asin()\n : new Complex(\n (a !== 0) ? a / 0 : 0,\n (b !== 0) ? -b / 0 : 0).asin();\n },\n\n /**\n * Calculate the complex sinh\n *\n * @returns {Complex}\n */\n 'sinh': function() {\n\n // sinh(c) = (e^c - e^-c) / 2\n\n var a = this['re'];\n var b = this['im'];\n\n return new Complex(\n sinh(a) * Math.cos(b),\n cosh(a) * Math.sin(b));\n },\n\n /**\n * Calculate the complex cosh\n *\n * @returns {Complex}\n */\n 'cosh': function() {\n\n // cosh(c) = (e^c + e^-c) / 2\n\n var a = this['re'];\n var b = this['im'];\n\n return new Complex(\n cosh(a) * Math.cos(b),\n sinh(a) * Math.sin(b));\n },\n\n /**\n * Calculate the complex tanh\n *\n * @returns {Complex}\n */\n 'tanh': function() {\n\n // tanh(c) = (e^c - e^-c) / (e^c + e^-c)\n\n var a = 2 * this['re'];\n var b = 2 * this['im'];\n var d = cosh(a) + Math.cos(b);\n\n return new Complex(\n sinh(a) / d,\n Math.sin(b) / d);\n },\n\n /**\n * Calculate the complex coth\n *\n * @returns {Complex}\n */\n 'coth': function() {\n\n // coth(c) = (e^c + e^-c) / (e^c - e^-c)\n\n var a = 2 * this['re'];\n var b = 2 * this['im'];\n var d = cosh(a) - Math.cos(b);\n\n return new Complex(\n sinh(a) / d,\n -Math.sin(b) / d);\n },\n\n /**\n * Calculate the complex coth\n *\n * @returns {Complex}\n */\n 'csch': function() {\n\n // csch(c) = 2 / (e^c - e^-c)\n\n var a = this['re'];\n var b = this['im'];\n var d = Math.cos(2 * b) - cosh(2 * a);\n\n return new Complex(\n -2 * sinh(a) * Math.cos(b) / d,\n 2 * cosh(a) * Math.sin(b) / d);\n },\n\n /**\n * Calculate the complex sech\n *\n * @returns {Complex}\n */\n 'sech': function() {\n\n // sech(c) = 2 / (e^c + e^-c)\n\n var a = this['re'];\n var b = this['im'];\n var d = Math.cos(2 * b) + cosh(2 * a);\n\n return new Complex(\n 2 * cosh(a) * Math.cos(b) / d,\n -2 * sinh(a) * Math.sin(b) / d);\n },\n\n /**\n * Calculate the complex asinh\n *\n * @returns {Complex}\n */\n 'asinh': function() {\n\n // asinh(c) = log(c + sqrt(c^2 + 1))\n\n var tmp = this['im'];\n this['im'] = -this['re'];\n this['re'] = tmp;\n var res = this['asin']();\n\n this['re'] = -this['im'];\n this['im'] = tmp;\n tmp = res['re'];\n\n res['re'] = -res['im'];\n res['im'] = tmp;\n return res;\n },\n\n /**\n * Calculate the complex acosh\n *\n * @returns {Complex}\n */\n 'acosh': function() {\n\n // acosh(c) = log(c + sqrt(c^2 - 1))\n\n var res = this['acos']();\n if (res['im'] <= 0) {\n var tmp = res['re'];\n res['re'] = -res['im'];\n res['im'] = tmp;\n } else {\n var tmp = res['im'];\n res['im'] = -res['re'];\n res['re'] = tmp;\n }\n return res;\n },\n\n /**\n * Calculate the complex atanh\n *\n * @returns {Complex}\n */\n 'atanh': function() {\n\n // atanh(c) = log((1+c) / (1-c)) / 2\n\n var a = this['re'];\n var b = this['im'];\n\n var noIM = a > 1 && b === 0;\n var oneMinus = 1 - a;\n var onePlus = 1 + a;\n var d = oneMinus * oneMinus + b * b;\n\n var x = (d !== 0)\n ? new Complex(\n (onePlus * oneMinus - b * b) / d,\n (b * oneMinus + onePlus * b) / d)\n : new Complex(\n (a !== -1) ? (a / 0) : 0,\n (b !== 0) ? (b / 0) : 0);\n\n var temp = x['re'];\n x['re'] = logHypot(x['re'], x['im']) / 2;\n x['im'] = Math.atan2(x['im'], temp) / 2;\n if (noIM) {\n x['im'] = -x['im'];\n }\n return x;\n },\n\n /**\n * Calculate the complex acoth\n *\n * @returns {Complex}\n */\n 'acoth': function() {\n\n // acoth(c) = log((c+1) / (c-1)) / 2\n\n var a = this['re'];\n var b = this['im'];\n\n if (a === 0 && b === 0) {\n return new Complex(0, Math.PI / 2);\n }\n\n var d = a * a + b * b;\n return (d !== 0)\n ? new Complex(\n a / d,\n -b / d).atanh()\n : new Complex(\n (a !== 0) ? a / 0 : 0,\n (b !== 0) ? -b / 0 : 0).atanh();\n },\n\n /**\n * Calculate the complex acsch\n *\n * @returns {Complex}\n */\n 'acsch': function() {\n\n // acsch(c) = log((1+sqrt(1+c^2))/c)\n\n var a = this['re'];\n var b = this['im'];\n\n if (b === 0) {\n\n return new Complex(\n (a !== 0)\n ? Math.log(a + Math.sqrt(a * a + 1))\n : Infinity, 0);\n }\n\n var d = a * a + b * b;\n return (d !== 0)\n ? new Complex(\n a / d,\n -b / d).asinh()\n : new Complex(\n (a !== 0) ? a / 0 : 0,\n (b !== 0) ? -b / 0 : 0).asinh();\n },\n\n /**\n * Calculate the complex asech\n *\n * @returns {Complex}\n */\n 'asech': function() {\n\n // asech(c) = log((1+sqrt(1-c^2))/c)\n\n var a = this['re'];\n var b = this['im'];\n\n if (this['isZero']()) {\n return Complex['INFINITY'];\n }\n\n var d = a * a + b * b;\n return (d !== 0)\n ? new Complex(\n a / d,\n -b / d).acosh()\n : new Complex(\n (a !== 0) ? a / 0 : 0,\n (b !== 0) ? -b / 0 : 0).acosh();\n },\n\n /**\n * Calculate the complex inverse 1/z\n *\n * @returns {Complex}\n */\n 'inverse': function() {\n\n // 1 / 0 = Infinity and 1 / Infinity = 0\n if (this['isZero']()) {\n return Complex['INFINITY'];\n }\n\n if (this['isInfinite']()) {\n return Complex['ZERO'];\n }\n\n var a = this['re'];\n var b = this['im'];\n\n var d = a * a + b * b;\n\n return new Complex(a / d, -b / d);\n },\n\n /**\n * Returns the complex conjugate\n *\n * @returns {Complex}\n */\n 'conjugate': function() {\n\n return new Complex(this['re'], -this['im']);\n },\n\n /**\n * Gets the negated complex number\n *\n * @returns {Complex}\n */\n 'neg': function() {\n\n return new Complex(-this['re'], -this['im']);\n },\n\n /**\n * Ceils the actual complex number\n *\n * @returns {Complex}\n */\n 'ceil': function(places) {\n\n places = Math.pow(10, places || 0);\n\n return new Complex(\n Math.ceil(this['re'] * places) / places,\n Math.ceil(this['im'] * places) / places);\n },\n\n /**\n * Floors the actual complex number\n *\n * @returns {Complex}\n */\n 'floor': function(places) {\n\n places = Math.pow(10, places || 0);\n\n return new Complex(\n Math.floor(this['re'] * places) / places,\n Math.floor(this['im'] * places) / places);\n },\n\n /**\n * Ceils the actual complex number\n *\n * @returns {Complex}\n */\n 'round': function(places) {\n\n places = Math.pow(10, places || 0);\n\n return new Complex(\n Math.round(this['re'] * places) / places,\n Math.round(this['im'] * places) / places);\n },\n\n /**\n * Compares two complex numbers\n *\n * **Note:** new Complex(Infinity).equals(Infinity) === false\n *\n * @returns {boolean}\n */\n 'equals': function(a, b) {\n\n var z = new Complex(a, b);\n\n return Math.abs(z['re'] - this['re']) <= Complex['EPSILON'] &&\n Math.abs(z['im'] - this['im']) <= Complex['EPSILON'];\n },\n\n /**\n * Clones the actual object\n *\n * @returns {Complex}\n */\n 'clone': function() {\n\n return new Complex(this['re'], this['im']);\n },\n\n /**\n * Gets a string of the actual complex number\n *\n * @returns {string}\n */\n 'toString': function() {\n\n var a = this['re'];\n var b = this['im'];\n var ret = \"\";\n\n if (this['isNaN']()) {\n return 'NaN';\n }\n\n if (this['isInfinite']()) {\n return 'Infinity';\n }\n\n if (Math.abs(a) < Complex['EPSILON']) {\n a = 0;\n }\n\n if (Math.abs(b) < Complex['EPSILON']) {\n b = 0;\n }\n\n // If is real number\n if (b === 0) {\n return ret + a;\n }\n\n if (a !== 0) {\n ret += a;\n ret += \" \";\n if (b < 0) {\n b = -b;\n ret += \"-\";\n } else {\n ret += \"+\";\n }\n ret += \" \";\n } else if (b < 0) {\n b = -b;\n ret += \"-\";\n }\n\n if (1 !== b) { // b is the absolute imaginary part\n ret += b;\n }\n return ret + \"i\";\n },\n\n /**\n * Returns the actual number as a vector\n *\n * @returns {Array}\n */\n 'toVector': function() {\n\n return [this['re'], this['im']];\n },\n\n /**\n * Returns the actual real value of the current object\n *\n * @returns {number|null}\n */\n 'valueOf': function() {\n\n if (this['im'] === 0) {\n return this['re'];\n }\n return null;\n },\n\n /**\n * Determines whether a complex number is not on the Riemann sphere.\n *\n * @returns {boolean}\n */\n 'isNaN': function() {\n return isNaN(this['re']) || isNaN(this['im']);\n },\n\n /**\n * Determines whether or not a complex number is at the zero pole of the\n * Riemann sphere.\n *\n * @returns {boolean}\n */\n 'isZero': function() {\n return this['im'] === 0 && this['re'] === 0;\n },\n\n /**\n * Determines whether a complex number is not at the infinity pole of the\n * Riemann sphere.\n *\n * @returns {boolean}\n */\n 'isFinite': function() {\n return isFinite(this['re']) && isFinite(this['im']);\n },\n\n /**\n * Determines whether or not a complex number is at the infinity pole of the\n * Riemann sphere.\n *\n * @returns {boolean}\n */\n 'isInfinite': function() {\n return !(this['isNaN']() || this['isFinite']());\n }\n };\n\n Complex['ZERO'] = new Complex(0, 0);\n Complex['ONE'] = new Complex(1, 0);\n Complex['I'] = new Complex(0, 1);\n Complex['PI'] = new Complex(Math.PI, 0);\n Complex['E'] = new Complex(Math.E, 0);\n Complex['INFINITY'] = new Complex(Infinity, Infinity);\n Complex['NAN'] = new Complex(NaN, NaN);\n Complex['EPSILON'] = 1e-15;\n\n if (typeof define === 'function' && define['amd']) {\n define([], function() {\n return Complex;\n });\n } else if (typeof exports === 'object') {\n Object.defineProperty(Complex, \"__esModule\", { 'value': true });\n Complex['default'] = Complex;\n Complex['Complex'] = Complex;\n module['exports'] = Complex;\n } else {\n root['Complex'] = Complex;\n }\n\n})(this);\n", "import Fraction from 'fraction.js'\n\nexport function radian(angle: string): number {\n const coefficient = piCoefficient(angle)\n const fraction = new Fraction(coefficient).valueOf()\n\n return fraction * Math.PI\n}\n\nexport function angleDenominator(angle: string): number {\n const coefficient = piCoefficient(angle)\n const split = coefficient.split('/')\n\n if (split.length === 1) {\n return 1\n } else if (split.length === 2) {\n return parseInt(split[1])\n } else {\n throw new Error(`Failed to parse angle '${angle}'`)\n }\n}\n\nexport function angleNumerator(angle: string): number {\n const coefficient = piCoefficient(angle)\n const split = coefficient.split('/')\n\n if (split.length === 1) {\n return parseInt(split[0])\n } else if (split.length === 2) {\n return parseInt(split[0])\n } else {\n throw new Error(`Failed to parse angle '${angle}'`)\n }\n}\n\nexport function isAngleLessThan(angle: string, other: string): boolean {\n return new Fraction(piCoefficient(angle)).valueOf() < new Fraction(piCoefficient(other)).valueOf()\n}\n\nexport function isAngleGreaterThan(angle: string, other: string): boolean {\n return new Fraction(piCoefficient(angle)).valueOf() > new Fraction(piCoefficient(other)).valueOf()\n}\n\nexport function isValidAngle(angle: string): boolean {\n if (angle === '0') return true\n if (!/\u03C0/.test(angle)) return false\n\n try {\n const coefficient = piCoefficient(angle)\n new Fraction(coefficient).valueOf()\n\n return true\n } catch (e) {\n return false\n }\n}\n\nexport function piCoefficient(angle: string): string {\n return angle.replace(/(\\d+)\u03C0/g, '$1').replace(/\u03C0/g, '1')\n}\n\nexport function reduceAngle(angle: string): string {\n try {\n const coefficient = piCoefficient(angle)\n const reduced = new Fraction(coefficient).toFraction()\n const split = reduced.split('/')\n\n let numerator: string\n if (split[0] === '0') {\n numerator = '0'\n } else if (split[0] === '1') {\n numerator = `\u03C0`\n } else if (split[0] === '-1') {\n numerator = `-\u03C0`\n } else {\n numerator = `${split[0]}\u03C0`\n }\n\n if (split.length === 1) {\n return numerator\n } else {\n return `${numerator}/${split[1]}`\n }\n } catch (e) {\n throw new Error(`Failed to parse angle '${angle}'`)\n }\n}\n", "/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst COLLECTION_CUTOFF = 1000\nconst BAD_TO_STRING_RESULT = Object.prototype.toString.call({})\nconst RECURSE_LIMIT_DESCRIPTION = '!recursion-limit!'\nconst DEFAULT_RECURSION_LIMIT = 10\n\n// Attempts to give a useful and unambiguous description of the given value.\nexport function describe(value: unknown, recursionLimit = DEFAULT_RECURSION_LIMIT): string {\n return (\n tryDescribeAtomic(value) || tryDescribeCollection(value, recursionLimit) || describeFallback(value, recursionLimit)\n )\n}\n\nfunction tryDescribeAtomic(value: unknown) {\n if (value === null) return 'null'\n if (value === undefined) return 'undefined'\n if (typeof value === 'string') return `\"${value}\"`\n if (typeof value === 'number') return String(value)\n\n return undefined\n}\n\nfunction tryDescribeCollection(value: unknown, recursionLimit: number) {\n if (recursionLimit === 0) return RECURSE_LIMIT_DESCRIPTION\n if (value instanceof Map) return describeMap(value, recursionLimit)\n if (value instanceof Set) return describeSet(value, recursionLimit)\n const isIterable = (v: unknown): v is Iterable => {\n if ((v as Iterable)[Symbol.iterator] !== undefined) {\n return true\n }\n return false\n }\n if (isIterable(value)) return describeIterable(value, recursionLimit)\n\n return undefined\n}\n\nfunction describeFallback(value: unknown, recursionLimit: number) {\n const defaultString = String(value)\n if (defaultString !== BAD_TO_STRING_RESULT) return defaultString\n\n return describeObject(value, recursionLimit)\n}\n\nfunction describeMap(map: Map, limit: number) {\n const entries = []\n for (const [k, v] of map.entries()) {\n if (entries.length > COLLECTION_CUTOFF) {\n entries.push('[...]')\n break\n }\n const keyDesc = describe(k, limit - 1)\n const valDesc = describe(v, limit - 1)\n entries.push(`${keyDesc}: ${valDesc}`)\n }\n return `Map{${entries.join(', ')}}`\n}\n\nfunction describeSet(set: Set, limit: number) {\n const entries = []\n for (const e of set) {\n if (entries.length > COLLECTION_CUTOFF) {\n entries.push('[...]')\n break\n }\n entries.push(describe(e, limit - 1))\n }\n return `Set{${entries.join(', ')}}`\n}\n\nfunction describeIterable(seq: Iterable, limit: number): string {\n const entries = []\n for (const e of seq) {\n if (entries.length > COLLECTION_CUTOFF) {\n entries.push('[...]')\n break\n }\n entries.push(describe(e, limit - 1))\n }\n const prefix = Array.isArray(seq) ? '' : seq.constructor.name\n return `${prefix}[${entries.join(', ')}]`\n}\n\nfunction describeObject(value: unknown, limit: number) {\n const entries = []\n for (const k in value as Record) {\n if (!Object.prototype.hasOwnProperty.call(value, k)) {\n continue\n }\n if (entries.length > COLLECTION_CUTOFF) {\n entries.push('[...]')\n break\n }\n const v = (value as Record)[k]\n const keyDesc = describe(k, limit - 1)\n const valDesc = describe(v, limit - 1)\n entries.push(`${keyDesc}: ${valDesc}`)\n }\n\n const typeName = (value as Record).constructor.name\n const prefix = typeName === {}.constructor.name ? '' : `(Type: ${typeName})`\n return `${prefix}{${entries.join(', ')}}`\n}\n", "/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {describe} from './describe'\n\nlet CONSTRUCTOR_CALLS_NESTING = 0\n\nexport class DetailedError extends Error {\n public details: string | undefined\n private detailsObj: unknown\n\n constructor(message: string, detailsObj: unknown) {\n super(message)\n\n this.detailsObj = detailsObj\n this.name = 'Error'\n this.message = message\n this.stack = new Error().stack\n if (this.stack !== undefined) {\n this.stack = this.stack.replace(/^Error\\n\\s+at new DetailedError (\\S+)\\s?\\n\\s+at /, '\\n ')\n }\n\n CONSTRUCTOR_CALLS_NESTING++\n try {\n this.details =\n CONSTRUCTOR_CALLS_NESTING === 1\n ? describe(this.detailsObj)\n : '(failed to describe detailsObj due to possibly re-entrancy)'\n } catch (ex) {\n // eslint-disable-next-line no-console\n console.error(ex)\n this.details = '(failed to describe detailsObj, see the console for details)'\n } finally {\n CONSTRUCTOR_CALLS_NESTING--\n }\n }\n}\n", "type UnicodeFraction = {character: string; ref: string; value: number}\n\n/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const UNICODE_FRACTIONS = [\n {character: '\\u00BD', ref: '\u00BD', expanded: '1/2', value: 1 / 2},\n {character: '\\u00BC', ref: '\u00BC', expanded: '1/4', value: 1 / 4},\n {character: '\\u00BE', ref: '\u00BE', expanded: '3/4', value: 3 / 4},\n {character: '\\u2153', ref: '\u2153', expanded: '1/3', value: 1 / 3},\n {character: '\\u2154', ref: '\u2154', expanded: '2/3', value: 2 / 3},\n {character: '\\u2155', ref: '\u2155', expanded: '1/5', value: 1 / 5},\n {character: '\\u2156', ref: '\u2156', expanded: '2/5', value: 2 / 5},\n {character: '\\u2157', ref: '\u2157', expanded: '3/5', value: 3 / 5},\n {character: '\\u2158', ref: '\u2158', expanded: '4/5', value: 4 / 5},\n {character: '\\u2159', ref: '\u2159', expanded: '1/6', value: 1 / 6},\n {character: '\\u215A', ref: '\u215A', expanded: '5/6', value: 5 / 6},\n {character: '\\u2150', ref: '\u2150', expanded: '1/7', value: 1 / 7},\n {character: '\\u215B', ref: '\u215B', expanded: '1/8', value: 1 / 8},\n {character: '\\u215C', ref: '\u215C', expanded: '3/8', value: 3 / 8},\n {character: '\\u215D', ref: '\u215D', expanded: '5/8', value: 5 / 8},\n {character: '\\u215E', ref: '\u215E', expanded: '7/8', value: 7 / 8},\n {character: '\\u2151', ref: '\u2151', expanded: '1/9', value: 1 / 9},\n {character: '\\u2152', ref: '\u2152', expanded: '1/10', value: 1 / 10}\n]\n\n/**\n * Stores formatting options, for determining what string output should look\n * like.\n */\nexport class Format {\n /**\n * Returns an approximated result, but with the constraint that when it\n * changes slightly it should \"look the same\". (It should look good when\n * varying and animated.)\n */\n static readonly CONSISTENT = new Format(false, 0, 2, ', ')\n\n /**\n * Returns an accurate result, but favoring looking nice over being small.\n */\n static readonly EXACT = new Format(true, 0, undefined, ', ')\n\n /**\n * Returns an accurate result, favoring being small over looking nice.\n */\n static readonly MINIFIED = new Format(true, 0, undefined, ',')\n\n /**\n * Returns an approximated result, strongly favoring looking nice.\n */\n static readonly SIMPLIFIED = new Format(true, 0.0005, 3, ', ')\n\n /**\n * Parses the given text into a float. Works for text created by\n * [[formatFloat]].\n */\n static parseFloat(text: string): number {\n if (text.length === 0) {\n throw new Error(`Not a number: '${text}'`)\n }\n if (text[0] === '-') {\n return -Format.parseFloat(text.substr(1))\n }\n if (text[0] === '\\u221A') {\n return Math.sqrt(Format.parseFloat(text.substr(1)))\n }\n\n const fraction = Format.matchUnicodeFraction(e => e.character === text)\n if (fraction !== undefined) {\n return fraction.value\n }\n\n const result = parseFloat(text)\n if (isNaN(result)) {\n throw new Error(`Not a number: '${text}'`)\n }\n return result\n }\n\n /**\n * Corrects a value to a nearby simple fraction or root thereof, such as\n * sqrt(1/2), so it can be printed compactly.\n *\n * @param value The value to round.\n * @param epsilon The maximum offset error introduced by the rounding.\n */\n static simplifyByRounding(value: number, epsilon: number): number {\n if (value < 0) {\n return -Format.simplifyByRounding(-value, epsilon)\n }\n\n const r = value % 1\n if (r <= epsilon || 1 - r <= epsilon) {\n return Math.round(value)\n }\n\n const fraction = Format.matchUnicodeFraction(e => Math.abs(e.value - value) <= epsilon)\n if (fraction !== undefined) {\n return fraction.value\n }\n\n const rootFraction = Format.matchUnicodeFraction(e => Math.abs(Math.sqrt(e.value) - value) <= epsilon)\n if (rootFraction !== undefined) {\n return Math.sqrt(rootFraction.value)\n }\n\n return value\n }\n\n /**\n * Returns the first element of an array matching the given predicate, or else\n * returns undefined.\n *\n * @hidden\n */\n static matchUnicodeFraction(predicate: (arrayItem: UnicodeFraction) => boolean): UnicodeFraction | undefined {\n for (const each of UNICODE_FRACTIONS) {\n if (predicate(each)) return each\n }\n return undefined\n }\n\n public allowAbbreviation: boolean\n public maxAbbreviationError: number\n public fixedDigits: number | undefined\n public itemSeparator: string\n\n /**\n * @param allowAbbreviation Should outputs be shortened, if possible?\n * @param maxAbbreviationError How much error is abbreviating allowed to introduce?\n * @param fixedDigits Use toFixed? How many digits?\n * @param itemSeparator What should list items be separated by?\n */\n constructor(\n allowAbbreviation: boolean,\n maxAbbreviationError: number,\n fixedDigits: number | undefined,\n itemSeparator: string\n ) {\n this.allowAbbreviation = allowAbbreviation\n this.maxAbbreviationError = maxAbbreviationError\n this.fixedDigits = fixedDigits\n this.itemSeparator = itemSeparator\n }\n\n formatFloat(f: number): string {\n if (this.allowAbbreviation) {\n return this.abbreviateFloat(f, this.maxAbbreviationError, this.fixedDigits)\n }\n if (this.fixedDigits !== undefined) {\n return f.toFixed(this.fixedDigits)\n }\n return String(f)\n }\n\n /**\n * Returns a string representation of a float, taking advantage of unicode\n * fractions and square roots.\n *\n * @param value The value to represent as a string.\n * @param epsilon The maximum error introduced by using an expression.\n * @param digits digits The number of digits to use if no expression matches.\n */\n private abbreviateFloat(value: number, epsilon = 0, digits: number | undefined = undefined): string {\n if (Math.abs(value) < epsilon) return '0'\n if (value < 0) return `-${this.abbreviateFloat(-value, epsilon, digits)}`\n\n const fraction = Format.matchUnicodeFraction(e => Math.abs(e.value - value) <= epsilon)\n if (fraction !== undefined) {\n return fraction.character\n }\n\n const rootFraction = Format.matchUnicodeFraction(e => Math.abs(Math.sqrt(e.value) - value) <= epsilon)\n if (rootFraction !== undefined) {\n return `\\u221A${rootFraction.character}`\n }\n\n if (value % 1 !== 0 && digits !== undefined) {\n return value.toFixed(digits)\n }\n\n return value.toString()\n }\n}\n", "/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class Util {\n static need(expression: boolean | unknown, message: string, args?: unknown[]): void {\n if (expression !== true) {\n const argDesc = args === undefined ? '(not provided)' : `[${Array.prototype.slice.call(args).join(', ')}]`\n const msgDesc = message === undefined ? '(not provided)' : message\n const msg = `Precondition failed\\n\\nMessage: ${msgDesc}\\n\\nArgs: ${argDesc}`\n throw new Error(msg)\n }\n }\n\n static notNull(v: T): asserts v is NonNullable {\n Util.need(v !== null && v !== undefined, 'notNull')\n }\n\n static snappedCosSin(radians: number): number[] {\n const unit = Math.PI / 4\n const i = Math.round(radians / unit)\n if (i * unit === radians) {\n const s = Math.sqrt(0.5)\n const snaps = [\n [1, 0],\n [s, s],\n [0, 1],\n [-s, s],\n [-1, 0],\n [-s, -s],\n [0, -1],\n [s, -s]\n ]\n return snaps[i & 7]\n }\n return [Math.cos(radians), Math.sin(radians)]\n }\n}\n", "/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {DetailedError} from './detailed-error'\nimport {Format} from './format'\nimport {Util} from './util'\n\nexport class Complex {\n static readonly ZERO = new Complex(0, 0)\n static readonly ONE = new Complex(1, 0)\n static readonly I = new Complex(0, 1)\n\n public real: number\n public imag: number\n\n static from(v: number | Complex): Complex {\n if (v instanceof Complex) {\n return v\n }\n if (typeof v === 'number') {\n return new Complex(v, 0)\n }\n throw new DetailedError('Unrecognized value type.', {v})\n }\n\n static polar(magnitude: number, phase: number): Complex {\n const [cos, sin] = Util.snappedCosSin(phase)\n return new Complex(magnitude * cos, magnitude * sin)\n }\n\n static realPartOf(v: number | Complex): number {\n if (v instanceof Complex) {\n return v.real\n }\n if (typeof v === 'number') {\n return v\n }\n throw new DetailedError('Unrecognized value type.', {v})\n }\n\n static imagPartOf(v: number | Complex): number {\n if (v instanceof Complex) {\n return v.imag\n }\n if (typeof v === 'number') {\n return 0\n }\n throw new DetailedError('Unrecognized value type.', {v})\n }\n\n static parse(s: string): Complex {\n const m = s.match(/^\\s*([+-]?\\d+(?:\\.\\d*)?(?:e[+-]?\\d+)?)\\s*(?:([+-])\\s*i)?\\s*$/)\n\n if (m) {\n let [, real, sign, imag] = m\n if (real === undefined) real = '0'\n if (sign === undefined) sign = '+'\n if (imag === undefined) imag = '0'\n\n const [realPart, imagPart] = [real, imag].map(x => parseFloat(x))\n const [realSign, imagSign] = [sign, sign].map(x => (x === '-' ? -1 : 1))\n\n return new Complex(realPart * realSign, imagPart * imagSign)\n }\n throw new DetailedError('Invalid complex number string.', {s})\n }\n\n constructor(real: number, imag: number) {\n this.real = real\n this.imag = imag\n }\n\n static rootsOfQuadratic(a: number | Complex, b: number | Complex, c: number | Complex): Complex[] {\n a = Complex.from(a)\n b = Complex.from(b)\n c = Complex.from(c)\n\n if (a.isEqualTo(0)) {\n if (!b.isEqualTo(0)) {\n return [c.times(-1).dividedBy(b)]\n }\n if (!c.isEqualTo(0)) {\n return []\n }\n throw Error('Degenerate')\n }\n\n const difs = b.times(b).minus(a.times(c).times(4)).sqrts()\n const mid = b.times(-1)\n const denom = a.times(2)\n return difs.map(d => mid.minus(d).dividedBy(denom))\n }\n\n isEqualTo(other: unknown): boolean {\n if (other instanceof Complex) {\n return this.real === other.real && this.imag === other.imag\n }\n if (typeof other === 'number') {\n return this.real === other && this.imag === 0\n }\n return false\n }\n\n isApproximatelyEqualTo(other: number | Complex | unknown, epsilon: number): boolean {\n if (other instanceof Complex || typeof other === 'number') {\n const d = this.minus(Complex.from(other))\n return Math.abs(d.real) <= epsilon && Math.abs(d.imag) <= epsilon && d.abs() <= epsilon\n }\n return false\n }\n\n norm2(): number {\n return this.real * this.real + this.imag * this.imag\n }\n\n abs(): number {\n return Math.sqrt(this.norm2())\n }\n\n unit(): Complex {\n const m = this.norm2()\n if (m < 0.00001) {\n return Complex.polar(1, this.phase())\n }\n return this.dividedBy(Math.sqrt(m))\n }\n\n plus(v: number | Complex): Complex {\n const c = Complex.from(v)\n return new Complex(this.real + c.real, this.imag + c.imag)\n }\n\n minus(v: number | Complex): Complex {\n const c = Complex.from(v)\n return new Complex(this.real - c.real, this.imag - c.imag)\n }\n\n times(v: number | Complex): Complex {\n const c = Complex.from(v)\n return new Complex(this.real * c.real - this.imag * c.imag, this.real * c.imag + this.imag * c.real)\n }\n\n dividedBy(v: number | Complex): Complex {\n const c = Complex.from(v)\n const d = c.norm2()\n if (d === 0) {\n throw new Error('Division by Zero')\n }\n\n const n = this.times(c.conjugate())\n return new Complex(n.real / d, n.imag / d)\n }\n\n sqrts(): [Complex] | [Complex, Complex] {\n const [r, i] = [this.real, this.imag]\n const m = Math.sqrt(Math.sqrt(r * r + i * i))\n if (m === 0) {\n return [Complex.ZERO]\n }\n if (i === 0 && r < 0) {\n return [new Complex(0, m), new Complex(0, -m)]\n }\n\n const a = this.phase() / 2\n const c = Complex.polar(m, a)\n return [c, c.times(-1)]\n }\n\n conjugate(): Complex {\n return new Complex(this.real, -this.imag)\n }\n\n toString(format?: Format): string {\n format = format || Format.EXACT\n return format.allowAbbreviation ? this.toStringAllowSingleValue(format) : this.toStringBothValues(format)\n }\n\n neg(): Complex {\n return new Complex(-this.real, -this.imag)\n }\n\n raisedTo(exponent: number | Complex): Complex {\n if (exponent === 0.5 && this.imag === 0 && this.real >= 0) {\n return new Complex(Math.sqrt(this.real), 0)\n }\n if (Complex.ZERO.isEqualTo(exponent)) {\n return Complex.ONE\n }\n if (this.isEqualTo(Complex.ZERO)) {\n return Complex.ZERO\n }\n return this.ln().times(Complex.from(exponent)).exp()\n }\n\n exp(): Complex {\n return Complex.polar(Math.exp(this.real), this.imag)\n }\n\n cos(): Complex {\n const z = this.times(Complex.I)\n return z.exp().plus(z.neg().exp()).times(0.5)\n }\n\n sin(): Complex {\n const z = this.times(Complex.I)\n return z.exp().minus(z.neg().exp()).dividedBy(new Complex(0, 2))\n }\n\n tan(): Complex {\n return this.sin().dividedBy(this.cos())\n }\n\n ln(): Complex {\n return new Complex(Math.log(this.abs()), this.phase())\n }\n\n phase(): number {\n return Math.atan2(this.imag, this.real)\n }\n\n private toStringAllowSingleValue(format: Format): string {\n if (Math.abs(this.imag) <= format.maxAbbreviationError) {\n return format.formatFloat(this.real)\n }\n if (Math.abs(this.real) <= format.maxAbbreviationError) {\n if (Math.abs(this.imag - 1) <= format.maxAbbreviationError) {\n return 'i'\n }\n if (Math.abs(this.imag + 1) <= format.maxAbbreviationError) {\n return '-i'\n }\n return `${format.formatFloat(this.imag)}i`\n }\n\n return this.toStringBothValues(format)\n }\n\n private toStringBothValues(format: Format): string {\n const separator = this.imag >= 0 ? '+' : '-'\n const imagFactor =\n format.allowAbbreviation && Math.abs(Math.abs(this.imag) - 1) <= format.maxAbbreviationError\n ? ''\n : format.formatFloat(Math.abs(this.imag))\n const prefix = format.allowAbbreviation || format.fixedDigits === undefined || this.real < 0 ? '' : '+'\n return `${prefix + format.formatFloat(this.real) + separator + imagFactor}i`\n }\n}\n", "/**\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function hasOwnProperty(obj: unknown, key: K): obj is Record {\n return obj !== null && obj !== undefined && key in (obj as Record)\n}\n\nexport type ArrayIsh =\n | unknown[]\n | Float32Array\n | Float64Array\n | Int8Array\n | Int16Array\n | Int32Array\n | Uint8Array\n | Uint16Array\n | Uint32Array\n | Uint8ClampedArray\n\nconst GENERIC_ARRAY_TYPES = [\n Float32Array,\n Float64Array,\n Int8Array,\n Int16Array,\n Int32Array,\n Uint8Array,\n Uint16Array,\n Uint32Array,\n Uint8ClampedArray\n]\n\nexport function equate(subject: unknown, other: unknown): boolean {\n if (subject === other || (isExactlyNaN(subject) && isExactlyNaN(other))) {\n return true\n }\n\n const customEquality = tryEquateCustom(subject, other)\n if (customEquality !== undefined) {\n return customEquality\n }\n if (isAtomic(subject) || isAtomic(other) || !eqType(subject, other)) {\n return false\n }\n\n if (subject instanceof Map && other instanceof Map) {\n return equateMaps(subject, other)\n }\n if (subject instanceof Set && other instanceof Set) {\n return equateSets(subject, other)\n }\n if (isIndexable(subject) && isIndexable(other)) {\n return equateIndexables(subject, other)\n }\n\n return equateObjects(subject, other)\n}\n\nfunction isIndexable(value: unknown): value is ArrayIsh {\n return Array.isArray(value) || !GENERIC_ARRAY_TYPES.every(t => !(value instanceof t))\n}\n\nfunction isExactlyNaN(v: unknown) {\n return typeof v === 'number' && isNaN(v)\n}\n\nfunction tryEquateCustom(subject: unknown, other: unknown): boolean | undefined {\n if (!isAtomic(subject) && hasOwnProperty(subject, 'isEqualTo') && typeof subject.isEqualTo === 'function') {\n return subject.isEqualTo(other) as boolean\n }\n if (!isAtomic(other) && hasOwnProperty(other, 'isEqualTo') && typeof other.isEqualTo === 'function') {\n return other.isEqualTo(subject) as boolean\n }\n return undefined\n}\n\ntype Atomic = null | undefined | string | number | boolean\n\nfunction isAtomic(value: unknown): value is Atomic {\n return (\n value === null ||\n value === undefined ||\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n )\n}\n\nfunction equateMaps(subject: Map, other: Map) {\n if (subject.size !== other.size) {\n return false\n }\n for (const [k, v] of subject) {\n if (!other.has(k)) {\n return false\n }\n const otherV = other.get(k)\n if (!equate(v, otherV)) {\n return false\n }\n }\n return true\n}\n\nfunction equateSets(subject: Set, other: Set) {\n if (subject.size !== other.size) {\n return false\n }\n for (const k of subject) {\n if (!other.has(k)) {\n return false\n }\n }\n return true\n}\n\nfunction eqType(subject: unknown, other: unknown): boolean {\n return typeof subject === typeof other\n}\n\nfunction equateIndexables(subject: ArrayIsh, other: ArrayIsh) {\n if (subject.length !== other.length) {\n return false\n }\n for (let i = 0; i < subject.length; i++) {\n if (!equate(subject[i], other[i])) {\n return false\n }\n }\n return true\n}\n\nfunction objectKeys(obj: unknown) {\n const result = new Set()\n for (const k in obj as Record) {\n if (hasOwnProperty(obj, k)) {\n result.add(k)\n }\n }\n return result\n}\n\nfunction equateObjects(subject: unknown, other: unknown) {\n const keys = objectKeys(subject)\n if (!equateSets(keys, objectKeys(other))) {\n return false\n }\n\n for (const k of keys) {\n if (k === Symbol.iterator) {\n continue\n }\n if (!equate((subject as Record)[k as string], (other as Record)[k as string])) {\n return false\n }\n }\n\n const hasSubjectIter = hasOwnProperty(subject, Symbol.iterator)\n const hasOtherIter = hasOwnProperty(other, Symbol.iterator)\n if (hasSubjectIter !== hasOtherIter) {\n return false\n }\n if (hasSubjectIter && hasOtherIter) {\n if (!equateIterables(subject as Iterable, other as Iterable)) {\n return false\n }\n }\n\n return true\n}\n\nfunction equateIterables(subject: Iterable, other: Iterable) {\n const otherIter = other[Symbol.iterator]()\n for (const subjectItem of subject) {\n const otherItemDone = otherIter.next()\n if (otherItemDone.done || !equate(subjectItem, otherItemDone.value)) {\n return false\n }\n }\n return otherIter.next().done\n}\n", "export const SerializedHGateType = 'H'\n\nexport type SerializedHGate = {\n type: typeof SerializedHGateType\n targets: number[]\n controls?: number[]\n if?: string\n}\n", "export const SerializedXGateType = 'X'\n\nexport type SerializedXGate = {\n type: typeof SerializedXGateType\n targets: number[]\n controls?: number[]\n if?: string\n}\n", "export const SerializedYGateType = 'Y'\n\nexport type SerializedYGate = {\n type: typeof SerializedYGateType\n targets: number[]\n controls?: number[]\n if?: string\n}\n", "export const SerializedZGateType = 'Z'\n\nexport type SerializedZGate = {\n type: typeof SerializedZGateType\n targets: number[]\n controls?: number[]\n if?: string\n}\n", "export const SerializedPhaseGateType = 'P'\n\nexport type SerializedPhaseGate = {\n type: typeof SerializedPhaseGateType\n angle?: string\n targets: number[]\n controls?: number[]\n if?: string\n}\n", "export const SerializedTGateType = 'T'\n\nexport type SerializedTGate = {\n type: typeof SerializedTGateType\n targets: number[]\n controls?: number[]\n if?: string\n}\n", "export const SerializedRnotGateType = 'X^\u00BD'\n\nexport type SerializedRnotGate = {\n type: typeof SerializedRnotGateType\n targets: number[]\n controls?: number[]\n if?: string\n}\n", "export const SerializedRxGateType = 'Rx'\n\nexport type SerializedRxGate = {\n type: typeof SerializedRxGateType\n targets: number[]\n angle?: string\n controls?: number[]\n if?: string\n}\n", "export const SerializedRyGateType = 'Ry'\n\nexport type SerializedRyGate = {\n type: typeof SerializedRyGateType\n targets: number[]\n angle?: string\n controls?: number[]\n if?: string\n}\n", "export const SerializedRzGateType = 'Rz'\n\nexport type SerializedRzGate = {\n type: typeof SerializedRzGateType\n targets: number[]\n angle?: string\n controls?: number[]\n if?: string\n}\n", "export const SerializedSwapGateType = 'Swap'\n\nexport type SerializedSwapGate = {\n type: typeof SerializedSwapGateType\n targets: [number, number]\n controls?: number[]\n}\n", "export const SerializedControlGateType = '\u2022'\n\nexport type SerializedControlGate = {\n type: typeof SerializedControlGateType\n targets: number[]\n}\n", "export const SerializedBlochDisplayType = 'Bloch'\n\nexport type SerializedBlochDisplay = {\n type: typeof SerializedBlochDisplayType\n targets: number[]\n}\n", "export const SerializedWrite0GateType = '|0>'\nexport const SerializedWrite1GateType = '|1>'\n\nexport type SerializedWriteGate = {\n type: typeof SerializedWrite0GateType | typeof SerializedWrite1GateType\n targets: number[]\n}\n", "export const SerializedMeasurementGateType = 'Measure'\n\nexport type SerializedMeasurementGate = {\n type: typeof SerializedMeasurementGateType\n targets: number[]\n flag?: string\n}\n", null, null, null, null, null, null, null, null, "import {Constructor} from './constructor'\nimport {attr} from '@github/catalyst'\n\nexport declare class Activateable {\n get active(): boolean\n set active(value: boolean)\n activate(): void\n deactivate(): void\n}\n\nexport function ActivateableMixin>(\n Base: TBase\n): Constructor & TBase {\n class ActivateableMixinClass extends Base {\n @attr active = false\n\n activate() {\n this.active = true\n this.dispatchEvent(new Event('operation-active', {bubbles: true}))\n }\n\n deactivate() {\n this.active = false\n }\n }\n\n return ActivateableMixinClass as Constructor & TBase\n}\n", "import {Constructor} from './constructor'\nimport {attr} from '@github/catalyst'\n\nexport declare class Angleable {\n get angle(): string\n set angle(value: string)\n get reducedAngle(): string\n set reducedAngle(value: string)\n}\n\nexport const isAngleable = (arg: unknown): arg is Angleable =>\n typeof arg === 'object' &&\n arg !== null &&\n typeof (arg as Angleable).angle === 'string' &&\n typeof (arg as Angleable).reducedAngle === 'string'\n\nexport function AngleableMixin>(Base: TBase): Constructor & TBase {\n class AngleableMixinClass extends Base {\n @attr angle = ''\n @attr reducedAngle = ''\n }\n\n return AngleableMixinClass as Constructor & TBase\n}\n", "import {Constructor} from './constructor'\n\nexport declare class Controllable {\n set controls(value: number[])\n get controls(): number[]\n get isControlled(): boolean\n}\n\nexport const isControllable = (arg: unknown): arg is Controllable =>\n typeof arg === 'object' && arg !== null && typeof (arg as Controllable).controls === 'object'\n\nexport function ControllableMixin>(\n Base: TBase\n): Constructor & TBase {\n class ControllableMixinClass extends Base {\n set controls(controls: number[]) {\n this.setAttribute('data-controls', controls.sort().join())\n }\n\n get controls(): number[] {\n const dataControls = this.getAttribute('data-controls')\n if (dataControls === null) return []\n if (dataControls === '') return []\n\n return dataControls\n .split(',')\n .map(each => parseInt(each))\n .sort()\n }\n\n get isControlled(): boolean {\n return this.controls.length > 0\n }\n }\n\n return ControllableMixinClass as Constructor & TBase\n}\n", "import {Constructor} from './constructor'\nimport {attr} from '@github/catalyst'\n\nexport declare class Disableable {\n get disabled(): boolean\n set disabled(value: boolean)\n get enabled(): boolean\n enable(): void\n disable(): void\n}\n\nexport function DisableableMixin>(\n Base: TBase\n): Constructor & TBase {\n class DisableableMixinClass extends Base {\n @attr disabled = false\n\n get enabled(): boolean {\n return !this.disabled\n }\n\n enable(): void {\n this.disabled = false\n }\n\n disable(): void {\n this.disabled = true\n }\n }\n\n return DisableableMixinClass as Constructor & TBase\n}\n", "/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\nvar __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n };\r\n return __assign.apply(this, arguments);\r\n};\r\n\r\nfunction __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nfunction __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nfunction __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nfunction __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\n\nexport { __assign, __read, __rest, __spreadArray, __values };\n", "var ActionTypes;\n\n(function (ActionTypes) {\n ActionTypes[\"Start\"] = \"xstate.start\";\n ActionTypes[\"Stop\"] = \"xstate.stop\";\n ActionTypes[\"Raise\"] = \"xstate.raise\";\n ActionTypes[\"Send\"] = \"xstate.send\";\n ActionTypes[\"Cancel\"] = \"xstate.cancel\";\n ActionTypes[\"NullEvent\"] = \"\";\n ActionTypes[\"Assign\"] = \"xstate.assign\";\n ActionTypes[\"After\"] = \"xstate.after\";\n ActionTypes[\"DoneState\"] = \"done.state\";\n ActionTypes[\"DoneInvoke\"] = \"done.invoke\";\n ActionTypes[\"Log\"] = \"xstate.log\";\n ActionTypes[\"Init\"] = \"xstate.init\";\n ActionTypes[\"Invoke\"] = \"xstate.invoke\";\n ActionTypes[\"ErrorExecution\"] = \"error.execution\";\n ActionTypes[\"ErrorCommunication\"] = \"error.communication\";\n ActionTypes[\"ErrorPlatform\"] = \"error.platform\";\n ActionTypes[\"ErrorCustom\"] = \"xstate.error\";\n ActionTypes[\"Update\"] = \"xstate.update\";\n ActionTypes[\"Pure\"] = \"xstate.pure\";\n ActionTypes[\"Choose\"] = \"xstate.choose\";\n})(ActionTypes || (ActionTypes = {}));\n\nvar SpecialTargets;\n\n(function (SpecialTargets) {\n SpecialTargets[\"Parent\"] = \"#_parent\";\n SpecialTargets[\"Internal\"] = \"#_internal\";\n})(SpecialTargets || (SpecialTargets = {}));\n\nexport { ActionTypes, SpecialTargets };\n", "import { ActionTypes } from './types.js';\n\nvar start = ActionTypes.Start;\nvar stop = ActionTypes.Stop;\nvar raise = ActionTypes.Raise;\nvar send = ActionTypes.Send;\nvar cancel = ActionTypes.Cancel;\nvar nullEvent = ActionTypes.NullEvent;\nvar assign = ActionTypes.Assign;\nvar after = ActionTypes.After;\nvar doneState = ActionTypes.DoneState;\nvar log = ActionTypes.Log;\nvar init = ActionTypes.Init;\nvar invoke = ActionTypes.Invoke;\nvar errorExecution = ActionTypes.ErrorExecution;\nvar errorPlatform = ActionTypes.ErrorPlatform;\nvar error = ActionTypes.ErrorCustom;\nvar update = ActionTypes.Update;\nvar choose = ActionTypes.Choose;\nvar pure = ActionTypes.Pure;\n\nexport { after, assign, cancel, choose, doneState, error, errorExecution, errorPlatform, init, invoke, log, nullEvent, pure, raise, send, start, stop, update };\n", "var STATE_DELIMITER = '.';\nvar EMPTY_ACTIVITY_MAP = {};\nvar DEFAULT_GUARD_TYPE = 'xstate.guard';\nvar TARGETLESS_KEY = '';\n\nexport { DEFAULT_GUARD_TYPE, EMPTY_ACTIVITY_MAP, STATE_DELIMITER, TARGETLESS_KEY };\n", "var IS_PRODUCTION = process.env.NODE_ENV === 'production';\n\nexport { IS_PRODUCTION };\n", "import { __values, __spreadArray, __read, __assign } from './_virtual/_tslib.js';\nimport { DEFAULT_GUARD_TYPE, TARGETLESS_KEY, STATE_DELIMITER } from './constants.js';\nimport { IS_PRODUCTION } from './environment.js';\n\nvar _a;\nfunction keys(value) {\n return Object.keys(value);\n}\nfunction matchesState(parentStateId, childStateId, delimiter) {\n if (delimiter === void 0) {\n delimiter = STATE_DELIMITER;\n }\n\n var parentStateValue = toStateValue(parentStateId, delimiter);\n var childStateValue = toStateValue(childStateId, delimiter);\n\n if (isString(childStateValue)) {\n if (isString(parentStateValue)) {\n return childStateValue === parentStateValue;\n } // Parent more specific than child\n\n\n return false;\n }\n\n if (isString(parentStateValue)) {\n return parentStateValue in childStateValue;\n }\n\n return Object.keys(parentStateValue).every(function (key) {\n if (!(key in childStateValue)) {\n return false;\n }\n\n return matchesState(parentStateValue[key], childStateValue[key]);\n });\n}\nfunction getEventType(event) {\n try {\n return isString(event) || typeof event === 'number' ? \"\".concat(event) : event.type;\n } catch (e) {\n throw new Error('Events must be strings or objects with a string event.type property.');\n }\n}\nfunction getActionType(action) {\n try {\n return isString(action) || typeof action === 'number' ? \"\".concat(action) : isFunction(action) ? action.name : action.type;\n } catch (e) {\n throw new Error('Actions must be strings or objects with a string action.type property.');\n }\n}\nfunction toStatePath(stateId, delimiter) {\n try {\n if (isArray(stateId)) {\n return stateId;\n }\n\n return stateId.toString().split(delimiter);\n } catch (e) {\n throw new Error(\"'\".concat(stateId, \"' is not a valid state path.\"));\n }\n}\nfunction isStateLike(state) {\n return typeof state === 'object' && 'value' in state && 'context' in state && 'event' in state && '_event' in state;\n}\nfunction toStateValue(stateValue, delimiter) {\n if (isStateLike(stateValue)) {\n return stateValue.value;\n }\n\n if (isArray(stateValue)) {\n return pathToStateValue(stateValue);\n }\n\n if (typeof stateValue !== 'string') {\n return stateValue;\n }\n\n var statePath = toStatePath(stateValue, delimiter);\n return pathToStateValue(statePath);\n}\nfunction pathToStateValue(statePath) {\n if (statePath.length === 1) {\n return statePath[0];\n }\n\n var value = {};\n var marker = value;\n\n for (var i = 0; i < statePath.length - 1; i++) {\n if (i === statePath.length - 2) {\n marker[statePath[i]] = statePath[i + 1];\n } else {\n marker[statePath[i]] = {};\n marker = marker[statePath[i]];\n }\n }\n\n return value;\n}\nfunction mapValues(collection, iteratee) {\n var result = {};\n var collectionKeys = Object.keys(collection);\n\n for (var i = 0; i < collectionKeys.length; i++) {\n var key = collectionKeys[i];\n result[key] = iteratee(collection[key], key, collection, i);\n }\n\n return result;\n}\nfunction mapFilterValues(collection, iteratee, predicate) {\n var e_1, _a;\n\n var result = {};\n\n try {\n for (var _b = __values(Object.keys(collection)), _c = _b.next(); !_c.done; _c = _b.next()) {\n var key = _c.value;\n var item = collection[key];\n\n if (!predicate(item)) {\n continue;\n }\n\n result[key] = iteratee(item, key, collection);\n }\n } catch (e_1_1) {\n e_1 = {\n error: e_1_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n } finally {\n if (e_1) throw e_1.error;\n }\n }\n\n return result;\n}\n/**\r\n * Retrieves a value at the given path.\r\n * @param props The deep path to the prop of the desired value\r\n */\n\nvar path = function (props) {\n return function (object) {\n var e_2, _a;\n\n var result = object;\n\n try {\n for (var props_1 = __values(props), props_1_1 = props_1.next(); !props_1_1.done; props_1_1 = props_1.next()) {\n var prop = props_1_1.value;\n result = result[prop];\n }\n } catch (e_2_1) {\n e_2 = {\n error: e_2_1\n };\n } finally {\n try {\n if (props_1_1 && !props_1_1.done && (_a = props_1.return)) _a.call(props_1);\n } finally {\n if (e_2) throw e_2.error;\n }\n }\n\n return result;\n };\n};\n/**\r\n * Retrieves a value at the given path via the nested accessor prop.\r\n * @param props The deep path to the prop of the desired value\r\n */\n\nfunction nestedPath(props, accessorProp) {\n return function (object) {\n var e_3, _a;\n\n var result = object;\n\n try {\n for (var props_2 = __values(props), props_2_1 = props_2.next(); !props_2_1.done; props_2_1 = props_2.next()) {\n var prop = props_2_1.value;\n result = result[accessorProp][prop];\n }\n } catch (e_3_1) {\n e_3 = {\n error: e_3_1\n };\n } finally {\n try {\n if (props_2_1 && !props_2_1.done && (_a = props_2.return)) _a.call(props_2);\n } finally {\n if (e_3) throw e_3.error;\n }\n }\n\n return result;\n };\n}\nfunction toStatePaths(stateValue) {\n if (!stateValue) {\n return [[]];\n }\n\n if (isString(stateValue)) {\n return [[stateValue]];\n }\n\n var result = flatten(Object.keys(stateValue).map(function (key) {\n var subStateValue = stateValue[key];\n\n if (typeof subStateValue !== 'string' && (!subStateValue || !Object.keys(subStateValue).length)) {\n return [[key]];\n }\n\n return toStatePaths(stateValue[key]).map(function (subPath) {\n return [key].concat(subPath);\n });\n }));\n return result;\n}\nfunction pathsToStateValue(paths) {\n var e_4, _a;\n\n var result = {};\n\n if (paths && paths.length === 1 && paths[0].length === 1) {\n return paths[0][0];\n }\n\n try {\n for (var paths_1 = __values(paths), paths_1_1 = paths_1.next(); !paths_1_1.done; paths_1_1 = paths_1.next()) {\n var currentPath = paths_1_1.value;\n var marker = result; // tslint:disable-next-line:prefer-for-of\n\n for (var i = 0; i < currentPath.length; i++) {\n var subPath = currentPath[i];\n\n if (i === currentPath.length - 2) {\n marker[subPath] = currentPath[i + 1];\n break;\n }\n\n marker[subPath] = marker[subPath] || {};\n marker = marker[subPath];\n }\n }\n } catch (e_4_1) {\n e_4 = {\n error: e_4_1\n };\n } finally {\n try {\n if (paths_1_1 && !paths_1_1.done && (_a = paths_1.return)) _a.call(paths_1);\n } finally {\n if (e_4) throw e_4.error;\n }\n }\n\n return result;\n}\nfunction flatten(array) {\n var _a;\n\n return (_a = []).concat.apply(_a, __spreadArray([], __read(array), false));\n}\nfunction toArrayStrict(value) {\n if (isArray(value)) {\n return value;\n }\n\n return [value];\n}\nfunction toArray(value) {\n if (value === undefined) {\n return [];\n }\n\n return toArrayStrict(value);\n}\nfunction mapContext(mapper, context, _event) {\n var e_5, _a;\n\n if (isFunction(mapper)) {\n return mapper(context, _event.data);\n }\n\n var result = {};\n\n try {\n for (var _b = __values(Object.keys(mapper)), _c = _b.next(); !_c.done; _c = _b.next()) {\n var key = _c.value;\n var subMapper = mapper[key];\n\n if (isFunction(subMapper)) {\n result[key] = subMapper(context, _event.data);\n } else {\n result[key] = subMapper;\n }\n }\n } catch (e_5_1) {\n e_5 = {\n error: e_5_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n } finally {\n if (e_5) throw e_5.error;\n }\n }\n\n return result;\n}\nfunction isBuiltInEvent(eventType) {\n return /^(done|error)\\./.test(eventType);\n}\nfunction isPromiseLike(value) {\n if (value instanceof Promise) {\n return true;\n } // Check if shape matches the Promise/A+ specification for a \"thenable\".\n\n\n if (value !== null && (isFunction(value) || typeof value === 'object') && isFunction(value.then)) {\n return true;\n }\n\n return false;\n}\nfunction isBehavior(value) {\n return value !== null && typeof value === 'object' && 'transition' in value && typeof value.transition === 'function';\n}\nfunction partition(items, predicate) {\n var e_6, _a;\n\n var _b = __read([[], []], 2),\n truthy = _b[0],\n falsy = _b[1];\n\n try {\n for (var items_1 = __values(items), items_1_1 = items_1.next(); !items_1_1.done; items_1_1 = items_1.next()) {\n var item = items_1_1.value;\n\n if (predicate(item)) {\n truthy.push(item);\n } else {\n falsy.push(item);\n }\n }\n } catch (e_6_1) {\n e_6 = {\n error: e_6_1\n };\n } finally {\n try {\n if (items_1_1 && !items_1_1.done && (_a = items_1.return)) _a.call(items_1);\n } finally {\n if (e_6) throw e_6.error;\n }\n }\n\n return [truthy, falsy];\n}\nfunction updateHistoryStates(hist, stateValue) {\n return mapValues(hist.states, function (subHist, key) {\n if (!subHist) {\n return undefined;\n }\n\n var subStateValue = (isString(stateValue) ? undefined : stateValue[key]) || (subHist ? subHist.current : undefined);\n\n if (!subStateValue) {\n return undefined;\n }\n\n return {\n current: subStateValue,\n states: updateHistoryStates(subHist, subStateValue)\n };\n });\n}\nfunction updateHistoryValue(hist, stateValue) {\n return {\n current: stateValue,\n states: updateHistoryStates(hist, stateValue)\n };\n}\nfunction updateContext(context, _event, assignActions, state) {\n if (!IS_PRODUCTION) {\n warn(!!context, 'Attempting to update undefined context');\n }\n\n var updatedContext = context ? assignActions.reduce(function (acc, assignAction) {\n var e_7, _a;\n\n var assignment = assignAction.assignment;\n var meta = {\n state: state,\n action: assignAction,\n _event: _event\n };\n var partialUpdate = {};\n\n if (isFunction(assignment)) {\n partialUpdate = assignment(acc, _event.data, meta);\n } else {\n try {\n for (var _b = __values(Object.keys(assignment)), _c = _b.next(); !_c.done; _c = _b.next()) {\n var key = _c.value;\n var propAssignment = assignment[key];\n partialUpdate[key] = isFunction(propAssignment) ? propAssignment(acc, _event.data, meta) : propAssignment;\n }\n } catch (e_7_1) {\n e_7 = {\n error: e_7_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n } finally {\n if (e_7) throw e_7.error;\n }\n }\n }\n\n return Object.assign({}, acc, partialUpdate);\n }, context) : context;\n return updatedContext;\n} // tslint:disable-next-line:no-empty\n\nvar warn = function () {};\n\nif (!IS_PRODUCTION) {\n warn = function (condition, message) {\n var error = condition instanceof Error ? condition : undefined;\n\n if (!error && condition) {\n return;\n }\n\n if (console !== undefined) {\n var args = [\"Warning: \".concat(message)];\n\n if (error) {\n args.push(error);\n } // tslint:disable-next-line:no-console\n\n\n console.warn.apply(console, args);\n }\n };\n}\nfunction isArray(value) {\n return Array.isArray(value);\n} // tslint:disable-next-line:ban-types\n\nfunction isFunction(value) {\n return typeof value === 'function';\n}\nfunction isString(value) {\n return typeof value === 'string';\n}\nfunction toGuard(condition, guardMap) {\n if (!condition) {\n return undefined;\n }\n\n if (isString(condition)) {\n return {\n type: DEFAULT_GUARD_TYPE,\n name: condition,\n predicate: guardMap ? guardMap[condition] : undefined\n };\n }\n\n if (isFunction(condition)) {\n return {\n type: DEFAULT_GUARD_TYPE,\n name: condition.name,\n predicate: condition\n };\n }\n\n return condition;\n}\nfunction isObservable(value) {\n try {\n return 'subscribe' in value && isFunction(value.subscribe);\n } catch (e) {\n return false;\n }\n}\nvar symbolObservable = /*#__PURE__*/function () {\n return typeof Symbol === 'function' && Symbol.observable || '@@observable';\n}(); // TODO: to be removed in v5, left it out just to minimize the scope of the change and maintain compatibility with older versions of integration paackages\n\nvar interopSymbols = (_a = {}, _a[symbolObservable] = function () {\n return this;\n}, _a[Symbol.observable] = function () {\n return this;\n}, _a);\nfunction isMachine(value) {\n return !!value && '__xstatenode' in value;\n}\nfunction isActor(value) {\n return !!value && typeof value.send === 'function';\n}\nvar uniqueId = /*#__PURE__*/function () {\n var currentId = 0;\n return function () {\n currentId++;\n return currentId.toString(16);\n };\n}();\nfunction toEventObject(event, payload // id?: TEvent['type']\n) {\n if (isString(event) || typeof event === 'number') {\n return __assign({\n type: event\n }, payload);\n }\n\n return event;\n}\nfunction toSCXMLEvent(event, scxmlEvent) {\n if (!isString(event) && '$$type' in event && event.$$type === 'scxml') {\n return event;\n }\n\n var eventObject = toEventObject(event);\n return __assign({\n name: eventObject.type,\n data: eventObject,\n $$type: 'scxml',\n type: 'external'\n }, scxmlEvent);\n}\nfunction toTransitionConfigArray(event, configLike) {\n var transitions = toArrayStrict(configLike).map(function (transitionLike) {\n if (typeof transitionLike === 'undefined' || typeof transitionLike === 'string' || isMachine(transitionLike)) {\n return {\n target: transitionLike,\n event: event\n };\n }\n\n return __assign(__assign({}, transitionLike), {\n event: event\n });\n });\n return transitions;\n}\nfunction normalizeTarget(target) {\n if (target === undefined || target === TARGETLESS_KEY) {\n return undefined;\n }\n\n return toArray(target);\n}\nfunction reportUnhandledExceptionOnInvocation(originalError, currentError, id) {\n if (!IS_PRODUCTION) {\n var originalStackTrace = originalError.stack ? \" Stacktrace was '\".concat(originalError.stack, \"'\") : '';\n\n if (originalError === currentError) {\n // tslint:disable-next-line:no-console\n console.error(\"Missing onError handler for invocation '\".concat(id, \"', error was '\").concat(originalError, \"'.\").concat(originalStackTrace));\n } else {\n var stackTrace = currentError.stack ? \" Stacktrace was '\".concat(currentError.stack, \"'\") : ''; // tslint:disable-next-line:no-console\n\n console.error(\"Missing onError handler and/or unhandled exception/promise rejection for invocation '\".concat(id, \"'. \") + \"Original error: '\".concat(originalError, \"'. \").concat(originalStackTrace, \" Current error is '\").concat(currentError, \"'.\").concat(stackTrace));\n }\n }\n}\nfunction evaluateGuard(machine, guard, context, _event, state) {\n var guards = machine.options.guards;\n var guardMeta = {\n state: state,\n cond: guard,\n _event: _event\n }; // TODO: do not hardcode!\n\n if (guard.type === DEFAULT_GUARD_TYPE) {\n return ((guards === null || guards === void 0 ? void 0 : guards[guard.name]) || guard.predicate)(context, _event.data, guardMeta);\n }\n\n var condFn = guards === null || guards === void 0 ? void 0 : guards[guard.type];\n\n if (!condFn) {\n throw new Error(\"Guard '\".concat(guard.type, \"' is not implemented on machine '\").concat(machine.id, \"'.\"));\n }\n\n return condFn(context, _event.data, guardMeta);\n}\nfunction toInvokeSource(src) {\n if (typeof src === 'string') {\n return {\n type: src\n };\n }\n\n return src;\n}\nfunction toObserver(nextHandler, errorHandler, completionHandler) {\n if (typeof nextHandler === 'object') {\n return nextHandler;\n }\n\n var noop = function () {\n return void 0;\n };\n\n return {\n next: nextHandler,\n error: errorHandler || noop,\n complete: completionHandler || noop\n };\n}\nfunction createInvokeId(stateNodeId, index) {\n return \"\".concat(stateNodeId, \":invocation[\").concat(index, \"]\");\n}\n\nexport { createInvokeId, evaluateGuard, flatten, getActionType, getEventType, interopSymbols, isActor, isArray, isBehavior, isBuiltInEvent, isFunction, isMachine, isObservable, isPromiseLike, isStateLike, isString, keys, mapContext, mapFilterValues, mapValues, matchesState, nestedPath, normalizeTarget, partition, path, pathToStateValue, pathsToStateValue, reportUnhandledExceptionOnInvocation, symbolObservable, toArray, toArrayStrict, toEventObject, toGuard, toInvokeSource, toObserver, toSCXMLEvent, toStatePath, toStatePaths, toStateValue, toTransitionConfigArray, uniqueId, updateContext, updateHistoryStates, updateHistoryValue, warn };\n", "import { __assign, __read, __spreadArray } from './_virtual/_tslib.js';\nimport { SpecialTargets, ActionTypes } from './types.js';\nimport { init, send as send$1, raise as raise$1, update, log as log$1, cancel as cancel$1, assign as assign$1, error as error$1, stop as stop$1, pure as pure$1, choose as choose$1 } from './actionTypes.js';\nimport * as actionTypes from './actionTypes.js';\nexport { actionTypes };\nimport { toSCXMLEvent, isString, isFunction, toEventObject, getEventType, partition, updateContext, flatten, toArray, toGuard, evaluateGuard, warn, isArray } from './utils.js';\nimport { IS_PRODUCTION } from './environment.js';\n\nvar initEvent = /*#__PURE__*/toSCXMLEvent({\n type: init\n});\nfunction getActionFunction(actionType, actionFunctionMap) {\n return actionFunctionMap ? actionFunctionMap[actionType] || undefined : undefined;\n}\nfunction toActionObject(action, actionFunctionMap) {\n var actionObject;\n\n if (isString(action) || typeof action === 'number') {\n var exec = getActionFunction(action, actionFunctionMap);\n\n if (isFunction(exec)) {\n actionObject = {\n type: action,\n exec: exec\n };\n } else if (exec) {\n actionObject = exec;\n } else {\n actionObject = {\n type: action,\n exec: undefined\n };\n }\n } else if (isFunction(action)) {\n actionObject = {\n // Convert action to string if unnamed\n type: action.name || action.toString(),\n exec: action\n };\n } else {\n var exec = getActionFunction(action.type, actionFunctionMap);\n\n if (isFunction(exec)) {\n actionObject = __assign(__assign({}, action), {\n exec: exec\n });\n } else if (exec) {\n var actionType = exec.type || action.type;\n actionObject = __assign(__assign(__assign({}, exec), action), {\n type: actionType\n });\n } else {\n actionObject = action;\n }\n }\n\n return actionObject;\n}\nvar toActionObjects = function (action, actionFunctionMap) {\n if (!action) {\n return [];\n }\n\n var actions = isArray(action) ? action : [action];\n return actions.map(function (subAction) {\n return toActionObject(subAction, actionFunctionMap);\n });\n};\nfunction toActivityDefinition(action) {\n var actionObject = toActionObject(action);\n return __assign(__assign({\n id: isString(action) ? action : actionObject.id\n }, actionObject), {\n type: actionObject.type\n });\n}\n/**\r\n * Raises an event. This places the event in the internal event queue, so that\r\n * the event is immediately consumed by the machine in the current step.\r\n *\r\n * @param eventType The event to raise.\r\n */\n\nfunction raise(event) {\n if (!isString(event)) {\n return send(event, {\n to: SpecialTargets.Internal\n });\n }\n\n return {\n type: raise$1,\n event: event\n };\n}\nfunction resolveRaise(action) {\n return {\n type: raise$1,\n _event: toSCXMLEvent(action.event)\n };\n}\n/**\r\n * Sends an event. This returns an action that will be read by an interpreter to\r\n * send the event in the next step, after the current step is finished executing.\r\n *\r\n * @param event The event to send.\r\n * @param options Options to pass into the send event:\r\n * - `id` - The unique send event identifier (used with `cancel()`).\r\n * - `delay` - The number of milliseconds to delay the sending of the event.\r\n * - `to` - The target of this event (by default, the machine the event was sent from).\r\n */\n\nfunction send(event, options) {\n return {\n to: options ? options.to : undefined,\n type: send$1,\n event: isFunction(event) ? event : toEventObject(event),\n delay: options ? options.delay : undefined,\n id: options && options.id !== undefined ? options.id : isFunction(event) ? event.name : getEventType(event)\n };\n}\nfunction resolveSend(action, ctx, _event, delaysMap) {\n var meta = {\n _event: _event\n }; // TODO: helper function for resolving Expr\n\n var resolvedEvent = toSCXMLEvent(isFunction(action.event) ? action.event(ctx, _event.data, meta) : action.event);\n var resolvedDelay;\n\n if (isString(action.delay)) {\n var configDelay = delaysMap && delaysMap[action.delay];\n resolvedDelay = isFunction(configDelay) ? configDelay(ctx, _event.data, meta) : configDelay;\n } else {\n resolvedDelay = isFunction(action.delay) ? action.delay(ctx, _event.data, meta) : action.delay;\n }\n\n var resolvedTarget = isFunction(action.to) ? action.to(ctx, _event.data, meta) : action.to;\n return __assign(__assign({}, action), {\n to: resolvedTarget,\n _event: resolvedEvent,\n event: resolvedEvent.data,\n delay: resolvedDelay\n });\n}\n/**\r\n * Sends an event to this machine's parent.\r\n *\r\n * @param event The event to send to the parent machine.\r\n * @param options Options to pass into the send event.\r\n */\n\nfunction sendParent(event, options) {\n return send(event, __assign(__assign({}, options), {\n to: SpecialTargets.Parent\n }));\n}\n/**\r\n * Sends an event to an actor.\r\n *\r\n * @param actor The `ActorRef` to send the event to.\r\n * @param event The event to send, or an expression that evaluates to the event to send\r\n * @param options Send action options\r\n * @returns An XState send action object\r\n */\n\nfunction sendTo(actor, event, options) {\n return send(event, __assign(__assign({}, options), {\n to: actor\n }));\n}\n/**\r\n * Sends an update event to this machine's parent.\r\n */\n\nfunction sendUpdate() {\n return sendParent(update);\n}\n/**\r\n * Sends an event back to the sender of the original event.\r\n *\r\n * @param event The event to send back to the sender\r\n * @param options Options to pass into the send event\r\n */\n\nfunction respond(event, options) {\n return send(event, __assign(__assign({}, options), {\n to: function (_, __, _a) {\n var _event = _a._event;\n return _event.origin; // TODO: handle when _event.origin is undefined\n }\n }));\n}\n\nvar defaultLogExpr = function (context, event) {\n return {\n context: context,\n event: event\n };\n};\n/**\r\n *\r\n * @param expr The expression function to evaluate which will be logged.\r\n * Takes in 2 arguments:\r\n * - `ctx` - the current state context\r\n * - `event` - the event that caused this action to be executed.\r\n * @param label The label to give to the logged expression.\r\n */\n\n\nfunction log(expr, label) {\n if (expr === void 0) {\n expr = defaultLogExpr;\n }\n\n return {\n type: log$1,\n label: label,\n expr: expr\n };\n}\nvar resolveLog = function (action, ctx, _event) {\n return __assign(__assign({}, action), {\n value: isString(action.expr) ? action.expr : action.expr(ctx, _event.data, {\n _event: _event\n })\n });\n};\n/**\r\n * Cancels an in-flight `send(...)` action. A canceled sent action will not\r\n * be executed, nor will its event be sent, unless it has already been sent\r\n * (e.g., if `cancel(...)` is called after the `send(...)` action's `delay`).\r\n *\r\n * @param sendId The `id` of the `send(...)` action to cancel.\r\n */\n\nvar cancel = function (sendId) {\n return {\n type: cancel$1,\n sendId: sendId\n };\n};\n/**\r\n * Starts an activity.\r\n *\r\n * @param activity The activity to start.\r\n */\n\nfunction start(activity) {\n var activityDef = toActivityDefinition(activity);\n return {\n type: ActionTypes.Start,\n activity: activityDef,\n exec: undefined\n };\n}\n/**\r\n * Stops an activity.\r\n *\r\n * @param actorRef The activity to stop.\r\n */\n\nfunction stop(actorRef) {\n var activity = isFunction(actorRef) ? actorRef : toActivityDefinition(actorRef);\n return {\n type: ActionTypes.Stop,\n activity: activity,\n exec: undefined\n };\n}\nfunction resolveStop(action, context, _event) {\n var actorRefOrString = isFunction(action.activity) ? action.activity(context, _event.data) : action.activity;\n var resolvedActorRef = typeof actorRefOrString === 'string' ? {\n id: actorRefOrString\n } : actorRefOrString;\n var actionObject = {\n type: ActionTypes.Stop,\n activity: resolvedActorRef\n };\n return actionObject;\n}\n/**\r\n * Updates the current context of the machine.\r\n *\r\n * @param assignment An object that represents the partial context to update.\r\n */\n\nvar assign = function (assignment) {\n return {\n type: assign$1,\n assignment: assignment\n };\n};\nfunction isActionObject(action) {\n return typeof action === 'object' && 'type' in action;\n}\n/**\r\n * Returns an event type that represents an implicit event that\r\n * is sent after the specified `delay`.\r\n *\r\n * @param delayRef The delay in milliseconds\r\n * @param id The state node ID where this event is handled\r\n */\n\nfunction after(delayRef, id) {\n var idSuffix = id ? \"#\".concat(id) : '';\n return \"\".concat(ActionTypes.After, \"(\").concat(delayRef, \")\").concat(idSuffix);\n}\n/**\r\n * Returns an event that represents that a final state node\r\n * has been reached in the parent state node.\r\n *\r\n * @param id The final state node's parent state node `id`\r\n * @param data The data to pass into the event\r\n */\n\nfunction done(id, data) {\n var type = \"\".concat(ActionTypes.DoneState, \".\").concat(id);\n var eventObject = {\n type: type,\n data: data\n };\n\n eventObject.toString = function () {\n return type;\n };\n\n return eventObject;\n}\n/**\r\n * Returns an event that represents that an invoked service has terminated.\r\n *\r\n * An invoked service is terminated when it has reached a top-level final state node,\r\n * but not when it is canceled.\r\n *\r\n * @param id The final state node ID\r\n * @param data The data to pass into the event\r\n */\n\nfunction doneInvoke(id, data) {\n var type = \"\".concat(ActionTypes.DoneInvoke, \".\").concat(id);\n var eventObject = {\n type: type,\n data: data\n };\n\n eventObject.toString = function () {\n return type;\n };\n\n return eventObject;\n}\nfunction error(id, data) {\n var type = \"\".concat(ActionTypes.ErrorPlatform, \".\").concat(id);\n var eventObject = {\n type: type,\n data: data\n };\n\n eventObject.toString = function () {\n return type;\n };\n\n return eventObject;\n}\nfunction pure(getActions) {\n return {\n type: ActionTypes.Pure,\n get: getActions\n };\n}\n/**\r\n * Forwards (sends) an event to a specified service.\r\n *\r\n * @param target The target service to forward the event to.\r\n * @param options Options to pass into the send action creator.\r\n */\n\nfunction forwardTo(target, options) {\n return send(function (_, event) {\n return event;\n }, __assign(__assign({}, options), {\n to: target\n }));\n}\n/**\r\n * Escalates an error by sending it as an event to this machine's parent.\r\n *\r\n * @param errorData The error data to send, or the expression function that\r\n * takes in the `context`, `event`, and `meta`, and returns the error data to send.\r\n * @param options Options to pass into the send action creator.\r\n */\n\nfunction escalate(errorData, options) {\n return sendParent(function (context, event, meta) {\n return {\n type: error$1,\n data: isFunction(errorData) ? errorData(context, event, meta) : errorData\n };\n }, __assign(__assign({}, options), {\n to: SpecialTargets.Parent\n }));\n}\nfunction choose(conds) {\n return {\n type: ActionTypes.Choose,\n conds: conds\n };\n}\nfunction resolveActions(machine, currentState, currentContext, _event, actions, preserveActionOrder) {\n if (preserveActionOrder === void 0) {\n preserveActionOrder = false;\n }\n\n var _a = __read(preserveActionOrder ? [[], actions] : partition(actions, function (action) {\n return action.type === assign$1;\n }), 2),\n assignActions = _a[0],\n otherActions = _a[1];\n\n var updatedContext = assignActions.length ? updateContext(currentContext, _event, assignActions, currentState) : currentContext;\n var preservedContexts = preserveActionOrder ? [currentContext] : undefined;\n var resolvedActions = flatten(otherActions.map(function (actionObject) {\n var _a;\n\n switch (actionObject.type) {\n case raise$1:\n return resolveRaise(actionObject);\n\n case send$1:\n var sendAction = resolveSend(actionObject, updatedContext, _event, machine.options.delays); // TODO: fix ActionTypes.Init\n\n if (!IS_PRODUCTION) {\n // warn after resolving as we can create better contextual message here\n warn(!isString(actionObject.delay) || typeof sendAction.delay === 'number', // tslint:disable-next-line:max-line-length\n \"No delay reference for delay expression '\".concat(actionObject.delay, \"' was found on machine '\").concat(machine.id, \"'\"));\n }\n\n return sendAction;\n\n case log$1:\n return resolveLog(actionObject, updatedContext, _event);\n\n case choose$1:\n {\n var chooseAction = actionObject;\n var matchedActions = (_a = chooseAction.conds.find(function (condition) {\n var guard = toGuard(condition.cond, machine.options.guards);\n return !guard || evaluateGuard(machine, guard, updatedContext, _event, currentState);\n })) === null || _a === void 0 ? void 0 : _a.actions;\n\n if (!matchedActions) {\n return [];\n }\n\n var _b = __read(resolveActions(machine, currentState, updatedContext, _event, toActionObjects(toArray(matchedActions), machine.options.actions), preserveActionOrder), 2),\n resolvedActionsFromChoose = _b[0],\n resolvedContextFromChoose = _b[1];\n\n updatedContext = resolvedContextFromChoose;\n preservedContexts === null || preservedContexts === void 0 ? void 0 : preservedContexts.push(updatedContext);\n return resolvedActionsFromChoose;\n }\n\n case pure$1:\n {\n var matchedActions = actionObject.get(updatedContext, _event.data);\n\n if (!matchedActions) {\n return [];\n }\n\n var _c = __read(resolveActions(machine, currentState, updatedContext, _event, toActionObjects(toArray(matchedActions), machine.options.actions), preserveActionOrder), 2),\n resolvedActionsFromPure = _c[0],\n resolvedContext = _c[1];\n\n updatedContext = resolvedContext;\n preservedContexts === null || preservedContexts === void 0 ? void 0 : preservedContexts.push(updatedContext);\n return resolvedActionsFromPure;\n }\n\n case stop$1:\n {\n return resolveStop(actionObject, updatedContext, _event);\n }\n\n case assign$1:\n {\n updatedContext = updateContext(updatedContext, _event, [actionObject], currentState);\n preservedContexts === null || preservedContexts === void 0 ? void 0 : preservedContexts.push(updatedContext);\n break;\n }\n\n default:\n var resolvedActionObject = toActionObject(actionObject, machine.options.actions);\n var exec_1 = resolvedActionObject.exec;\n\n if (exec_1 && preservedContexts) {\n var contextIndex_1 = preservedContexts.length - 1;\n resolvedActionObject = __assign(__assign({}, resolvedActionObject), {\n exec: function (_ctx) {\n var args = [];\n\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n\n exec_1.apply(void 0, __spreadArray([preservedContexts[contextIndex_1]], __read(args), false));\n }\n });\n }\n\n return resolvedActionObject;\n }\n }).filter(function (a) {\n return !!a;\n }));\n return [resolvedActions, updatedContext];\n}\n\nexport { after, assign, cancel, choose, done, doneInvoke, error, escalate, forwardTo, getActionFunction, initEvent, isActionObject, log, pure, raise, resolveActions, resolveLog, resolveRaise, resolveSend, resolveStop, respond, send, sendParent, sendTo, sendUpdate, start, stop, toActionObject, toActionObjects, toActivityDefinition };\n", "/**\r\n * Maintains a stack of the current service in scope.\r\n * This is used to provide the correct service to spawn().\r\n */\nvar serviceStack = [];\nvar provide = function (service, fn) {\n serviceStack.push(service);\n var result = fn(service);\n serviceStack.pop();\n return result;\n};\nvar consume = function (fn) {\n return fn(serviceStack[serviceStack.length - 1]);\n};\n\nexport { consume, provide };\n", "import { __assign } from './_virtual/_tslib.js';\nimport { symbolObservable, toInvokeSource, mapContext, isMachine } from './utils.js';\nimport { provide } from './serviceScope.js';\n\nfunction createNullActor(id) {\n var _a;\n\n return _a = {\n id: id,\n send: function () {\n return void 0;\n },\n subscribe: function () {\n return {\n unsubscribe: function () {\n return void 0;\n }\n };\n },\n getSnapshot: function () {\n return undefined;\n },\n toJSON: function () {\n return {\n id: id\n };\n }\n }, _a[symbolObservable] = function () {\n return this;\n }, _a;\n}\n/**\r\n * Creates a deferred actor that is able to be invoked given the provided\r\n * invocation information in its `.meta` value.\r\n *\r\n * @param invokeDefinition The meta information needed to invoke the actor.\r\n */\n\nfunction createInvocableActor(invokeDefinition, machine, context, _event) {\n var _a;\n\n var invokeSrc = toInvokeSource(invokeDefinition.src);\n var serviceCreator = (_a = machine === null || machine === void 0 ? void 0 : machine.options.services) === null || _a === void 0 ? void 0 : _a[invokeSrc.type];\n var resolvedData = invokeDefinition.data ? mapContext(invokeDefinition.data, context, _event) : undefined;\n var tempActor = serviceCreator ? createDeferredActor(serviceCreator, invokeDefinition.id, resolvedData) : createNullActor(invokeDefinition.id); // @ts-ignore\n\n tempActor.meta = invokeDefinition;\n return tempActor;\n}\nfunction createDeferredActor(entity, id, data) {\n var tempActor = createNullActor(id); // @ts-ignore\n\n tempActor.deferred = true;\n\n if (isMachine(entity)) {\n // \"mute\" the existing service scope so potential spawned actors within the `.initialState` stay deferred here\n var initialState_1 = tempActor.state = provide(undefined, function () {\n return (data ? entity.withContext(data) : entity).initialState;\n });\n\n tempActor.getSnapshot = function () {\n return initialState_1;\n };\n }\n\n return tempActor;\n}\nfunction isActor(item) {\n try {\n return typeof item.send === 'function';\n } catch (e) {\n return false;\n }\n}\nfunction isSpawnedActor(item) {\n return isActor(item) && 'id' in item;\n} // TODO: refactor the return type, this could be written in a better way but it's best to avoid unneccessary breaking changes now\n\nfunction toActorRef(actorRefLike) {\n var _a;\n\n return __assign((_a = {\n subscribe: function () {\n return {\n unsubscribe: function () {\n return void 0;\n }\n };\n },\n id: 'anonymous',\n getSnapshot: function () {\n return undefined;\n }\n }, _a[symbolObservable] = function () {\n return this;\n }, _a), actorRefLike);\n}\n\nexport { createDeferredActor, createInvocableActor, createNullActor, isActor, isSpawnedActor, toActorRef };\n", "import { __values, __spreadArray, __read } from './_virtual/_tslib.js';\nimport { flatten } from './utils.js';\n\nvar isLeafNode = function (stateNode) {\n return stateNode.type === 'atomic' || stateNode.type === 'final';\n};\nfunction getChildren(stateNode) {\n return Object.keys(stateNode.states).map(function (key) {\n return stateNode.states[key];\n }).filter(function (sn) {\n return sn.type !== 'history';\n });\n}\nfunction getAllStateNodes(stateNode) {\n var stateNodes = [stateNode];\n\n if (isLeafNode(stateNode)) {\n return stateNodes;\n }\n\n return stateNodes.concat(flatten(getChildren(stateNode).map(getAllStateNodes)));\n}\nfunction getConfiguration(prevStateNodes, stateNodes) {\n var e_1, _a, e_2, _b, e_3, _c, e_4, _d;\n\n var prevConfiguration = new Set(prevStateNodes);\n var prevAdjList = getAdjList(prevConfiguration);\n var configuration = new Set(stateNodes);\n\n try {\n // add all ancestors\n for (var configuration_1 = __values(configuration), configuration_1_1 = configuration_1.next(); !configuration_1_1.done; configuration_1_1 = configuration_1.next()) {\n var s = configuration_1_1.value;\n var m = s.parent;\n\n while (m && !configuration.has(m)) {\n configuration.add(m);\n m = m.parent;\n }\n }\n } catch (e_1_1) {\n e_1 = {\n error: e_1_1\n };\n } finally {\n try {\n if (configuration_1_1 && !configuration_1_1.done && (_a = configuration_1.return)) _a.call(configuration_1);\n } finally {\n if (e_1) throw e_1.error;\n }\n }\n\n var adjList = getAdjList(configuration);\n\n try {\n // add descendants\n for (var configuration_2 = __values(configuration), configuration_2_1 = configuration_2.next(); !configuration_2_1.done; configuration_2_1 = configuration_2.next()) {\n var s = configuration_2_1.value; // if previously active, add existing child nodes\n\n if (s.type === 'compound' && (!adjList.get(s) || !adjList.get(s).length)) {\n if (prevAdjList.get(s)) {\n prevAdjList.get(s).forEach(function (sn) {\n return configuration.add(sn);\n });\n } else {\n s.initialStateNodes.forEach(function (sn) {\n return configuration.add(sn);\n });\n }\n } else {\n if (s.type === 'parallel') {\n try {\n for (var _e = (e_3 = void 0, __values(getChildren(s))), _f = _e.next(); !_f.done; _f = _e.next()) {\n var child = _f.value;\n\n if (!configuration.has(child)) {\n configuration.add(child);\n\n if (prevAdjList.get(child)) {\n prevAdjList.get(child).forEach(function (sn) {\n return configuration.add(sn);\n });\n } else {\n child.initialStateNodes.forEach(function (sn) {\n return configuration.add(sn);\n });\n }\n }\n }\n } catch (e_3_1) {\n e_3 = {\n error: e_3_1\n };\n } finally {\n try {\n if (_f && !_f.done && (_c = _e.return)) _c.call(_e);\n } finally {\n if (e_3) throw e_3.error;\n }\n }\n }\n }\n }\n } catch (e_2_1) {\n e_2 = {\n error: e_2_1\n };\n } finally {\n try {\n if (configuration_2_1 && !configuration_2_1.done && (_b = configuration_2.return)) _b.call(configuration_2);\n } finally {\n if (e_2) throw e_2.error;\n }\n }\n\n try {\n // add all ancestors\n for (var configuration_3 = __values(configuration), configuration_3_1 = configuration_3.next(); !configuration_3_1.done; configuration_3_1 = configuration_3.next()) {\n var s = configuration_3_1.value;\n var m = s.parent;\n\n while (m && !configuration.has(m)) {\n configuration.add(m);\n m = m.parent;\n }\n }\n } catch (e_4_1) {\n e_4 = {\n error: e_4_1\n };\n } finally {\n try {\n if (configuration_3_1 && !configuration_3_1.done && (_d = configuration_3.return)) _d.call(configuration_3);\n } finally {\n if (e_4) throw e_4.error;\n }\n }\n\n return configuration;\n}\n\nfunction getValueFromAdj(baseNode, adjList) {\n var childStateNodes = adjList.get(baseNode);\n\n if (!childStateNodes) {\n return {}; // todo: fix?\n }\n\n if (baseNode.type === 'compound') {\n var childStateNode = childStateNodes[0];\n\n if (childStateNode) {\n if (isLeafNode(childStateNode)) {\n return childStateNode.key;\n }\n } else {\n return {};\n }\n }\n\n var stateValue = {};\n childStateNodes.forEach(function (csn) {\n stateValue[csn.key] = getValueFromAdj(csn, adjList);\n });\n return stateValue;\n}\n\nfunction getAdjList(configuration) {\n var e_5, _a;\n\n var adjList = new Map();\n\n try {\n for (var configuration_4 = __values(configuration), configuration_4_1 = configuration_4.next(); !configuration_4_1.done; configuration_4_1 = configuration_4.next()) {\n var s = configuration_4_1.value;\n\n if (!adjList.has(s)) {\n adjList.set(s, []);\n }\n\n if (s.parent) {\n if (!adjList.has(s.parent)) {\n adjList.set(s.parent, []);\n }\n\n adjList.get(s.parent).push(s);\n }\n }\n } catch (e_5_1) {\n e_5 = {\n error: e_5_1\n };\n } finally {\n try {\n if (configuration_4_1 && !configuration_4_1.done && (_a = configuration_4.return)) _a.call(configuration_4);\n } finally {\n if (e_5) throw e_5.error;\n }\n }\n\n return adjList;\n}\nfunction getValue(rootNode, configuration) {\n var config = getConfiguration([rootNode], configuration);\n return getValueFromAdj(rootNode, getAdjList(config));\n}\nfunction has(iterable, item) {\n if (Array.isArray(iterable)) {\n return iterable.some(function (member) {\n return member === item;\n });\n }\n\n if (iterable instanceof Set) {\n return iterable.has(item);\n }\n\n return false; // TODO: fix\n}\nfunction nextEvents(configuration) {\n return __spreadArray([], __read(new Set(flatten(__spreadArray([], __read(configuration.map(function (sn) {\n return sn.ownEvents;\n })), false)))), false);\n}\nfunction isInFinalState(configuration, stateNode) {\n if (stateNode.type === 'compound') {\n return getChildren(stateNode).some(function (s) {\n return s.type === 'final' && has(configuration, s);\n });\n }\n\n if (stateNode.type === 'parallel') {\n return getChildren(stateNode).every(function (sn) {\n return isInFinalState(configuration, sn);\n });\n }\n\n return false;\n}\nfunction getMeta(configuration) {\n if (configuration === void 0) {\n configuration = [];\n }\n\n return configuration.reduce(function (acc, stateNode) {\n if (stateNode.meta !== undefined) {\n acc[stateNode.id] = stateNode.meta;\n }\n\n return acc;\n }, {});\n}\nfunction getTagsFromConfiguration(configuration) {\n return new Set(flatten(configuration.map(function (sn) {\n return sn.tags;\n })));\n}\n\nexport { getAdjList, getAllStateNodes, getChildren, getConfiguration, getMeta, getTagsFromConfiguration, getValue, has, isInFinalState, isLeafNode, nextEvents };\n", "import { __assign, __spreadArray, __read, __rest } from './_virtual/_tslib.js';\nimport { EMPTY_ACTIVITY_MAP } from './constants.js';\nimport { isString, matchesState, warn } from './utils.js';\nimport { getMeta, nextEvents } from './stateUtils.js';\nimport { initEvent } from './actions.js';\nimport { IS_PRODUCTION } from './environment.js';\n\nfunction stateValuesEqual(a, b) {\n if (a === b) {\n return true;\n }\n\n if (a === undefined || b === undefined) {\n return false;\n }\n\n if (isString(a) || isString(b)) {\n return a === b;\n }\n\n var aKeys = Object.keys(a);\n var bKeys = Object.keys(b);\n return aKeys.length === bKeys.length && aKeys.every(function (key) {\n return stateValuesEqual(a[key], b[key]);\n });\n}\nfunction isStateConfig(state) {\n if (typeof state !== 'object' || state === null) {\n return false;\n }\n\n return 'value' in state && '_event' in state;\n}\n/**\r\n * @deprecated Use `isStateConfig(object)` or `state instanceof State` instead.\r\n */\n\nvar isState = isStateConfig;\nfunction bindActionToState(action, state) {\n var exec = action.exec;\n\n var boundAction = __assign(__assign({}, action), {\n exec: exec !== undefined ? function () {\n return exec(state.context, state.event, {\n action: action,\n state: state,\n _event: state._event\n });\n } : undefined\n });\n\n return boundAction;\n}\n\nvar State =\n/*#__PURE__*/\n\n/** @class */\nfunction () {\n /**\r\n * Creates a new State instance.\r\n * @param value The state value\r\n * @param context The extended state\r\n * @param historyValue The tree representing historical values of the state nodes\r\n * @param history The previous state\r\n * @param actions An array of action objects to execute as side-effects\r\n * @param activities A mapping of activities and whether they are started (`true`) or stopped (`false`).\r\n * @param meta\r\n * @param events Internal event queue. Should be empty with run-to-completion semantics.\r\n * @param configuration\r\n */\n function State(config) {\n var _this = this;\n\n var _a;\n\n this.actions = [];\n this.activities = EMPTY_ACTIVITY_MAP;\n this.meta = {};\n this.events = [];\n this.value = config.value;\n this.context = config.context;\n this._event = config._event;\n this._sessionid = config._sessionid;\n this.event = this._event.data;\n this.historyValue = config.historyValue;\n this.history = config.history;\n this.actions = config.actions || [];\n this.activities = config.activities || EMPTY_ACTIVITY_MAP;\n this.meta = getMeta(config.configuration);\n this.events = config.events || [];\n this.matches = this.matches.bind(this);\n this.toStrings = this.toStrings.bind(this);\n this.configuration = config.configuration;\n this.transitions = config.transitions;\n this.children = config.children;\n this.done = !!config.done;\n this.tags = (_a = Array.isArray(config.tags) ? new Set(config.tags) : config.tags) !== null && _a !== void 0 ? _a : new Set();\n this.machine = config.machine;\n Object.defineProperty(this, 'nextEvents', {\n get: function () {\n return nextEvents(_this.configuration);\n }\n });\n }\n /**\r\n * Creates a new State instance for the given `stateValue` and `context`.\r\n * @param stateValue\r\n * @param context\r\n */\n\n\n State.from = function (stateValue, context) {\n if (stateValue instanceof State) {\n if (stateValue.context !== context) {\n return new State({\n value: stateValue.value,\n context: context,\n _event: stateValue._event,\n _sessionid: null,\n historyValue: stateValue.historyValue,\n history: stateValue.history,\n actions: [],\n activities: stateValue.activities,\n meta: {},\n events: [],\n configuration: [],\n transitions: [],\n children: {}\n });\n }\n\n return stateValue;\n }\n\n var _event = initEvent;\n return new State({\n value: stateValue,\n context: context,\n _event: _event,\n _sessionid: null,\n historyValue: undefined,\n history: undefined,\n actions: [],\n activities: undefined,\n meta: undefined,\n events: [],\n configuration: [],\n transitions: [],\n children: {}\n });\n };\n /**\r\n * Creates a new State instance for the given `config`.\r\n * @param config The state config\r\n */\n\n\n State.create = function (config) {\n return new State(config);\n };\n /**\r\n * Creates a new `State` instance for the given `stateValue` and `context` with no actions (side-effects).\r\n * @param stateValue\r\n * @param context\r\n */\n\n\n State.inert = function (stateValue, context) {\n if (stateValue instanceof State) {\n if (!stateValue.actions.length) {\n return stateValue;\n }\n\n var _event = initEvent;\n return new State({\n value: stateValue.value,\n context: context,\n _event: _event,\n _sessionid: null,\n historyValue: stateValue.historyValue,\n history: stateValue.history,\n activities: stateValue.activities,\n configuration: stateValue.configuration,\n transitions: [],\n children: {}\n });\n }\n\n return State.from(stateValue, context);\n };\n /**\r\n * Returns an array of all the string leaf state node paths.\r\n * @param stateValue\r\n * @param delimiter The character(s) that separate each subpath in the string state node path.\r\n */\n\n\n State.prototype.toStrings = function (stateValue, delimiter) {\n var _this = this;\n\n if (stateValue === void 0) {\n stateValue = this.value;\n }\n\n if (delimiter === void 0) {\n delimiter = '.';\n }\n\n if (isString(stateValue)) {\n return [stateValue];\n }\n\n var valueKeys = Object.keys(stateValue);\n return valueKeys.concat.apply(valueKeys, __spreadArray([], __read(valueKeys.map(function (key) {\n return _this.toStrings(stateValue[key], delimiter).map(function (s) {\n return key + delimiter + s;\n });\n })), false));\n };\n\n State.prototype.toJSON = function () {\n var _a = this;\n _a.configuration;\n _a.transitions;\n var tags = _a.tags;\n _a.machine;\n var jsonValues = __rest(_a, [\"configuration\", \"transitions\", \"tags\", \"machine\"]);\n\n return __assign(__assign({}, jsonValues), {\n tags: Array.from(tags)\n });\n };\n\n State.prototype.matches = function (parentStateValue) {\n return matchesState(parentStateValue, this.value);\n };\n /**\r\n * Whether the current state configuration has a state node with the specified `tag`.\r\n * @param tag\r\n */\n\n\n State.prototype.hasTag = function (tag) {\n return this.tags.has(tag);\n };\n /**\r\n * Determines whether sending the `event` will cause a non-forbidden transition\r\n * to be selected, even if the transitions have no actions nor\r\n * change the state value.\r\n *\r\n * @param event The event to test\r\n * @returns Whether the event will cause a transition\r\n */\n\n\n State.prototype.can = function (event) {\n var _a;\n\n if (IS_PRODUCTION) {\n warn(!!this.machine, \"state.can(...) used outside of a machine-created State object; this will always return false.\");\n }\n\n var transitionData = (_a = this.machine) === null || _a === void 0 ? void 0 : _a.getTransitionData(this, event);\n return !!(transitionData === null || transitionData === void 0 ? void 0 : transitionData.transitions.length) && // Check that at least one transition is not forbidden\n transitionData.transitions.some(function (t) {\n return t.target !== undefined || t.actions.length;\n });\n };\n\n return State;\n}();\n\nexport { State, bindActionToState, isState, isStateConfig, stateValuesEqual };\n", "import { __assign } from './_virtual/_tslib.js';\n\nvar defaultOptions = {\n deferEvents: false\n};\n\nvar Scheduler =\n/*#__PURE__*/\n\n/** @class */\nfunction () {\n function Scheduler(options) {\n this.processingEvent = false;\n this.queue = [];\n this.initialized = false;\n this.options = __assign(__assign({}, defaultOptions), options);\n }\n\n Scheduler.prototype.initialize = function (callback) {\n this.initialized = true;\n\n if (callback) {\n if (!this.options.deferEvents) {\n this.schedule(callback);\n return;\n }\n\n this.process(callback);\n }\n\n this.flushEvents();\n };\n\n Scheduler.prototype.schedule = function (task) {\n if (!this.initialized || this.processingEvent) {\n this.queue.push(task);\n return;\n }\n\n if (this.queue.length !== 0) {\n throw new Error('Event queue should be empty when it is not processing events');\n }\n\n this.process(task);\n this.flushEvents();\n };\n\n Scheduler.prototype.clear = function () {\n this.queue = [];\n };\n\n Scheduler.prototype.flushEvents = function () {\n var nextCallback = this.queue.shift();\n\n while (nextCallback) {\n this.process(nextCallback);\n nextCallback = this.queue.shift();\n }\n };\n\n Scheduler.prototype.process = function (callback) {\n this.processingEvent = true;\n\n try {\n callback();\n } catch (e) {\n // there is no use to keep the future events\n // as the situation is not anymore the same\n this.clear();\n throw e;\n } finally {\n this.processingEvent = false;\n }\n };\n\n return Scheduler;\n}();\n\nexport { Scheduler };\n", "var children = /*#__PURE__*/new Map();\nvar sessionIdIndex = 0;\nvar registry = {\n bookId: function () {\n return \"x:\".concat(sessionIdIndex++);\n },\n register: function (id, actor) {\n children.set(id, actor);\n return id;\n },\n get: function (id) {\n return children.get(id);\n },\n free: function (id) {\n children.delete(id);\n }\n};\n\nexport { registry };\n", "import { IS_PRODUCTION } from './environment.js';\n\nfunction getGlobal() {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n }\n\n if (typeof self !== 'undefined') {\n return self;\n }\n\n if (typeof window !== 'undefined') {\n return window;\n }\n\n if (typeof global !== 'undefined') {\n return global;\n }\n\n if (!IS_PRODUCTION) {\n console.warn('XState could not find a global object in this environment. Please let the maintainers know and raise an issue here: https://github.com/statelyai/xstate/issues');\n }\n}\n\nfunction getDevTools() {\n var global = getGlobal();\n\n if (global && '__xstate__' in global) {\n return global.__xstate__;\n }\n\n return undefined;\n}\n\nfunction registerService(service) {\n if (!getGlobal()) {\n return;\n }\n\n var devTools = getDevTools();\n\n if (devTools) {\n devTools.register(service);\n }\n}\n\nexport { getGlobal, registerService };\n", "import { error, doneInvoke } from './actions.js';\nimport { toActorRef } from './Actor.js';\nimport { toObserver } from './utils.js';\n\n/**\r\n * Returns an actor behavior from a reducer and its initial state.\r\n *\r\n * @param transition The pure reducer that returns the next state given the current state and event.\r\n * @param initialState The initial state of the reducer.\r\n * @returns An actor behavior\r\n */\n\nfunction fromReducer(transition, initialState) {\n return {\n transition: transition,\n initialState: initialState\n };\n}\nfunction fromPromise(promiseFn) {\n var initialState = {\n error: undefined,\n data: undefined,\n status: 'pending'\n };\n return {\n transition: function (state, event, _a) {\n var parent = _a.parent,\n id = _a.id,\n observers = _a.observers;\n\n switch (event.type) {\n case 'fulfill':\n parent === null || parent === void 0 ? void 0 : parent.send(doneInvoke(id, event.data));\n return {\n error: undefined,\n data: event.data,\n status: 'fulfilled'\n };\n\n case 'reject':\n parent === null || parent === void 0 ? void 0 : parent.send(error(id, event.error));\n observers.forEach(function (observer) {\n observer.error(event.error);\n });\n return {\n error: event.error,\n data: undefined,\n status: 'rejected'\n };\n\n default:\n return state;\n }\n },\n initialState: initialState,\n start: function (_a) {\n var self = _a.self;\n promiseFn().then(function (data) {\n self.send({\n type: 'fulfill',\n data: data\n });\n }, function (reason) {\n self.send({\n type: 'reject',\n error: reason\n });\n });\n return initialState;\n }\n };\n}\nfunction spawnBehavior(behavior, options) {\n if (options === void 0) {\n options = {};\n }\n\n var state = behavior.initialState;\n var observers = new Set();\n var mailbox = [];\n var flushing = false;\n\n var flush = function () {\n if (flushing) {\n return;\n }\n\n flushing = true;\n\n while (mailbox.length > 0) {\n var event_1 = mailbox.shift();\n state = behavior.transition(state, event_1, actorCtx);\n observers.forEach(function (observer) {\n return observer.next(state);\n });\n }\n\n flushing = false;\n };\n\n var actor = toActorRef({\n id: options.id,\n send: function (event) {\n mailbox.push(event);\n flush();\n },\n getSnapshot: function () {\n return state;\n },\n subscribe: function (next, handleError, complete) {\n var observer = toObserver(next, handleError, complete);\n observers.add(observer);\n observer.next(state);\n return {\n unsubscribe: function () {\n observers.delete(observer);\n }\n };\n }\n });\n var actorCtx = {\n parent: options.parent,\n self: actor,\n id: options.id || 'anonymous',\n observers: observers\n };\n state = behavior.start ? behavior.start(actorCtx) : state;\n return actor;\n}\n\nexport { fromPromise, fromReducer, spawnBehavior };\n", "import { __values, __spreadArray, __read, __assign } from './_virtual/_tslib.js';\nimport { ActionTypes, SpecialTargets } from './types.js';\nimport { isStateConfig, State, bindActionToState } from './State.js';\nimport { errorPlatform, log, stop, start, cancel, send, update, error as error$1 } from './actionTypes.js';\nimport { doneInvoke, initEvent, getActionFunction, error } from './actions.js';\nimport { IS_PRODUCTION } from './environment.js';\nimport { warn, mapContext, isFunction, toSCXMLEvent, toInvokeSource, isMachine, isPromiseLike, isObservable, isBehavior, reportUnhandledExceptionOnInvocation, symbolObservable, isArray, toEventObject, isString, isActor, uniqueId, toObserver } from './utils.js';\nimport { Scheduler } from './scheduler.js';\nimport { isSpawnedActor, createDeferredActor } from './Actor.js';\nimport { isInFinalState } from './stateUtils.js';\nimport { registry } from './registry.js';\nimport { getGlobal, registerService } from './devTools.js';\nimport { provide, consume } from './serviceScope.js';\nimport { spawnBehavior } from './behaviors.js';\n\nvar DEFAULT_SPAWN_OPTIONS = {\n sync: false,\n autoForward: false\n};\nvar InterpreterStatus;\n\n(function (InterpreterStatus) {\n InterpreterStatus[InterpreterStatus[\"NotStarted\"] = 0] = \"NotStarted\";\n InterpreterStatus[InterpreterStatus[\"Running\"] = 1] = \"Running\";\n InterpreterStatus[InterpreterStatus[\"Stopped\"] = 2] = \"Stopped\";\n})(InterpreterStatus || (InterpreterStatus = {}));\n\nvar Interpreter =\n/*#__PURE__*/\n\n/** @class */\nfunction () {\n /**\r\n * Creates a new Interpreter instance (i.e., service) for the given machine with the provided options, if any.\r\n *\r\n * @param machine The machine to be interpreted\r\n * @param options Interpreter options\r\n */\n function Interpreter(machine, options) {\n var _this = this;\n\n if (options === void 0) {\n options = Interpreter.defaultOptions;\n }\n\n this.machine = machine;\n this.delayedEventsMap = {};\n this.listeners = new Set();\n this.contextListeners = new Set();\n this.stopListeners = new Set();\n this.doneListeners = new Set();\n this.eventListeners = new Set();\n this.sendListeners = new Set();\n /**\r\n * Whether the service is started.\r\n */\n\n this.initialized = false;\n this.status = InterpreterStatus.NotStarted;\n this.children = new Map();\n this.forwardTo = new Set();\n /**\r\n * Alias for Interpreter.prototype.start\r\n */\n\n this.init = this.start;\n /**\r\n * Sends an event to the running interpreter to trigger a transition.\r\n *\r\n * An array of events (batched) can be sent as well, which will send all\r\n * batched events to the running interpreter. The listeners will be\r\n * notified only **once** when all events are processed.\r\n *\r\n * @param event The event(s) to send\r\n */\n\n this.send = function (event, payload) {\n if (isArray(event)) {\n _this.batch(event);\n\n return _this.state;\n }\n\n var _event = toSCXMLEvent(toEventObject(event, payload));\n\n if (_this.status === InterpreterStatus.Stopped) {\n // do nothing\n if (!IS_PRODUCTION) {\n warn(false, \"Event \\\"\".concat(_event.name, \"\\\" was sent to stopped service \\\"\").concat(_this.machine.id, \"\\\". This service has already reached its final state, and will not transition.\\nEvent: \").concat(JSON.stringify(_event.data)));\n }\n\n return _this.state;\n }\n\n if (_this.status !== InterpreterStatus.Running && !_this.options.deferEvents) {\n throw new Error(\"Event \\\"\".concat(_event.name, \"\\\" was sent to uninitialized service \\\"\").concat(_this.machine.id // tslint:disable-next-line:max-line-length\n , \"\\\". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.\\nEvent: \").concat(JSON.stringify(_event.data)));\n }\n\n _this.scheduler.schedule(function () {\n // Forward copy of event to child actors\n _this.forward(_event);\n\n var nextState = _this.nextState(_event);\n\n _this.update(nextState, _event);\n });\n\n return _this._state; // TODO: deprecate (should return void)\n // tslint:disable-next-line:semicolon\n };\n\n this.sendTo = function (event, to) {\n var isParent = _this.parent && (to === SpecialTargets.Parent || _this.parent.id === to);\n var target = isParent ? _this.parent : isString(to) ? _this.children.get(to) || registry.get(to) : isActor(to) ? to : undefined;\n\n if (!target) {\n if (!isParent) {\n throw new Error(\"Unable to send event to child '\".concat(to, \"' from service '\").concat(_this.id, \"'.\"));\n } // tslint:disable-next-line:no-console\n\n\n if (!IS_PRODUCTION) {\n warn(false, \"Service '\".concat(_this.id, \"' has no parent: unable to send event \").concat(event.type));\n }\n\n return;\n }\n\n if ('machine' in target) {\n // Send SCXML events to machines\n target.send(__assign(__assign({}, event), {\n name: event.name === error$1 ? \"\".concat(error(_this.id)) : event.name,\n origin: _this.sessionId\n }));\n } else {\n // Send normal events to other targets\n target.send(event.data);\n }\n };\n\n var resolvedOptions = __assign(__assign({}, Interpreter.defaultOptions), options);\n\n var clock = resolvedOptions.clock,\n logger = resolvedOptions.logger,\n parent = resolvedOptions.parent,\n id = resolvedOptions.id;\n var resolvedId = id !== undefined ? id : machine.id;\n this.id = resolvedId;\n this.logger = logger;\n this.clock = clock;\n this.parent = parent;\n this.options = resolvedOptions;\n this.scheduler = new Scheduler({\n deferEvents: this.options.deferEvents\n });\n this.sessionId = registry.bookId();\n }\n\n Object.defineProperty(Interpreter.prototype, \"initialState\", {\n get: function () {\n var _this = this;\n\n if (this._initialState) {\n return this._initialState;\n }\n\n return provide(this, function () {\n _this._initialState = _this.machine.initialState;\n return _this._initialState;\n });\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(Interpreter.prototype, \"state\", {\n get: function () {\n if (!IS_PRODUCTION) {\n warn(this.status !== InterpreterStatus.NotStarted, \"Attempted to read state from uninitialized service '\".concat(this.id, \"'. Make sure the service is started first.\"));\n }\n\n return this._state;\n },\n enumerable: false,\n configurable: true\n });\n /**\r\n * Executes the actions of the given state, with that state's `context` and `event`.\r\n *\r\n * @param state The state whose actions will be executed\r\n * @param actionsConfig The action implementations to use\r\n */\n\n Interpreter.prototype.execute = function (state, actionsConfig) {\n var e_1, _a;\n\n try {\n for (var _b = __values(state.actions), _c = _b.next(); !_c.done; _c = _b.next()) {\n var action = _c.value;\n this.exec(action, state, actionsConfig);\n }\n } catch (e_1_1) {\n e_1 = {\n error: e_1_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n } finally {\n if (e_1) throw e_1.error;\n }\n }\n };\n\n Interpreter.prototype.update = function (state, _event) {\n var e_2, _a, e_3, _b, e_4, _c, e_5, _d;\n\n var _this = this; // Attach session ID to state\n\n\n state._sessionid = this.sessionId; // Update state\n\n this._state = state; // Execute actions\n\n if (this.options.execute) {\n this.execute(this.state);\n } // Update children\n\n\n this.children.forEach(function (child) {\n _this.state.children[child.id] = child;\n }); // Dev tools\n\n if (this.devTools) {\n this.devTools.send(_event.data, state);\n } // Execute listeners\n\n\n if (state.event) {\n try {\n for (var _e = __values(this.eventListeners), _f = _e.next(); !_f.done; _f = _e.next()) {\n var listener = _f.value;\n listener(state.event);\n }\n } catch (e_2_1) {\n e_2 = {\n error: e_2_1\n };\n } finally {\n try {\n if (_f && !_f.done && (_a = _e.return)) _a.call(_e);\n } finally {\n if (e_2) throw e_2.error;\n }\n }\n }\n\n try {\n for (var _g = __values(this.listeners), _h = _g.next(); !_h.done; _h = _g.next()) {\n var listener = _h.value;\n listener(state, state.event);\n }\n } catch (e_3_1) {\n e_3 = {\n error: e_3_1\n };\n } finally {\n try {\n if (_h && !_h.done && (_b = _g.return)) _b.call(_g);\n } finally {\n if (e_3) throw e_3.error;\n }\n }\n\n try {\n for (var _j = __values(this.contextListeners), _k = _j.next(); !_k.done; _k = _j.next()) {\n var contextListener = _k.value;\n contextListener(this.state.context, this.state.history ? this.state.history.context : undefined);\n }\n } catch (e_4_1) {\n e_4 = {\n error: e_4_1\n };\n } finally {\n try {\n if (_k && !_k.done && (_c = _j.return)) _c.call(_j);\n } finally {\n if (e_4) throw e_4.error;\n }\n }\n\n var isDone = isInFinalState(state.configuration || [], this.machine);\n\n if (this.state.configuration && isDone) {\n // get final child state node\n var finalChildStateNode = state.configuration.find(function (sn) {\n return sn.type === 'final' && sn.parent === _this.machine;\n });\n var doneData = finalChildStateNode && finalChildStateNode.doneData ? mapContext(finalChildStateNode.doneData, state.context, _event) : undefined;\n\n try {\n for (var _l = __values(this.doneListeners), _m = _l.next(); !_m.done; _m = _l.next()) {\n var listener = _m.value;\n listener(doneInvoke(this.id, doneData));\n }\n } catch (e_5_1) {\n e_5 = {\n error: e_5_1\n };\n } finally {\n try {\n if (_m && !_m.done && (_d = _l.return)) _d.call(_l);\n } finally {\n if (e_5) throw e_5.error;\n }\n }\n\n this.stop();\n }\n };\n /*\r\n * Adds a listener that is notified whenever a state transition happens. The listener is called with\r\n * the next state and the event object that caused the state transition.\r\n *\r\n * @param listener The state listener\r\n */\n\n\n Interpreter.prototype.onTransition = function (listener) {\n this.listeners.add(listener); // Send current state to listener\n\n if (this.status === InterpreterStatus.Running) {\n listener(this.state, this.state.event);\n }\n\n return this;\n };\n\n Interpreter.prototype.subscribe = function (nextListenerOrObserver, _, // TODO: error listener\n completeListener) {\n var _this = this;\n\n if (!nextListenerOrObserver) {\n return {\n unsubscribe: function () {\n return void 0;\n }\n };\n }\n\n var listener;\n var resolvedCompleteListener = completeListener;\n\n if (typeof nextListenerOrObserver === 'function') {\n listener = nextListenerOrObserver;\n } else {\n listener = nextListenerOrObserver.next.bind(nextListenerOrObserver);\n resolvedCompleteListener = nextListenerOrObserver.complete.bind(nextListenerOrObserver);\n }\n\n this.listeners.add(listener); // Send current state to listener\n\n if (this.status !== InterpreterStatus.NotStarted) {\n listener(this.state);\n }\n\n if (resolvedCompleteListener) {\n if (this.status === InterpreterStatus.Stopped) {\n resolvedCompleteListener();\n } else {\n this.onDone(resolvedCompleteListener);\n }\n }\n\n return {\n unsubscribe: function () {\n listener && _this.listeners.delete(listener);\n resolvedCompleteListener && _this.doneListeners.delete(resolvedCompleteListener);\n }\n };\n };\n /**\r\n * Adds an event listener that is notified whenever an event is sent to the running interpreter.\r\n * @param listener The event listener\r\n */\n\n\n Interpreter.prototype.onEvent = function (listener) {\n this.eventListeners.add(listener);\n return this;\n };\n /**\r\n * Adds an event listener that is notified whenever a `send` event occurs.\r\n * @param listener The event listener\r\n */\n\n\n Interpreter.prototype.onSend = function (listener) {\n this.sendListeners.add(listener);\n return this;\n };\n /**\r\n * Adds a context listener that is notified whenever the state context changes.\r\n * @param listener The context listener\r\n */\n\n\n Interpreter.prototype.onChange = function (listener) {\n this.contextListeners.add(listener);\n return this;\n };\n /**\r\n * Adds a listener that is notified when the machine is stopped.\r\n * @param listener The listener\r\n */\n\n\n Interpreter.prototype.onStop = function (listener) {\n this.stopListeners.add(listener);\n return this;\n };\n /**\r\n * Adds a state listener that is notified when the statechart has reached its final state.\r\n * @param listener The state listener\r\n */\n\n\n Interpreter.prototype.onDone = function (listener) {\n this.doneListeners.add(listener);\n return this;\n };\n /**\r\n * Removes a listener.\r\n * @param listener The listener to remove\r\n */\n\n\n Interpreter.prototype.off = function (listener) {\n this.listeners.delete(listener);\n this.eventListeners.delete(listener);\n this.sendListeners.delete(listener);\n this.stopListeners.delete(listener);\n this.doneListeners.delete(listener);\n this.contextListeners.delete(listener);\n return this;\n };\n /**\r\n * Starts the interpreter from the given state, or the initial state.\r\n * @param initialState The state to start the statechart from\r\n */\n\n\n Interpreter.prototype.start = function (initialState) {\n var _this = this;\n\n if (this.status === InterpreterStatus.Running) {\n // Do not restart the service if it is already started\n return this;\n } // yes, it's a hack but we need the related cache to be populated for some things to work (like delayed transitions)\n // this is usually called by `machine.getInitialState` but if we rehydrate from a state we might bypass this call\n // we also don't want to call this method here as it resolves the full initial state which might involve calling assign actions\n // and that could potentially lead to some unwanted side-effects (even such as creating some rogue actors)\n\n\n this.machine._init();\n\n registry.register(this.sessionId, this);\n this.initialized = true;\n this.status = InterpreterStatus.Running;\n var resolvedState = initialState === undefined ? this.initialState : provide(this, function () {\n return isStateConfig(initialState) ? _this.machine.resolveState(initialState) : _this.machine.resolveState(State.from(initialState, _this.machine.context));\n });\n\n if (this.options.devTools) {\n this.attachDev();\n }\n\n this.scheduler.initialize(function () {\n _this.update(resolvedState, initEvent);\n });\n return this;\n };\n /**\r\n * Stops the interpreter and unsubscribe all listeners.\r\n *\r\n * This will also notify the `onStop` listeners.\r\n */\n\n\n Interpreter.prototype.stop = function () {\n var e_6, _a, e_7, _b, e_8, _c, e_9, _d, e_10, _e;\n\n var _this = this;\n\n try {\n for (var _f = __values(this.listeners), _g = _f.next(); !_g.done; _g = _f.next()) {\n var listener = _g.value;\n this.listeners.delete(listener);\n }\n } catch (e_6_1) {\n e_6 = {\n error: e_6_1\n };\n } finally {\n try {\n if (_g && !_g.done && (_a = _f.return)) _a.call(_f);\n } finally {\n if (e_6) throw e_6.error;\n }\n }\n\n try {\n for (var _h = __values(this.stopListeners), _j = _h.next(); !_j.done; _j = _h.next()) {\n var listener = _j.value; // call listener, then remove\n\n listener();\n this.stopListeners.delete(listener);\n }\n } catch (e_7_1) {\n e_7 = {\n error: e_7_1\n };\n } finally {\n try {\n if (_j && !_j.done && (_b = _h.return)) _b.call(_h);\n } finally {\n if (e_7) throw e_7.error;\n }\n }\n\n try {\n for (var _k = __values(this.contextListeners), _l = _k.next(); !_l.done; _l = _k.next()) {\n var listener = _l.value;\n this.contextListeners.delete(listener);\n }\n } catch (e_8_1) {\n e_8 = {\n error: e_8_1\n };\n } finally {\n try {\n if (_l && !_l.done && (_c = _k.return)) _c.call(_k);\n } finally {\n if (e_8) throw e_8.error;\n }\n }\n\n try {\n for (var _m = __values(this.doneListeners), _o = _m.next(); !_o.done; _o = _m.next()) {\n var listener = _o.value;\n this.doneListeners.delete(listener);\n }\n } catch (e_9_1) {\n e_9 = {\n error: e_9_1\n };\n } finally {\n try {\n if (_o && !_o.done && (_d = _m.return)) _d.call(_m);\n } finally {\n if (e_9) throw e_9.error;\n }\n }\n\n if (!this.initialized) {\n // Interpreter already stopped; do nothing\n return this;\n }\n\n __spreadArray([], __read(this.state.configuration), false).sort(function (a, b) {\n return b.order - a.order;\n }).forEach(function (stateNode) {\n var e_11, _a;\n\n try {\n for (var _b = __values(stateNode.definition.exit), _c = _b.next(); !_c.done; _c = _b.next()) {\n var action = _c.value;\n\n _this.exec(action, _this.state);\n }\n } catch (e_11_1) {\n e_11 = {\n error: e_11_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n } finally {\n if (e_11) throw e_11.error;\n }\n }\n }); // Stop all children\n\n\n this.children.forEach(function (child) {\n if (isFunction(child.stop)) {\n child.stop();\n }\n });\n this.children.clear();\n\n try {\n // Cancel all delayed events\n for (var _p = __values(Object.keys(this.delayedEventsMap)), _q = _p.next(); !_q.done; _q = _p.next()) {\n var key = _q.value;\n this.clock.clearTimeout(this.delayedEventsMap[key]);\n }\n } catch (e_10_1) {\n e_10 = {\n error: e_10_1\n };\n } finally {\n try {\n if (_q && !_q.done && (_e = _p.return)) _e.call(_p);\n } finally {\n if (e_10) throw e_10.error;\n }\n }\n\n this.scheduler.clear();\n this.scheduler = new Scheduler({\n deferEvents: this.options.deferEvents\n });\n this.initialized = false;\n this.status = InterpreterStatus.Stopped;\n this._initialState = undefined;\n registry.free(this.sessionId);\n return this;\n };\n\n Interpreter.prototype.batch = function (events) {\n var _this = this;\n\n if (this.status === InterpreterStatus.NotStarted && this.options.deferEvents) {\n // tslint:disable-next-line:no-console\n if (!IS_PRODUCTION) {\n warn(false, \"\".concat(events.length, \" event(s) were sent to uninitialized service \\\"\").concat(this.machine.id, \"\\\" and are deferred. Make sure .start() is called for this service.\\nEvent: \").concat(JSON.stringify(event)));\n }\n } else if (this.status !== InterpreterStatus.Running) {\n throw new Error( // tslint:disable-next-line:max-line-length\n \"\".concat(events.length, \" event(s) were sent to uninitialized service \\\"\").concat(this.machine.id, \"\\\". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.\"));\n }\n\n this.scheduler.schedule(function () {\n var e_12, _a;\n\n var nextState = _this.state;\n var batchChanged = false;\n var batchedActions = [];\n\n var _loop_1 = function (event_1) {\n var _event = toSCXMLEvent(event_1);\n\n _this.forward(_event);\n\n nextState = provide(_this, function () {\n return _this.machine.transition(nextState, _event);\n });\n batchedActions.push.apply(batchedActions, __spreadArray([], __read(nextState.actions.map(function (a) {\n return bindActionToState(a, nextState);\n })), false));\n batchChanged = batchChanged || !!nextState.changed;\n };\n\n try {\n for (var events_1 = __values(events), events_1_1 = events_1.next(); !events_1_1.done; events_1_1 = events_1.next()) {\n var event_1 = events_1_1.value;\n\n _loop_1(event_1);\n }\n } catch (e_12_1) {\n e_12 = {\n error: e_12_1\n };\n } finally {\n try {\n if (events_1_1 && !events_1_1.done && (_a = events_1.return)) _a.call(events_1);\n } finally {\n if (e_12) throw e_12.error;\n }\n }\n\n nextState.changed = batchChanged;\n nextState.actions = batchedActions;\n\n _this.update(nextState, toSCXMLEvent(events[events.length - 1]));\n });\n };\n /**\r\n * Returns a send function bound to this interpreter instance.\r\n *\r\n * @param event The event to be sent by the sender.\r\n */\n\n\n Interpreter.prototype.sender = function (event) {\n return this.send.bind(this, event);\n };\n /**\r\n * Returns the next state given the interpreter's current state and the event.\r\n *\r\n * This is a pure method that does _not_ update the interpreter's state.\r\n *\r\n * @param event The event to determine the next state\r\n */\n\n\n Interpreter.prototype.nextState = function (event) {\n var _this = this;\n\n var _event = toSCXMLEvent(event);\n\n if (_event.name.indexOf(errorPlatform) === 0 && !this.state.nextEvents.some(function (nextEvent) {\n return nextEvent.indexOf(errorPlatform) === 0;\n })) {\n throw _event.data.data;\n }\n\n var nextState = provide(this, function () {\n return _this.machine.transition(_this.state, _event);\n });\n return nextState;\n };\n\n Interpreter.prototype.forward = function (event) {\n var e_13, _a;\n\n try {\n for (var _b = __values(this.forwardTo), _c = _b.next(); !_c.done; _c = _b.next()) {\n var id = _c.value;\n var child = this.children.get(id);\n\n if (!child) {\n throw new Error(\"Unable to forward event '\".concat(event, \"' from interpreter '\").concat(this.id, \"' to nonexistant child '\").concat(id, \"'.\"));\n }\n\n child.send(event);\n }\n } catch (e_13_1) {\n e_13 = {\n error: e_13_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n } finally {\n if (e_13) throw e_13.error;\n }\n }\n };\n\n Interpreter.prototype.defer = function (sendAction) {\n var _this = this;\n\n this.delayedEventsMap[sendAction.id] = this.clock.setTimeout(function () {\n if (sendAction.to) {\n _this.sendTo(sendAction._event, sendAction.to);\n } else {\n _this.send(sendAction._event);\n }\n }, sendAction.delay);\n };\n\n Interpreter.prototype.cancel = function (sendId) {\n this.clock.clearTimeout(this.delayedEventsMap[sendId]);\n delete this.delayedEventsMap[sendId];\n };\n\n Interpreter.prototype.exec = function (action, state, actionFunctionMap) {\n if (actionFunctionMap === void 0) {\n actionFunctionMap = this.machine.options.actions;\n }\n\n var context = state.context,\n _event = state._event;\n var actionOrExec = action.exec || getActionFunction(action.type, actionFunctionMap);\n var exec = isFunction(actionOrExec) ? actionOrExec : actionOrExec ? actionOrExec.exec : action.exec;\n\n if (exec) {\n try {\n return exec(context, _event.data, {\n action: action,\n state: this.state,\n _event: _event\n });\n } catch (err) {\n if (this.parent) {\n this.parent.send({\n type: 'xstate.error',\n data: err\n });\n }\n\n throw err;\n }\n }\n\n switch (action.type) {\n case send:\n var sendAction = action;\n\n if (typeof sendAction.delay === 'number') {\n this.defer(sendAction);\n return;\n } else {\n if (sendAction.to) {\n this.sendTo(sendAction._event, sendAction.to);\n } else {\n this.send(sendAction._event);\n }\n }\n\n break;\n\n case cancel:\n this.cancel(action.sendId);\n break;\n\n case start:\n {\n if (this.status !== InterpreterStatus.Running) {\n return;\n }\n\n var activity = action.activity; // If the activity will be stopped right after it's started\n // (such as in transient states)\n // don't bother starting the activity.\n\n if (!this.state.activities[activity.id || activity.type]) {\n break;\n } // Invoked services\n\n\n if (activity.type === ActionTypes.Invoke) {\n var invokeSource = toInvokeSource(activity.src);\n var serviceCreator = this.machine.options.services ? this.machine.options.services[invokeSource.type] : undefined;\n var id = activity.id,\n data = activity.data;\n\n if (!IS_PRODUCTION) {\n warn(!('forward' in activity), // tslint:disable-next-line:max-line-length\n \"`forward` property is deprecated (found in invocation of '\".concat(activity.src, \"' in in machine '\").concat(this.machine.id, \"'). \") + \"Please use `autoForward` instead.\");\n }\n\n var autoForward = 'autoForward' in activity ? activity.autoForward : !!activity.forward;\n\n if (!serviceCreator) {\n // tslint:disable-next-line:no-console\n if (!IS_PRODUCTION) {\n warn(false, \"No service found for invocation '\".concat(activity.src, \"' in machine '\").concat(this.machine.id, \"'.\"));\n }\n\n return;\n }\n\n var resolvedData = data ? mapContext(data, context, _event) : undefined;\n\n if (typeof serviceCreator === 'string') {\n // TODO: warn\n return;\n }\n\n var source = isFunction(serviceCreator) ? serviceCreator(context, _event.data, {\n data: resolvedData,\n src: invokeSource,\n meta: activity.meta\n }) : serviceCreator;\n\n if (!source) {\n // TODO: warn?\n return;\n }\n\n var options = void 0;\n\n if (isMachine(source)) {\n source = resolvedData ? source.withContext(resolvedData) : source;\n options = {\n autoForward: autoForward\n };\n }\n\n this.spawn(source, id, options);\n } else {\n this.spawnActivity(activity);\n }\n\n break;\n }\n\n case stop:\n {\n this.stopChild(action.activity.id);\n break;\n }\n\n case log:\n var label = action.label,\n value = action.value;\n\n if (label) {\n this.logger(label, value);\n } else {\n this.logger(value);\n }\n\n break;\n\n default:\n if (!IS_PRODUCTION) {\n warn(false, \"No implementation found for action type '\".concat(action.type, \"'\"));\n }\n\n break;\n }\n\n return undefined;\n };\n\n Interpreter.prototype.removeChild = function (childId) {\n var _a;\n\n this.children.delete(childId);\n this.forwardTo.delete(childId); // this.state might not exist at the time this is called,\n // such as when a child is added then removed while initializing the state\n\n (_a = this.state) === null || _a === void 0 ? true : delete _a.children[childId];\n };\n\n Interpreter.prototype.stopChild = function (childId) {\n var child = this.children.get(childId);\n\n if (!child) {\n return;\n }\n\n this.removeChild(childId);\n\n if (isFunction(child.stop)) {\n child.stop();\n }\n };\n\n Interpreter.prototype.spawn = function (entity, name, options) {\n if (isPromiseLike(entity)) {\n return this.spawnPromise(Promise.resolve(entity), name);\n } else if (isFunction(entity)) {\n return this.spawnCallback(entity, name);\n } else if (isSpawnedActor(entity)) {\n return this.spawnActor(entity, name);\n } else if (isObservable(entity)) {\n return this.spawnObservable(entity, name);\n } else if (isMachine(entity)) {\n return this.spawnMachine(entity, __assign(__assign({}, options), {\n id: name\n }));\n } else if (isBehavior(entity)) {\n return this.spawnBehavior(entity, name);\n } else {\n throw new Error(\"Unable to spawn entity \\\"\".concat(name, \"\\\" of type \\\"\").concat(typeof entity, \"\\\".\"));\n }\n };\n\n Interpreter.prototype.spawnMachine = function (machine, options) {\n var _this = this;\n\n if (options === void 0) {\n options = {};\n }\n\n var childService = new Interpreter(machine, __assign(__assign({}, this.options), {\n parent: this,\n id: options.id || machine.id\n }));\n\n var resolvedOptions = __assign(__assign({}, DEFAULT_SPAWN_OPTIONS), options);\n\n if (resolvedOptions.sync) {\n childService.onTransition(function (state) {\n _this.send(update, {\n state: state,\n id: childService.id\n });\n });\n }\n\n var actor = childService;\n this.children.set(childService.id, actor);\n\n if (resolvedOptions.autoForward) {\n this.forwardTo.add(childService.id);\n }\n\n childService.onDone(function (doneEvent) {\n _this.removeChild(childService.id);\n\n _this.send(toSCXMLEvent(doneEvent, {\n origin: childService.id\n }));\n }).start();\n return actor;\n };\n\n Interpreter.prototype.spawnBehavior = function (behavior, id) {\n var actorRef = spawnBehavior(behavior, {\n id: id,\n parent: this\n });\n this.children.set(id, actorRef);\n return actorRef;\n };\n\n Interpreter.prototype.spawnPromise = function (promise, id) {\n var _a;\n\n var _this = this;\n\n var canceled = false;\n var resolvedData;\n promise.then(function (response) {\n if (!canceled) {\n resolvedData = response;\n\n _this.removeChild(id);\n\n _this.send(toSCXMLEvent(doneInvoke(id, response), {\n origin: id\n }));\n }\n }, function (errorData) {\n if (!canceled) {\n _this.removeChild(id);\n\n var errorEvent = error(id, errorData);\n\n try {\n // Send \"error.platform.id\" to this (parent).\n _this.send(toSCXMLEvent(errorEvent, {\n origin: id\n }));\n } catch (error) {\n reportUnhandledExceptionOnInvocation(errorData, error, id);\n\n if (_this.devTools) {\n _this.devTools.send(errorEvent, _this.state);\n }\n\n if (_this.machine.strict) {\n // it would be better to always stop the state machine if unhandled\n // exception/promise rejection happens but because we don't want to\n // break existing code so enforce it on strict mode only especially so\n // because documentation says that onError is optional\n _this.stop();\n }\n }\n }\n });\n var actor = (_a = {\n id: id,\n send: function () {\n return void 0;\n },\n subscribe: function (next, handleError, complete) {\n var observer = toObserver(next, handleError, complete);\n var unsubscribed = false;\n promise.then(function (response) {\n if (unsubscribed) {\n return;\n }\n\n observer.next(response);\n\n if (unsubscribed) {\n return;\n }\n\n observer.complete();\n }, function (err) {\n if (unsubscribed) {\n return;\n }\n\n observer.error(err);\n });\n return {\n unsubscribe: function () {\n return unsubscribed = true;\n }\n };\n },\n stop: function () {\n canceled = true;\n },\n toJSON: function () {\n return {\n id: id\n };\n },\n getSnapshot: function () {\n return resolvedData;\n }\n }, _a[symbolObservable] = function () {\n return this;\n }, _a);\n this.children.set(id, actor);\n return actor;\n };\n\n Interpreter.prototype.spawnCallback = function (callback, id) {\n var _a;\n\n var _this = this;\n\n var canceled = false;\n var receivers = new Set();\n var listeners = new Set();\n var emitted;\n\n var receive = function (e) {\n emitted = e;\n listeners.forEach(function (listener) {\n return listener(e);\n });\n\n if (canceled) {\n return;\n }\n\n _this.send(toSCXMLEvent(e, {\n origin: id\n }));\n };\n\n var callbackStop;\n\n try {\n callbackStop = callback(receive, function (newListener) {\n receivers.add(newListener);\n });\n } catch (err) {\n this.send(error(id, err));\n }\n\n if (isPromiseLike(callbackStop)) {\n // it turned out to be an async function, can't reliably check this before calling `callback`\n // because transpiled async functions are not recognizable\n return this.spawnPromise(callbackStop, id);\n }\n\n var actor = (_a = {\n id: id,\n send: function (event) {\n return receivers.forEach(function (receiver) {\n return receiver(event);\n });\n },\n subscribe: function (next) {\n var observer = toObserver(next);\n listeners.add(observer.next);\n return {\n unsubscribe: function () {\n listeners.delete(observer.next);\n }\n };\n },\n stop: function () {\n canceled = true;\n\n if (isFunction(callbackStop)) {\n callbackStop();\n }\n },\n toJSON: function () {\n return {\n id: id\n };\n },\n getSnapshot: function () {\n return emitted;\n }\n }, _a[symbolObservable] = function () {\n return this;\n }, _a);\n this.children.set(id, actor);\n return actor;\n };\n\n Interpreter.prototype.spawnObservable = function (source, id) {\n var _a;\n\n var _this = this;\n\n var emitted;\n var subscription = source.subscribe(function (value) {\n emitted = value;\n\n _this.send(toSCXMLEvent(value, {\n origin: id\n }));\n }, function (err) {\n _this.removeChild(id);\n\n _this.send(toSCXMLEvent(error(id, err), {\n origin: id\n }));\n }, function () {\n _this.removeChild(id);\n\n _this.send(toSCXMLEvent(doneInvoke(id), {\n origin: id\n }));\n });\n var actor = (_a = {\n id: id,\n send: function () {\n return void 0;\n },\n subscribe: function (next, handleError, complete) {\n return source.subscribe(next, handleError, complete);\n },\n stop: function () {\n return subscription.unsubscribe();\n },\n getSnapshot: function () {\n return emitted;\n },\n toJSON: function () {\n return {\n id: id\n };\n }\n }, _a[symbolObservable] = function () {\n return this;\n }, _a);\n this.children.set(id, actor);\n return actor;\n };\n\n Interpreter.prototype.spawnActor = function (actor, name) {\n this.children.set(name, actor);\n return actor;\n };\n\n Interpreter.prototype.spawnActivity = function (activity) {\n var implementation = this.machine.options && this.machine.options.activities ? this.machine.options.activities[activity.type] : undefined;\n\n if (!implementation) {\n if (!IS_PRODUCTION) {\n warn(false, \"No implementation found for activity '\".concat(activity.type, \"'\"));\n } // tslint:disable-next-line:no-console\n\n\n return;\n } // Start implementation\n\n\n var dispose = implementation(this.state.context, activity);\n this.spawnEffect(activity.id, dispose);\n };\n\n Interpreter.prototype.spawnEffect = function (id, dispose) {\n var _a;\n\n this.children.set(id, (_a = {\n id: id,\n send: function () {\n return void 0;\n },\n subscribe: function () {\n return {\n unsubscribe: function () {\n return void 0;\n }\n };\n },\n stop: dispose || undefined,\n getSnapshot: function () {\n return undefined;\n },\n toJSON: function () {\n return {\n id: id\n };\n }\n }, _a[symbolObservable] = function () {\n return this;\n }, _a));\n };\n\n Interpreter.prototype.attachDev = function () {\n var global = getGlobal();\n\n if (this.options.devTools && global) {\n if (global.__REDUX_DEVTOOLS_EXTENSION__) {\n var devToolsOptions = typeof this.options.devTools === 'object' ? this.options.devTools : undefined;\n this.devTools = global.__REDUX_DEVTOOLS_EXTENSION__.connect(__assign(__assign({\n name: this.id,\n autoPause: true,\n stateSanitizer: function (state) {\n return {\n value: state.value,\n context: state.context,\n actions: state.actions\n };\n }\n }, devToolsOptions), {\n features: __assign({\n jump: false,\n skip: false\n }, devToolsOptions ? devToolsOptions.features : undefined)\n }), this.machine);\n this.devTools.init(this.state);\n } // add XState-specific dev tooling hook\n\n\n registerService(this);\n }\n };\n\n Interpreter.prototype.toJSON = function () {\n return {\n id: this.id\n };\n };\n\n Interpreter.prototype[symbolObservable] = function () {\n return this;\n };\n\n Interpreter.prototype.getSnapshot = function () {\n if (this.status === InterpreterStatus.NotStarted) {\n return this.initialState;\n }\n\n return this._state;\n };\n /**\r\n * The default interpreter options:\r\n *\r\n * - `clock` uses the global `setTimeout` and `clearTimeout` functions\r\n * - `logger` uses the global `console.log()` method\r\n */\n\n\n Interpreter.defaultOptions = {\n execute: true,\n deferEvents: true,\n clock: {\n setTimeout: function (fn, ms) {\n return setTimeout(fn, ms);\n },\n clearTimeout: function (id) {\n return clearTimeout(id);\n }\n },\n logger: /*#__PURE__*/console.log.bind(console),\n devTools: false\n };\n Interpreter.interpret = interpret;\n return Interpreter;\n}();\n\nvar resolveSpawnOptions = function (nameOrOptions) {\n if (isString(nameOrOptions)) {\n return __assign(__assign({}, DEFAULT_SPAWN_OPTIONS), {\n name: nameOrOptions\n });\n }\n\n return __assign(__assign(__assign({}, DEFAULT_SPAWN_OPTIONS), {\n name: uniqueId()\n }), nameOrOptions);\n};\n\nfunction spawn(entity, nameOrOptions) {\n var resolvedOptions = resolveSpawnOptions(nameOrOptions);\n return consume(function (service) {\n if (!IS_PRODUCTION) {\n var isLazyEntity = isMachine(entity) || isFunction(entity);\n warn(!!service || isLazyEntity, \"Attempted to spawn an Actor (ID: \\\"\".concat(isMachine(entity) ? entity.id : 'undefined', \"\\\") outside of a service. This will have no effect.\"));\n }\n\n if (service) {\n return service.spawn(entity, resolvedOptions.name, resolvedOptions);\n } else {\n return createDeferredActor(entity, resolvedOptions.name);\n }\n });\n}\n/**\r\n * Creates a new Interpreter instance for the given machine with the provided options, if any.\r\n *\r\n * @param machine The machine to interpret\r\n * @param options Interpreter options\r\n */\n\nfunction interpret(machine, options) {\n var interpreter = new Interpreter(machine, options);\n return interpreter;\n}\n\nexport { Interpreter, InterpreterStatus, interpret, spawn };\n", "import { __assign, __rest } from './_virtual/_tslib.js';\nimport './types.js';\nimport { invoke } from './actionTypes.js';\nimport './utils.js';\nimport './environment.js';\n\nfunction toInvokeSource(src) {\n if (typeof src === 'string') {\n var simpleSrc = {\n type: src\n };\n\n simpleSrc.toString = function () {\n return src;\n }; // v4 compat - TODO: remove in v5\n\n\n return simpleSrc;\n }\n\n return src;\n}\nfunction toInvokeDefinition(invokeConfig) {\n return __assign(__assign({\n type: invoke\n }, invokeConfig), {\n toJSON: function () {\n invokeConfig.onDone;\n invokeConfig.onError;\n var invokeDef = __rest(invokeConfig, [\"onDone\", \"onError\"]);\n\n return __assign(__assign({}, invokeDef), {\n type: invoke,\n src: toInvokeSource(invokeConfig.src)\n });\n }\n });\n}\n\nexport { toInvokeDefinition, toInvokeSource };\n", "import { __assign, __spreadArray, __read, __values, __rest } from './_virtual/_tslib.js';\nimport { isFunction, mapValues, isArray, flatten, toArray, toStateValue, isString, getEventType, toSCXMLEvent, matchesState, path, evaluateGuard, mapContext, pathToStateValue, isBuiltInEvent, partition, updateHistoryValue, toStatePath, mapFilterValues, warn, toStatePaths, nestedPath, normalizeTarget, toGuard, toTransitionConfigArray, isMachine, createInvokeId } from './utils.js';\nimport { SpecialTargets } from './types.js';\nimport { State, stateValuesEqual } from './State.js';\nimport { start as start$1, stop as stop$1, raise as raise$1, send, invoke, update, nullEvent } from './actionTypes.js';\nimport { done, start, raise, stop, toActionObjects, resolveActions, doneInvoke, error, toActionObject, toActivityDefinition, after, send as send$1, cancel, initEvent } from './actions.js';\nimport { IS_PRODUCTION } from './environment.js';\nimport { STATE_DELIMITER } from './constants.js';\nimport { getAllStateNodes, getConfiguration, isInFinalState, getTagsFromConfiguration, has, getChildren, getValue, isLeafNode } from './stateUtils.js';\nimport { createInvocableActor } from './Actor.js';\nimport { toInvokeDefinition } from './invokeUtils.js';\n\nvar NULL_EVENT = '';\nvar STATE_IDENTIFIER = '#';\nvar WILDCARD = '*';\nvar EMPTY_OBJECT = {};\n\nvar isStateId = function (str) {\n return str[0] === STATE_IDENTIFIER;\n};\n\nvar createDefaultOptions = function () {\n return {\n actions: {},\n guards: {},\n services: {},\n activities: {},\n delays: {}\n };\n};\n\nvar validateArrayifiedTransitions = function (stateNode, event, transitions) {\n var hasNonLastUnguardedTarget = transitions.slice(0, -1).some(function (transition) {\n return !('cond' in transition) && !('in' in transition) && (isString(transition.target) || isMachine(transition.target));\n });\n var eventText = event === NULL_EVENT ? 'the transient event' : \"event '\".concat(event, \"'\");\n warn(!hasNonLastUnguardedTarget, \"One or more transitions for \".concat(eventText, \" on state '\").concat(stateNode.id, \"' are unreachable. \") + \"Make sure that the default transition is the last one defined.\");\n};\n\nvar StateNode =\n/*#__PURE__*/\n\n/** @class */\nfunction () {\n function StateNode(\n /**\r\n * The raw config used to create the machine.\r\n */\n config, options,\n /**\r\n * The initial extended state\r\n */\n _context, // TODO: this is unsafe, but we're removing it in v5 anyway\n _stateInfo) {\n var _this = this;\n\n if (_context === void 0) {\n _context = 'context' in config ? config.context : undefined;\n }\n\n var _a;\n\n this.config = config;\n this._context = _context;\n /**\r\n * The order this state node appears. Corresponds to the implicit SCXML document order.\r\n */\n\n this.order = -1;\n this.__xstatenode = true;\n this.__cache = {\n events: undefined,\n relativeValue: new Map(),\n initialStateValue: undefined,\n initialState: undefined,\n on: undefined,\n transitions: undefined,\n candidates: {},\n delayedTransitions: undefined\n };\n this.idMap = {};\n this.tags = [];\n this.options = Object.assign(createDefaultOptions(), options);\n this.parent = _stateInfo === null || _stateInfo === void 0 ? void 0 : _stateInfo.parent;\n this.key = this.config.key || (_stateInfo === null || _stateInfo === void 0 ? void 0 : _stateInfo.key) || this.config.id || '(machine)';\n this.machine = this.parent ? this.parent.machine : this;\n this.path = this.parent ? this.parent.path.concat(this.key) : [];\n this.delimiter = this.config.delimiter || (this.parent ? this.parent.delimiter : STATE_DELIMITER);\n this.id = this.config.id || __spreadArray([this.machine.key], __read(this.path), false).join(this.delimiter);\n this.version = this.parent ? this.parent.version : this.config.version;\n this.type = this.config.type || (this.config.parallel ? 'parallel' : this.config.states && Object.keys(this.config.states).length ? 'compound' : this.config.history ? 'history' : 'atomic');\n this.schema = this.parent ? this.machine.schema : (_a = this.config.schema) !== null && _a !== void 0 ? _a : {};\n this.description = this.config.description;\n\n if (!IS_PRODUCTION) {\n warn(!('parallel' in this.config), \"The \\\"parallel\\\" property is deprecated and will be removed in version 4.1. \".concat(this.config.parallel ? \"Replace with `type: 'parallel'`\" : \"Use `type: '\".concat(this.type, \"'`\"), \" in the config for state node '\").concat(this.id, \"' instead.\"));\n }\n\n this.initial = this.config.initial;\n this.states = this.config.states ? mapValues(this.config.states, function (stateConfig, key) {\n var _a;\n\n var stateNode = new StateNode(stateConfig, {}, undefined, {\n parent: _this,\n key: key\n });\n Object.assign(_this.idMap, __assign((_a = {}, _a[stateNode.id] = stateNode, _a), stateNode.idMap));\n return stateNode;\n }) : EMPTY_OBJECT; // Document order\n\n var order = 0;\n\n function dfs(stateNode) {\n var e_1, _a;\n\n stateNode.order = order++;\n\n try {\n for (var _b = __values(getChildren(stateNode)), _c = _b.next(); !_c.done; _c = _b.next()) {\n var child = _c.value;\n dfs(child);\n }\n } catch (e_1_1) {\n e_1 = {\n error: e_1_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n } finally {\n if (e_1) throw e_1.error;\n }\n }\n }\n\n dfs(this); // History config\n\n this.history = this.config.history === true ? 'shallow' : this.config.history || false;\n this._transient = !!this.config.always || (!this.config.on ? false : Array.isArray(this.config.on) ? this.config.on.some(function (_a) {\n var event = _a.event;\n return event === NULL_EVENT;\n }) : NULL_EVENT in this.config.on);\n this.strict = !!this.config.strict; // TODO: deprecate (entry)\n\n this.onEntry = toArray(this.config.entry || this.config.onEntry).map(function (action) {\n return toActionObject(action);\n }); // TODO: deprecate (exit)\n\n this.onExit = toArray(this.config.exit || this.config.onExit).map(function (action) {\n return toActionObject(action);\n });\n this.meta = this.config.meta;\n this.doneData = this.type === 'final' ? this.config.data : undefined;\n this.invoke = toArray(this.config.invoke).map(function (invokeConfig, i) {\n var _a, _b;\n\n if (isMachine(invokeConfig)) {\n var invokeId = createInvokeId(_this.id, i);\n _this.machine.options.services = __assign((_a = {}, _a[invokeId] = invokeConfig, _a), _this.machine.options.services);\n return toInvokeDefinition({\n src: invokeId,\n id: invokeId\n });\n } else if (isString(invokeConfig.src)) {\n var invokeId = invokeConfig.id || createInvokeId(_this.id, i);\n return toInvokeDefinition(__assign(__assign({}, invokeConfig), {\n id: invokeId,\n src: invokeConfig.src\n }));\n } else if (isMachine(invokeConfig.src) || isFunction(invokeConfig.src)) {\n var invokeId = invokeConfig.id || createInvokeId(_this.id, i);\n _this.machine.options.services = __assign((_b = {}, _b[invokeId] = invokeConfig.src, _b), _this.machine.options.services);\n return toInvokeDefinition(__assign(__assign({\n id: invokeId\n }, invokeConfig), {\n src: invokeId\n }));\n } else {\n var invokeSource = invokeConfig.src;\n return toInvokeDefinition(__assign(__assign({\n id: createInvokeId(_this.id, i)\n }, invokeConfig), {\n src: invokeSource\n }));\n }\n });\n this.activities = toArray(this.config.activities).concat(this.invoke).map(function (activity) {\n return toActivityDefinition(activity);\n });\n this.transition = this.transition.bind(this);\n this.tags = toArray(this.config.tags); // TODO: this is the real fix for initialization once\n // state node getters are deprecated\n // if (!this.parent) {\n // this._init();\n // }\n }\n\n StateNode.prototype._init = function () {\n if (this.__cache.transitions) {\n return;\n }\n\n getAllStateNodes(this).forEach(function (stateNode) {\n return stateNode.on;\n });\n };\n /**\r\n * Clones this state machine with custom options and context.\r\n *\r\n * @param options Options (actions, guards, activities, services) to recursively merge with the existing options.\r\n * @param context Custom context (will override predefined context)\r\n */\n\n\n StateNode.prototype.withConfig = function (options, context) {\n var _a = this.options,\n actions = _a.actions,\n activities = _a.activities,\n guards = _a.guards,\n services = _a.services,\n delays = _a.delays;\n return new StateNode(this.config, {\n actions: __assign(__assign({}, actions), options.actions),\n activities: __assign(__assign({}, activities), options.activities),\n guards: __assign(__assign({}, guards), options.guards),\n services: __assign(__assign({}, services), options.services),\n delays: __assign(__assign({}, delays), options.delays)\n }, context !== null && context !== void 0 ? context : this.context);\n };\n /**\r\n * Clones this state machine with custom context.\r\n *\r\n * @param context Custom context (will override predefined context, not recursive)\r\n */\n\n\n StateNode.prototype.withContext = function (context) {\n return new StateNode(this.config, this.options, context);\n };\n\n Object.defineProperty(StateNode.prototype, \"context\", {\n get: function () {\n return isFunction(this._context) ? this._context() : this._context;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(StateNode.prototype, \"definition\", {\n /**\r\n * The well-structured state node definition.\r\n */\n get: function () {\n return {\n id: this.id,\n key: this.key,\n version: this.version,\n context: this.context,\n type: this.type,\n initial: this.initial,\n history: this.history,\n states: mapValues(this.states, function (state) {\n return state.definition;\n }),\n on: this.on,\n transitions: this.transitions,\n entry: this.onEntry,\n exit: this.onExit,\n activities: this.activities || [],\n meta: this.meta,\n order: this.order || -1,\n data: this.doneData,\n invoke: this.invoke,\n description: this.description,\n tags: this.tags\n };\n },\n enumerable: false,\n configurable: true\n });\n\n StateNode.prototype.toJSON = function () {\n return this.definition;\n };\n\n Object.defineProperty(StateNode.prototype, \"on\", {\n /**\r\n * The mapping of events to transitions.\r\n */\n get: function () {\n if (this.__cache.on) {\n return this.__cache.on;\n }\n\n var transitions = this.transitions;\n return this.__cache.on = transitions.reduce(function (map, transition) {\n map[transition.eventType] = map[transition.eventType] || [];\n map[transition.eventType].push(transition);\n return map;\n }, {});\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(StateNode.prototype, \"after\", {\n get: function () {\n return this.__cache.delayedTransitions || (this.__cache.delayedTransitions = this.getDelayedTransitions(), this.__cache.delayedTransitions);\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(StateNode.prototype, \"transitions\", {\n /**\r\n * All the transitions that can be taken from this state node.\r\n */\n get: function () {\n return this.__cache.transitions || (this.__cache.transitions = this.formatTransitions(), this.__cache.transitions);\n },\n enumerable: false,\n configurable: true\n });\n\n StateNode.prototype.getCandidates = function (eventName) {\n if (this.__cache.candidates[eventName]) {\n return this.__cache.candidates[eventName];\n }\n\n var transient = eventName === NULL_EVENT;\n var candidates = this.transitions.filter(function (transition) {\n var sameEventType = transition.eventType === eventName; // null events should only match against eventless transitions\n\n return transient ? sameEventType : sameEventType || transition.eventType === WILDCARD;\n });\n this.__cache.candidates[eventName] = candidates;\n return candidates;\n };\n /**\r\n * All delayed transitions from the config.\r\n */\n\n\n StateNode.prototype.getDelayedTransitions = function () {\n var _this = this;\n\n var afterConfig = this.config.after;\n\n if (!afterConfig) {\n return [];\n }\n\n var mutateEntryExit = function (delay, i) {\n var delayRef = isFunction(delay) ? \"\".concat(_this.id, \":delay[\").concat(i, \"]\") : delay;\n var eventType = after(delayRef, _this.id);\n\n _this.onEntry.push(send$1(eventType, {\n delay: delay\n }));\n\n _this.onExit.push(cancel(eventType));\n\n return eventType;\n };\n\n var delayedTransitions = isArray(afterConfig) ? afterConfig.map(function (transition, i) {\n var eventType = mutateEntryExit(transition.delay, i);\n return __assign(__assign({}, transition), {\n event: eventType\n });\n }) : flatten(Object.keys(afterConfig).map(function (delay, i) {\n var configTransition = afterConfig[delay];\n var resolvedTransition = isString(configTransition) ? {\n target: configTransition\n } : configTransition;\n var resolvedDelay = !isNaN(+delay) ? +delay : delay;\n var eventType = mutateEntryExit(resolvedDelay, i);\n return toArray(resolvedTransition).map(function (transition) {\n return __assign(__assign({}, transition), {\n event: eventType,\n delay: resolvedDelay\n });\n });\n }));\n return delayedTransitions.map(function (delayedTransition) {\n var delay = delayedTransition.delay;\n return __assign(__assign({}, _this.formatTransition(delayedTransition)), {\n delay: delay\n });\n });\n };\n /**\r\n * Returns the state nodes represented by the current state value.\r\n *\r\n * @param state The state value or State instance\r\n */\n\n\n StateNode.prototype.getStateNodes = function (state) {\n var _a;\n\n var _this = this;\n\n if (!state) {\n return [];\n }\n\n var stateValue = state instanceof State ? state.value : toStateValue(state, this.delimiter);\n\n if (isString(stateValue)) {\n var initialStateValue = this.getStateNode(stateValue).initial;\n return initialStateValue !== undefined ? this.getStateNodes((_a = {}, _a[stateValue] = initialStateValue, _a)) : [this, this.states[stateValue]];\n }\n\n var subStateKeys = Object.keys(stateValue);\n var subStateNodes = [this];\n subStateNodes.push.apply(subStateNodes, __spreadArray([], __read(flatten(subStateKeys.map(function (subStateKey) {\n return _this.getStateNode(subStateKey).getStateNodes(stateValue[subStateKey]);\n }))), false));\n return subStateNodes;\n };\n /**\r\n * Returns `true` if this state node explicitly handles the given event.\r\n *\r\n * @param event The event in question\r\n */\n\n\n StateNode.prototype.handles = function (event) {\n var eventType = getEventType(event);\n return this.events.includes(eventType);\n };\n /**\r\n * Resolves the given `state` to a new `State` instance relative to this machine.\r\n *\r\n * This ensures that `.events` and `.nextEvents` represent the correct values.\r\n *\r\n * @param state The state to resolve\r\n */\n\n\n StateNode.prototype.resolveState = function (state) {\n var stateFromConfig = state instanceof State ? state : State.create(state);\n var configuration = Array.from(getConfiguration([], this.getStateNodes(stateFromConfig.value)));\n return new State(__assign(__assign({}, stateFromConfig), {\n value: this.resolve(stateFromConfig.value),\n configuration: configuration,\n done: isInFinalState(configuration, this),\n tags: getTagsFromConfiguration(configuration),\n machine: this.machine\n }));\n };\n\n StateNode.prototype.transitionLeafNode = function (stateValue, state, _event) {\n var stateNode = this.getStateNode(stateValue);\n var next = stateNode.next(state, _event);\n\n if (!next || !next.transitions.length) {\n return this.next(state, _event);\n }\n\n return next;\n };\n\n StateNode.prototype.transitionCompoundNode = function (stateValue, state, _event) {\n var subStateKeys = Object.keys(stateValue);\n var stateNode = this.getStateNode(subStateKeys[0]);\n\n var next = stateNode._transition(stateValue[subStateKeys[0]], state, _event);\n\n if (!next || !next.transitions.length) {\n return this.next(state, _event);\n }\n\n return next;\n };\n\n StateNode.prototype.transitionParallelNode = function (stateValue, state, _event) {\n var e_2, _a;\n\n var transitionMap = {};\n\n try {\n for (var _b = __values(Object.keys(stateValue)), _c = _b.next(); !_c.done; _c = _b.next()) {\n var subStateKey = _c.value;\n var subStateValue = stateValue[subStateKey];\n\n if (!subStateValue) {\n continue;\n }\n\n var subStateNode = this.getStateNode(subStateKey);\n\n var next = subStateNode._transition(subStateValue, state, _event);\n\n if (next) {\n transitionMap[subStateKey] = next;\n }\n }\n } catch (e_2_1) {\n e_2 = {\n error: e_2_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n } finally {\n if (e_2) throw e_2.error;\n }\n }\n\n var stateTransitions = Object.keys(transitionMap).map(function (key) {\n return transitionMap[key];\n });\n var enabledTransitions = flatten(stateTransitions.map(function (st) {\n return st.transitions;\n }));\n var willTransition = stateTransitions.some(function (st) {\n return st.transitions.length > 0;\n });\n\n if (!willTransition) {\n return this.next(state, _event);\n }\n\n var entryNodes = flatten(stateTransitions.map(function (t) {\n return t.entrySet;\n }));\n var configuration = flatten(Object.keys(transitionMap).map(function (key) {\n return transitionMap[key].configuration;\n }));\n return {\n transitions: enabledTransitions,\n entrySet: entryNodes,\n exitSet: flatten(stateTransitions.map(function (t) {\n return t.exitSet;\n })),\n configuration: configuration,\n source: state,\n actions: flatten(Object.keys(transitionMap).map(function (key) {\n return transitionMap[key].actions;\n }))\n };\n };\n\n StateNode.prototype._transition = function (stateValue, state, _event) {\n // leaf node\n if (isString(stateValue)) {\n return this.transitionLeafNode(stateValue, state, _event);\n } // hierarchical node\n\n\n if (Object.keys(stateValue).length === 1) {\n return this.transitionCompoundNode(stateValue, state, _event);\n } // orthogonal node\n\n\n return this.transitionParallelNode(stateValue, state, _event);\n };\n\n StateNode.prototype.getTransitionData = function (state, event) {\n return this._transition(state.value, state, toSCXMLEvent(event));\n };\n\n StateNode.prototype.next = function (state, _event) {\n var e_3, _a;\n\n var _this = this;\n\n var eventName = _event.name;\n var actions = [];\n var nextStateNodes = [];\n var selectedTransition;\n\n try {\n for (var _b = __values(this.getCandidates(eventName)), _c = _b.next(); !_c.done; _c = _b.next()) {\n var candidate = _c.value;\n var cond = candidate.cond,\n stateIn = candidate.in;\n var resolvedContext = state.context;\n var isInState = stateIn ? isString(stateIn) && isStateId(stateIn) ? // Check if in state by ID\n state.matches(toStateValue(this.getStateNodeById(stateIn).path, this.delimiter)) : // Check if in state by relative grandparent\n matchesState(toStateValue(stateIn, this.delimiter), path(this.path.slice(0, -2))(state.value)) : true;\n var guardPassed = false;\n\n try {\n guardPassed = !cond || evaluateGuard(this.machine, cond, resolvedContext, _event, state);\n } catch (err) {\n throw new Error(\"Unable to evaluate guard '\".concat(cond.name || cond.type, \"' in transition for event '\").concat(eventName, \"' in state node '\").concat(this.id, \"':\\n\").concat(err.message));\n }\n\n if (guardPassed && isInState) {\n if (candidate.target !== undefined) {\n nextStateNodes = candidate.target;\n }\n\n actions.push.apply(actions, __spreadArray([], __read(candidate.actions), false));\n selectedTransition = candidate;\n break;\n }\n }\n } catch (e_3_1) {\n e_3 = {\n error: e_3_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n } finally {\n if (e_3) throw e_3.error;\n }\n }\n\n if (!selectedTransition) {\n return undefined;\n }\n\n if (!nextStateNodes.length) {\n return {\n transitions: [selectedTransition],\n entrySet: [],\n exitSet: [],\n configuration: state.value ? [this] : [],\n source: state,\n actions: actions\n };\n }\n\n var allNextStateNodes = flatten(nextStateNodes.map(function (stateNode) {\n return _this.getRelativeStateNodes(stateNode, state.historyValue);\n }));\n var isInternal = !!selectedTransition.internal;\n var reentryNodes = isInternal ? [] : flatten(allNextStateNodes.map(function (n) {\n return _this.nodesFromChild(n);\n }));\n return {\n transitions: [selectedTransition],\n entrySet: reentryNodes,\n exitSet: isInternal ? [] : [this],\n configuration: allNextStateNodes,\n source: state,\n actions: actions\n };\n };\n\n StateNode.prototype.nodesFromChild = function (childStateNode) {\n if (childStateNode.escapes(this)) {\n return [];\n }\n\n var nodes = [];\n var marker = childStateNode;\n\n while (marker && marker !== this) {\n nodes.push(marker);\n marker = marker.parent;\n }\n\n nodes.push(this); // inclusive\n\n return nodes;\n };\n /**\r\n * Whether the given state node \"escapes\" this state node. If the `stateNode` is equal to or the parent of\r\n * this state node, it does not escape.\r\n */\n\n\n StateNode.prototype.escapes = function (stateNode) {\n if (this === stateNode) {\n return false;\n }\n\n var parent = this.parent;\n\n while (parent) {\n if (parent === stateNode) {\n return false;\n }\n\n parent = parent.parent;\n }\n\n return true;\n };\n\n StateNode.prototype.getActions = function (transition, currentContext, _event, prevState) {\n var e_4, _a, e_5, _b;\n\n var prevConfig = getConfiguration([], prevState ? this.getStateNodes(prevState.value) : [this]);\n var resolvedConfig = transition.configuration.length ? getConfiguration(prevConfig, transition.configuration) : prevConfig;\n\n try {\n for (var resolvedConfig_1 = __values(resolvedConfig), resolvedConfig_1_1 = resolvedConfig_1.next(); !resolvedConfig_1_1.done; resolvedConfig_1_1 = resolvedConfig_1.next()) {\n var sn = resolvedConfig_1_1.value;\n\n if (!has(prevConfig, sn)) {\n transition.entrySet.push(sn);\n }\n }\n } catch (e_4_1) {\n e_4 = {\n error: e_4_1\n };\n } finally {\n try {\n if (resolvedConfig_1_1 && !resolvedConfig_1_1.done && (_a = resolvedConfig_1.return)) _a.call(resolvedConfig_1);\n } finally {\n if (e_4) throw e_4.error;\n }\n }\n\n try {\n for (var prevConfig_1 = __values(prevConfig), prevConfig_1_1 = prevConfig_1.next(); !prevConfig_1_1.done; prevConfig_1_1 = prevConfig_1.next()) {\n var sn = prevConfig_1_1.value;\n\n if (!has(resolvedConfig, sn) || has(transition.exitSet, sn.parent)) {\n transition.exitSet.push(sn);\n }\n }\n } catch (e_5_1) {\n e_5 = {\n error: e_5_1\n };\n } finally {\n try {\n if (prevConfig_1_1 && !prevConfig_1_1.done && (_b = prevConfig_1.return)) _b.call(prevConfig_1);\n } finally {\n if (e_5) throw e_5.error;\n }\n }\n\n var doneEvents = flatten(transition.entrySet.map(function (sn) {\n var events = [];\n\n if (sn.type !== 'final') {\n return events;\n }\n\n var parent = sn.parent;\n\n if (!parent.parent) {\n return events;\n }\n\n events.push(done(sn.id, sn.doneData), // TODO: deprecate - final states should not emit done events for their own state.\n done(parent.id, sn.doneData ? mapContext(sn.doneData, currentContext, _event) : undefined));\n var grandparent = parent.parent;\n\n if (grandparent.type === 'parallel') {\n if (getChildren(grandparent).every(function (parentNode) {\n return isInFinalState(transition.configuration, parentNode);\n })) {\n events.push(done(grandparent.id));\n }\n }\n\n return events;\n }));\n transition.exitSet.sort(function (a, b) {\n return b.order - a.order;\n });\n transition.entrySet.sort(function (a, b) {\n return a.order - b.order;\n });\n var entryStates = new Set(transition.entrySet);\n var exitStates = new Set(transition.exitSet);\n\n var _c = __read([flatten(Array.from(entryStates).map(function (stateNode) {\n return __spreadArray(__spreadArray([], __read(stateNode.activities.map(function (activity) {\n return start(activity);\n })), false), __read(stateNode.onEntry), false);\n })).concat(doneEvents.map(raise)), flatten(Array.from(exitStates).map(function (stateNode) {\n return __spreadArray(__spreadArray([], __read(stateNode.onExit), false), __read(stateNode.activities.map(function (activity) {\n return stop(activity);\n })), false);\n }))], 2),\n entryActions = _c[0],\n exitActions = _c[1];\n\n var actions = toActionObjects(exitActions.concat(transition.actions).concat(entryActions), this.machine.options.actions);\n return actions;\n };\n /**\r\n * Determines the next state given the current `state` and sent `event`.\r\n *\r\n * @param state The current State instance or state value\r\n * @param event The event that was sent at the current state\r\n * @param context The current context (extended state) of the current state\r\n */\n\n\n StateNode.prototype.transition = function (state, event, context) {\n if (state === void 0) {\n state = this.initialState;\n }\n\n var _event = toSCXMLEvent(event);\n\n var currentState;\n\n if (state instanceof State) {\n currentState = context === undefined ? state : this.resolveState(State.from(state, context));\n } else {\n var resolvedStateValue = isString(state) ? this.resolve(pathToStateValue(this.getResolvedPath(state))) : this.resolve(state);\n var resolvedContext = context !== null && context !== void 0 ? context : this.machine.context;\n currentState = this.resolveState(State.from(resolvedStateValue, resolvedContext));\n }\n\n if (!IS_PRODUCTION && _event.name === WILDCARD) {\n throw new Error(\"An event cannot have the wildcard type ('\".concat(WILDCARD, \"')\"));\n }\n\n if (this.strict) {\n if (!this.events.includes(_event.name) && !isBuiltInEvent(_event.name)) {\n throw new Error(\"Machine '\".concat(this.id, \"' does not accept event '\").concat(_event.name, \"'\"));\n }\n }\n\n var stateTransition = this._transition(currentState.value, currentState, _event) || {\n transitions: [],\n configuration: [],\n entrySet: [],\n exitSet: [],\n source: currentState,\n actions: []\n };\n var prevConfig = getConfiguration([], this.getStateNodes(currentState.value));\n var resolvedConfig = stateTransition.configuration.length ? getConfiguration(prevConfig, stateTransition.configuration) : prevConfig;\n stateTransition.configuration = __spreadArray([], __read(resolvedConfig), false);\n return this.resolveTransition(stateTransition, currentState, currentState.context, _event);\n };\n\n StateNode.prototype.resolveRaisedTransition = function (state, _event, originalEvent) {\n var _a;\n\n var currentActions = state.actions;\n state = this.transition(state, _event); // Save original event to state\n // TODO: this should be the raised event! Delete in V5 (breaking)\n\n state._event = originalEvent;\n state.event = originalEvent.data;\n\n (_a = state.actions).unshift.apply(_a, __spreadArray([], __read(currentActions), false));\n\n return state;\n };\n\n StateNode.prototype.resolveTransition = function (stateTransition, currentState, context, _event) {\n var e_6, _a;\n\n var _this = this;\n\n if (_event === void 0) {\n _event = initEvent;\n }\n\n var configuration = stateTransition.configuration; // Transition will \"apply\" if:\n // - this is the initial state (there is no current state)\n // - OR there are transitions\n\n var willTransition = !currentState || stateTransition.transitions.length > 0;\n var resolvedStateValue = willTransition ? getValue(this.machine, configuration) : undefined;\n var historyValue = currentState ? currentState.historyValue ? currentState.historyValue : stateTransition.source ? this.machine.historyValue(currentState.value) : undefined : undefined;\n var actions = this.getActions(stateTransition, context, _event, currentState);\n var activities = currentState ? __assign({}, currentState.activities) : {};\n\n try {\n for (var actions_1 = __values(actions), actions_1_1 = actions_1.next(); !actions_1_1.done; actions_1_1 = actions_1.next()) {\n var action = actions_1_1.value;\n\n if (action.type === start$1) {\n activities[action.activity.id || action.activity.type] = action;\n } else if (action.type === stop$1) {\n activities[action.activity.id || action.activity.type] = false;\n }\n }\n } catch (e_6_1) {\n e_6 = {\n error: e_6_1\n };\n } finally {\n try {\n if (actions_1_1 && !actions_1_1.done && (_a = actions_1.return)) _a.call(actions_1);\n } finally {\n if (e_6) throw e_6.error;\n }\n }\n\n var _b = __read(resolveActions(this, currentState, context, _event, actions, this.machine.config.preserveActionOrder), 2),\n resolvedActions = _b[0],\n updatedContext = _b[1];\n\n var _c = __read(partition(resolvedActions, function (action) {\n return action.type === raise$1 || action.type === send && action.to === SpecialTargets.Internal;\n }), 2),\n raisedEvents = _c[0],\n nonRaisedActions = _c[1];\n\n var invokeActions = resolvedActions.filter(function (action) {\n var _a;\n\n return action.type === start$1 && ((_a = action.activity) === null || _a === void 0 ? void 0 : _a.type) === invoke;\n });\n var children = invokeActions.reduce(function (acc, action) {\n acc[action.activity.id] = createInvocableActor(action.activity, _this.machine, updatedContext, _event);\n return acc;\n }, currentState ? __assign({}, currentState.children) : {});\n var resolvedConfiguration = willTransition ? stateTransition.configuration : currentState ? currentState.configuration : [];\n var isDone = isInFinalState(resolvedConfiguration, this);\n var nextState = new State({\n value: resolvedStateValue || currentState.value,\n context: updatedContext,\n _event: _event,\n // Persist _sessionid between states\n _sessionid: currentState ? currentState._sessionid : null,\n historyValue: resolvedStateValue ? historyValue ? updateHistoryValue(historyValue, resolvedStateValue) : undefined : currentState ? currentState.historyValue : undefined,\n history: !resolvedStateValue || stateTransition.source ? currentState : undefined,\n actions: resolvedStateValue ? nonRaisedActions : [],\n activities: resolvedStateValue ? activities : currentState ? currentState.activities : {},\n events: [],\n configuration: resolvedConfiguration,\n transitions: stateTransition.transitions,\n children: children,\n done: isDone,\n tags: getTagsFromConfiguration(resolvedConfiguration),\n machine: this\n });\n var didUpdateContext = context !== updatedContext;\n nextState.changed = _event.name === update || didUpdateContext; // Dispose of penultimate histories to prevent memory leaks\n\n var history = nextState.history;\n\n if (history) {\n delete history.history;\n } // There are transient transitions if the machine is not in a final state\n // and if some of the state nodes have transient (\"always\") transitions.\n\n\n var isTransient = !isDone && (this._transient || configuration.some(function (stateNode) {\n return stateNode._transient;\n })); // If there are no enabled transitions, check if there are transient transitions.\n // If there are transient transitions, continue checking for more transitions\n // because an transient transition should be triggered even if there are no\n // enabled transitions.\n //\n // If we're already working on an transient transition (by checking\n // if the event is a NULL_EVENT), then stop to prevent an infinite loop.\n //\n // Otherwise, if there are no enabled nor transient transitions, we are done.\n\n if (!willTransition && (!isTransient || _event.name === NULL_EVENT)) {\n return nextState;\n }\n\n var maybeNextState = nextState;\n\n if (!isDone) {\n if (isTransient) {\n maybeNextState = this.resolveRaisedTransition(maybeNextState, {\n type: nullEvent\n }, _event);\n }\n\n while (raisedEvents.length) {\n var raisedEvent = raisedEvents.shift();\n maybeNextState = this.resolveRaisedTransition(maybeNextState, raisedEvent._event, _event);\n }\n } // Detect if state changed\n\n\n var changed = maybeNextState.changed || (history ? !!maybeNextState.actions.length || didUpdateContext || typeof history.value !== typeof maybeNextState.value || !stateValuesEqual(maybeNextState.value, history.value) : undefined);\n maybeNextState.changed = changed; // Preserve original history after raised events\n\n maybeNextState.history = history;\n return maybeNextState;\n };\n /**\r\n * Returns the child state node from its relative `stateKey`, or throws.\r\n */\n\n\n StateNode.prototype.getStateNode = function (stateKey) {\n if (isStateId(stateKey)) {\n return this.machine.getStateNodeById(stateKey);\n }\n\n if (!this.states) {\n throw new Error(\"Unable to retrieve child state '\".concat(stateKey, \"' from '\").concat(this.id, \"'; no child states exist.\"));\n }\n\n var result = this.states[stateKey];\n\n if (!result) {\n throw new Error(\"Child state '\".concat(stateKey, \"' does not exist on '\").concat(this.id, \"'\"));\n }\n\n return result;\n };\n /**\r\n * Returns the state node with the given `stateId`, or throws.\r\n *\r\n * @param stateId The state ID. The prefix \"#\" is removed.\r\n */\n\n\n StateNode.prototype.getStateNodeById = function (stateId) {\n var resolvedStateId = isStateId(stateId) ? stateId.slice(STATE_IDENTIFIER.length) : stateId;\n\n if (resolvedStateId === this.id) {\n return this;\n }\n\n var stateNode = this.machine.idMap[resolvedStateId];\n\n if (!stateNode) {\n throw new Error(\"Child state node '#\".concat(resolvedStateId, \"' does not exist on machine '\").concat(this.id, \"'\"));\n }\n\n return stateNode;\n };\n /**\r\n * Returns the relative state node from the given `statePath`, or throws.\r\n *\r\n * @param statePath The string or string array relative path to the state node.\r\n */\n\n\n StateNode.prototype.getStateNodeByPath = function (statePath) {\n if (typeof statePath === 'string' && isStateId(statePath)) {\n try {\n return this.getStateNodeById(statePath.slice(1));\n } catch (e) {// try individual paths\n // throw e;\n }\n }\n\n var arrayStatePath = toStatePath(statePath, this.delimiter).slice();\n var currentStateNode = this;\n\n while (arrayStatePath.length) {\n var key = arrayStatePath.shift();\n\n if (!key.length) {\n break;\n }\n\n currentStateNode = currentStateNode.getStateNode(key);\n }\n\n return currentStateNode;\n };\n /**\r\n * Resolves a partial state value with its full representation in this machine.\r\n *\r\n * @param stateValue The partial state value to resolve.\r\n */\n\n\n StateNode.prototype.resolve = function (stateValue) {\n var _a;\n\n var _this = this;\n\n if (!stateValue) {\n return this.initialStateValue || EMPTY_OBJECT; // TODO: type-specific properties\n }\n\n switch (this.type) {\n case 'parallel':\n return mapValues(this.initialStateValue, function (subStateValue, subStateKey) {\n return subStateValue ? _this.getStateNode(subStateKey).resolve(stateValue[subStateKey] || subStateValue) : EMPTY_OBJECT;\n });\n\n case 'compound':\n if (isString(stateValue)) {\n var subStateNode = this.getStateNode(stateValue);\n\n if (subStateNode.type === 'parallel' || subStateNode.type === 'compound') {\n return _a = {}, _a[stateValue] = subStateNode.initialStateValue, _a;\n }\n\n return stateValue;\n }\n\n if (!Object.keys(stateValue).length) {\n return this.initialStateValue || {};\n }\n\n return mapValues(stateValue, function (subStateValue, subStateKey) {\n return subStateValue ? _this.getStateNode(subStateKey).resolve(subStateValue) : EMPTY_OBJECT;\n });\n\n default:\n return stateValue || EMPTY_OBJECT;\n }\n };\n\n StateNode.prototype.getResolvedPath = function (stateIdentifier) {\n if (isStateId(stateIdentifier)) {\n var stateNode = this.machine.idMap[stateIdentifier.slice(STATE_IDENTIFIER.length)];\n\n if (!stateNode) {\n throw new Error(\"Unable to find state node '\".concat(stateIdentifier, \"'\"));\n }\n\n return stateNode.path;\n }\n\n return toStatePath(stateIdentifier, this.delimiter);\n };\n\n Object.defineProperty(StateNode.prototype, \"initialStateValue\", {\n get: function () {\n var _a;\n\n if (this.__cache.initialStateValue) {\n return this.__cache.initialStateValue;\n }\n\n var initialStateValue;\n\n if (this.type === 'parallel') {\n initialStateValue = mapFilterValues(this.states, function (state) {\n return state.initialStateValue || EMPTY_OBJECT;\n }, function (stateNode) {\n return !(stateNode.type === 'history');\n });\n } else if (this.initial !== undefined) {\n if (!this.states[this.initial]) {\n throw new Error(\"Initial state '\".concat(this.initial, \"' not found on '\").concat(this.key, \"'\"));\n }\n\n initialStateValue = isLeafNode(this.states[this.initial]) ? this.initial : (_a = {}, _a[this.initial] = this.states[this.initial].initialStateValue, _a);\n } else {\n // The finite state value of a machine without child states is just an empty object\n initialStateValue = {};\n }\n\n this.__cache.initialStateValue = initialStateValue;\n return this.__cache.initialStateValue;\n },\n enumerable: false,\n configurable: true\n });\n\n StateNode.prototype.getInitialState = function (stateValue, context) {\n this._init(); // TODO: this should be in the constructor (see note in constructor)\n\n\n var configuration = this.getStateNodes(stateValue);\n return this.resolveTransition({\n configuration: configuration,\n entrySet: configuration,\n exitSet: [],\n transitions: [],\n source: undefined,\n actions: []\n }, undefined, context !== null && context !== void 0 ? context : this.machine.context, undefined);\n };\n\n Object.defineProperty(StateNode.prototype, \"initialState\", {\n /**\r\n * The initial State instance, which includes all actions to be executed from\r\n * entering the initial state.\r\n */\n get: function () {\n var initialStateValue = this.initialStateValue;\n\n if (!initialStateValue) {\n throw new Error(\"Cannot retrieve initial state from simple state '\".concat(this.id, \"'.\"));\n }\n\n return this.getInitialState(initialStateValue);\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(StateNode.prototype, \"target\", {\n /**\r\n * The target state value of the history state node, if it exists. This represents the\r\n * default state value to transition to if no history value exists yet.\r\n */\n get: function () {\n var target;\n\n if (this.type === 'history') {\n var historyConfig = this.config;\n\n if (isString(historyConfig.target)) {\n target = isStateId(historyConfig.target) ? pathToStateValue(this.machine.getStateNodeById(historyConfig.target).path.slice(this.path.length - 1)) : historyConfig.target;\n } else {\n target = historyConfig.target;\n }\n }\n\n return target;\n },\n enumerable: false,\n configurable: true\n });\n /**\r\n * Returns the leaf nodes from a state path relative to this state node.\r\n *\r\n * @param relativeStateId The relative state path to retrieve the state nodes\r\n * @param history The previous state to retrieve history\r\n * @param resolve Whether state nodes should resolve to initial child state nodes\r\n */\n\n StateNode.prototype.getRelativeStateNodes = function (relativeStateId, historyValue, resolve) {\n if (resolve === void 0) {\n resolve = true;\n }\n\n return resolve ? relativeStateId.type === 'history' ? relativeStateId.resolveHistory(historyValue) : relativeStateId.initialStateNodes : [relativeStateId];\n };\n\n Object.defineProperty(StateNode.prototype, \"initialStateNodes\", {\n get: function () {\n var _this = this;\n\n if (isLeafNode(this)) {\n return [this];\n } // Case when state node is compound but no initial state is defined\n\n\n if (this.type === 'compound' && !this.initial) {\n if (!IS_PRODUCTION) {\n warn(false, \"Compound state node '\".concat(this.id, \"' has no initial state.\"));\n }\n\n return [this];\n }\n\n var initialStateNodePaths = toStatePaths(this.initialStateValue);\n return flatten(initialStateNodePaths.map(function (initialPath) {\n return _this.getFromRelativePath(initialPath);\n }));\n },\n enumerable: false,\n configurable: true\n });\n /**\r\n * Retrieves state nodes from a relative path to this state node.\r\n *\r\n * @param relativePath The relative path from this state node\r\n * @param historyValue\r\n */\n\n StateNode.prototype.getFromRelativePath = function (relativePath) {\n if (!relativePath.length) {\n return [this];\n }\n\n var _a = __read(relativePath),\n stateKey = _a[0],\n childStatePath = _a.slice(1);\n\n if (!this.states) {\n throw new Error(\"Cannot retrieve subPath '\".concat(stateKey, \"' from node with no states\"));\n }\n\n var childStateNode = this.getStateNode(stateKey);\n\n if (childStateNode.type === 'history') {\n return childStateNode.resolveHistory();\n }\n\n if (!this.states[stateKey]) {\n throw new Error(\"Child state '\".concat(stateKey, \"' does not exist on '\").concat(this.id, \"'\"));\n }\n\n return this.states[stateKey].getFromRelativePath(childStatePath);\n };\n\n StateNode.prototype.historyValue = function (relativeStateValue) {\n if (!Object.keys(this.states).length) {\n return undefined;\n }\n\n return {\n current: relativeStateValue || this.initialStateValue,\n states: mapFilterValues(this.states, function (stateNode, key) {\n if (!relativeStateValue) {\n return stateNode.historyValue();\n }\n\n var subStateValue = isString(relativeStateValue) ? undefined : relativeStateValue[key];\n return stateNode.historyValue(subStateValue || stateNode.initialStateValue);\n }, function (stateNode) {\n return !stateNode.history;\n })\n };\n };\n /**\r\n * Resolves to the historical value(s) of the parent state node,\r\n * represented by state nodes.\r\n *\r\n * @param historyValue\r\n */\n\n\n StateNode.prototype.resolveHistory = function (historyValue) {\n var _this = this;\n\n if (this.type !== 'history') {\n return [this];\n }\n\n var parent = this.parent;\n\n if (!historyValue) {\n var historyTarget = this.target;\n return historyTarget ? flatten(toStatePaths(historyTarget).map(function (relativeChildPath) {\n return parent.getFromRelativePath(relativeChildPath);\n })) : parent.initialStateNodes;\n }\n\n var subHistoryValue = nestedPath(parent.path, 'states')(historyValue).current;\n\n if (isString(subHistoryValue)) {\n return [parent.getStateNode(subHistoryValue)];\n }\n\n return flatten(toStatePaths(subHistoryValue).map(function (subStatePath) {\n return _this.history === 'deep' ? parent.getFromRelativePath(subStatePath) : [parent.states[subStatePath[0]]];\n }));\n };\n\n Object.defineProperty(StateNode.prototype, \"stateIds\", {\n /**\r\n * All the state node IDs of this state node and its descendant state nodes.\r\n */\n get: function () {\n var _this = this;\n\n var childStateIds = flatten(Object.keys(this.states).map(function (stateKey) {\n return _this.states[stateKey].stateIds;\n }));\n return [this.id].concat(childStateIds);\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(StateNode.prototype, \"events\", {\n /**\r\n * All the event types accepted by this state node and its descendants.\r\n */\n get: function () {\n var e_7, _a, e_8, _b;\n\n if (this.__cache.events) {\n return this.__cache.events;\n }\n\n var states = this.states;\n var events = new Set(this.ownEvents);\n\n if (states) {\n try {\n for (var _c = __values(Object.keys(states)), _d = _c.next(); !_d.done; _d = _c.next()) {\n var stateId = _d.value;\n var state = states[stateId];\n\n if (state.states) {\n try {\n for (var _e = (e_8 = void 0, __values(state.events)), _f = _e.next(); !_f.done; _f = _e.next()) {\n var event_1 = _f.value;\n events.add(\"\".concat(event_1));\n }\n } catch (e_8_1) {\n e_8 = {\n error: e_8_1\n };\n } finally {\n try {\n if (_f && !_f.done && (_b = _e.return)) _b.call(_e);\n } finally {\n if (e_8) throw e_8.error;\n }\n }\n }\n }\n } catch (e_7_1) {\n e_7 = {\n error: e_7_1\n };\n } finally {\n try {\n if (_d && !_d.done && (_a = _c.return)) _a.call(_c);\n } finally {\n if (e_7) throw e_7.error;\n }\n }\n }\n\n return this.__cache.events = Array.from(events);\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(StateNode.prototype, \"ownEvents\", {\n /**\r\n * All the events that have transitions directly from this state node.\r\n *\r\n * Excludes any inert events.\r\n */\n get: function () {\n var events = new Set(this.transitions.filter(function (transition) {\n return !(!transition.target && !transition.actions.length && transition.internal);\n }).map(function (transition) {\n return transition.eventType;\n }));\n return Array.from(events);\n },\n enumerable: false,\n configurable: true\n });\n\n StateNode.prototype.resolveTarget = function (_target) {\n var _this = this;\n\n if (_target === undefined) {\n // an undefined target signals that the state node should not transition from that state when receiving that event\n return undefined;\n }\n\n return _target.map(function (target) {\n if (!isString(target)) {\n return target;\n }\n\n var isInternalTarget = target[0] === _this.delimiter; // If internal target is defined on machine,\n // do not include machine key on target\n\n if (isInternalTarget && !_this.parent) {\n return _this.getStateNodeByPath(target.slice(1));\n }\n\n var resolvedTarget = isInternalTarget ? _this.key + target : target;\n\n if (_this.parent) {\n try {\n var targetStateNode = _this.parent.getStateNodeByPath(resolvedTarget);\n\n return targetStateNode;\n } catch (err) {\n throw new Error(\"Invalid transition definition for state node '\".concat(_this.id, \"':\\n\").concat(err.message));\n }\n } else {\n return _this.getStateNodeByPath(resolvedTarget);\n }\n });\n };\n\n StateNode.prototype.formatTransition = function (transitionConfig) {\n var _this = this;\n\n var normalizedTarget = normalizeTarget(transitionConfig.target);\n var internal = 'internal' in transitionConfig ? transitionConfig.internal : normalizedTarget ? normalizedTarget.some(function (_target) {\n return isString(_target) && _target[0] === _this.delimiter;\n }) : true;\n var guards = this.machine.options.guards;\n var target = this.resolveTarget(normalizedTarget);\n\n var transition = __assign(__assign({}, transitionConfig), {\n actions: toActionObjects(toArray(transitionConfig.actions)),\n cond: toGuard(transitionConfig.cond, guards),\n target: target,\n source: this,\n internal: internal,\n eventType: transitionConfig.event,\n toJSON: function () {\n return __assign(__assign({}, transition), {\n target: transition.target ? transition.target.map(function (t) {\n return \"#\".concat(t.id);\n }) : undefined,\n source: \"#\".concat(_this.id)\n });\n }\n });\n\n return transition;\n };\n\n StateNode.prototype.formatTransitions = function () {\n var e_9, _a;\n\n var _this = this;\n\n var onConfig;\n\n if (!this.config.on) {\n onConfig = [];\n } else if (Array.isArray(this.config.on)) {\n onConfig = this.config.on;\n } else {\n var _b = this.config.on,\n _c = WILDCARD,\n _d = _b[_c],\n wildcardConfigs = _d === void 0 ? [] : _d,\n strictTransitionConfigs_1 = __rest(_b, [typeof _c === \"symbol\" ? _c : _c + \"\"]);\n\n onConfig = flatten(Object.keys(strictTransitionConfigs_1).map(function (key) {\n if (!IS_PRODUCTION && key === NULL_EVENT) {\n warn(false, \"Empty string transition configs (e.g., `{ on: { '': ... }}`) for transient transitions are deprecated. Specify the transition in the `{ always: ... }` property instead. \" + \"Please check the `on` configuration for \\\"#\".concat(_this.id, \"\\\".\"));\n }\n\n var transitionConfigArray = toTransitionConfigArray(key, strictTransitionConfigs_1[key]);\n\n if (!IS_PRODUCTION) {\n validateArrayifiedTransitions(_this, key, transitionConfigArray);\n }\n\n return transitionConfigArray;\n }).concat(toTransitionConfigArray(WILDCARD, wildcardConfigs)));\n }\n\n var eventlessConfig = this.config.always ? toTransitionConfigArray('', this.config.always) : [];\n var doneConfig = this.config.onDone ? toTransitionConfigArray(String(done(this.id)), this.config.onDone) : [];\n\n if (!IS_PRODUCTION) {\n warn(!(this.config.onDone && !this.parent), \"Root nodes cannot have an \\\".onDone\\\" transition. Please check the config of \\\"\".concat(this.id, \"\\\".\"));\n }\n\n var invokeConfig = flatten(this.invoke.map(function (invokeDef) {\n var settleTransitions = [];\n\n if (invokeDef.onDone) {\n settleTransitions.push.apply(settleTransitions, __spreadArray([], __read(toTransitionConfigArray(String(doneInvoke(invokeDef.id)), invokeDef.onDone)), false));\n }\n\n if (invokeDef.onError) {\n settleTransitions.push.apply(settleTransitions, __spreadArray([], __read(toTransitionConfigArray(String(error(invokeDef.id)), invokeDef.onError)), false));\n }\n\n return settleTransitions;\n }));\n var delayedTransitions = this.after;\n var formattedTransitions = flatten(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], __read(doneConfig), false), __read(invokeConfig), false), __read(onConfig), false), __read(eventlessConfig), false).map(function (transitionConfig) {\n return toArray(transitionConfig).map(function (transition) {\n return _this.formatTransition(transition);\n });\n }));\n\n try {\n for (var delayedTransitions_1 = __values(delayedTransitions), delayedTransitions_1_1 = delayedTransitions_1.next(); !delayedTransitions_1_1.done; delayedTransitions_1_1 = delayedTransitions_1.next()) {\n var delayedTransition = delayedTransitions_1_1.value;\n formattedTransitions.push(delayedTransition);\n }\n } catch (e_9_1) {\n e_9 = {\n error: e_9_1\n };\n } finally {\n try {\n if (delayedTransitions_1_1 && !delayedTransitions_1_1.done && (_a = delayedTransitions_1.return)) _a.call(delayedTransitions_1);\n } finally {\n if (e_9) throw e_9.error;\n }\n }\n\n return formattedTransitions;\n };\n\n return StateNode;\n}();\n\nexport { StateNode };\n", "import { StateNode } from './StateNode.js';\n\nfunction Machine(config, options, initialContext) {\n if (initialContext === void 0) {\n initialContext = config.context;\n }\n\n return new StateNode(config, options, initialContext);\n}\nfunction createMachine(config, options) {\n return new StateNode(config, options);\n}\n\nexport { Machine, createMachine };\n", "import {Util, describe} from '@qni/common'\nimport {createMachine, interpret} from 'xstate'\nimport {CircuitDropzoneElement} from '../circuit-dropzone-element'\nimport {Constructor} from './constructor'\nimport {InteractEvent} from '@interactjs/types'\nimport {PaletteDropzoneElement} from '../palette-dropzone-element'\nimport {attr} from '@github/catalyst'\nimport interact from 'interactjs'\n\nexport const isDraggable = (arg: unknown): arg is Draggable =>\n arg !== undefined && arg !== null && typeof (arg as Draggable).draggable === 'boolean'\n\nconst isCircuitDropzoneElement = (arg: unknown): arg is CircuitDropzoneElement =>\n arg !== undefined && arg !== null && (arg as Element).tagName === 'CIRCUIT-DROPZONE'\n\nconst isPaletteDropzoneElement = (arg: unknown): arg is PaletteDropzoneElement =>\n arg !== undefined && arg !== null && (arg as Element).tagName === 'PALETTE-DROPZONE'\n\nexport declare class Draggable {\n get operationX(): number\n set operationX(value: number)\n get operationY(): number\n set operationY(value: number)\n get draggable(): boolean\n set draggable(value: boolean)\n get grabbed(): boolean\n set grabbed(value: boolean)\n get dragging(): boolean\n set dragging(value: boolean)\n get snapped(): boolean\n set snapped(value: boolean)\n get bit(): number\n set bit(value: number)\n get dropzone(): PaletteDropzoneElement | CircuitDropzoneElement | null\n get snapRange(): number\n set snapTargets(value: Array<{x: number; y: number}>)\n initDraggable(): void\n}\n\ntype DraggableContext = Record\ntype DraggableEvent =\n | {type: 'SET_INTERACT'}\n | {type: 'UNSET_INTERACT'}\n | {type: 'DELETE'}\n | {type: 'GRAB'; x: number; y: number}\n | {type: 'RELEASE'}\n | {type: 'START_DRAGGING'}\n | {type: 'END_DRAGGING'}\n | {type: 'SNAP'}\n | {type: 'UNSNAP'}\n\nexport function DraggableMixin>(Base: TBase): Constructor & TBase {\n class DraggableMixinClass extends Base {\n @attr operationX = 0\n @attr operationY = 0\n @attr grabbed = false\n @attr dragging = false\n @attr snapped = false\n @attr bit = -1\n @attr debugDraggable = false\n\n private snappedDropzone!: CircuitDropzoneElement | null | undefined\n private draggableMachine = createMachine(\n {\n id: 'draggable',\n initial: 'idle',\n states: {\n idle: {\n entry: ['init'],\n on: {\n SET_INTERACT: {\n target: 'grabbable',\n actions: ['setInteract']\n }\n }\n },\n grabbable: {\n on: {\n GRAB: {\n target: 'grabbed',\n actions: ['grab']\n },\n UNSET_INTERACT: {\n target: 'idle'\n }\n }\n },\n grabbed: {\n on: {\n START_DRAGGING: {\n target: 'dragging',\n actions: ['startDragging']\n },\n RELEASE: [\n {\n target: 'grabbable',\n actions: ['release'],\n cond: 'isOnCircuitDropzone'\n },\n {\n target: 'deleted',\n actions: ['release'],\n cond: 'isOnPaletteDropzone'\n }\n ]\n }\n },\n dragging: {\n type: 'compound',\n initial: 'unknown',\n on: {\n END_DRAGGING: {\n target: 'dropped',\n actions: ['endDragging']\n }\n },\n states: {\n unknown: {\n always: [\n {target: 'snapped', cond: 'isOnCircuitDropzone'},\n {target: 'unsnapped', cond: 'isOnPaletteDropzone'}\n ]\n },\n snapped: {\n entry: ['snap'],\n on: {\n UNSNAP: {\n target: 'unsnapped'\n }\n }\n },\n unsnapped: {\n entry: ['unsnap'],\n on: {\n SNAP: {\n target: 'snapped'\n }\n }\n }\n }\n },\n dropped: {\n entry: ['drop'],\n always: [\n {target: 'grabbable', cond: 'isDroppedOnCircuitDropzone'},\n {target: 'deleted', cond: 'isTrashed'}\n ]\n },\n deleted: {\n type: 'final',\n entry: 'delete'\n }\n }\n },\n {\n actions: {\n init: () => {\n this.dispatchEvent(new Event('draggable-init', {bubbles: true}))\n },\n setInteract: () => {\n const interactable = interact(this)\n interactable.styleCursor(false)\n interactable.on('down', this.grab.bind(this))\n interactable.on('up', this.release.bind(this))\n interactable.draggable({\n onstart: this.startDragging.bind(this),\n onmove: this.dragMove.bind(this),\n onend: this.endDragging.bind(this)\n })\n\n const dropzone = this.dropzone\n if (isCircuitDropzoneElement(dropzone)) {\n this.snappedDropzone = dropzone\n } else {\n this.snappedDropzone = null\n }\n },\n grab: (_context, event) => {\n if (event.type !== 'GRAB') return\n\n this.grabbed = true\n this.dispatchEvent(new Event('operation-grab', {bubbles: true}))\n\n if (isPaletteDropzoneElement(this.dropzone)) {\n this.snapped = false\n this.moveByOffset(event.x, event.y)\n this.classList.remove('qpu-operation-xl')\n }\n },\n release: () => {\n this.grabbed = false\n this.dispatchEvent(new Event('operation-release', {bubbles: true}))\n },\n startDragging: () => {\n this.dragging = true\n },\n endDragging: () => {\n this.grabbed = false\n this.dragging = false\n this.dispatchEvent(new Event('operation-end-dragging', {bubbles: true}))\n },\n snap: () => {\n this.snapped = true\n this.snappedDropzone = this.dropzone as CircuitDropzoneElement\n this.dispatchEvent(new Event('operation-snap', {bubbles: true}))\n },\n unsnap: () => {\n this.snapped = false\n if (this.snappedDropzone) {\n this.snappedDropzone.dispatchEvent(new Event('operation-unsnap', {bubbles: true}))\n }\n },\n drop: () => {\n if (!this.snapped) return\n\n this.moveTo(0, 0)\n this.dispatchEvent(new Event('operation-drop', {bubbles: true}))\n },\n delete: () => {\n interact(this).unset()\n this.dispatchEvent(new Event('operation-delete', {bubbles: true}))\n }\n },\n guards: {\n isOnCircuitDropzone: () => {\n return isCircuitDropzoneElement(this.dropzone)\n },\n isOnPaletteDropzone: () => {\n return isPaletteDropzoneElement(this.dropzone)\n },\n isDroppedOnCircuitDropzone: () => {\n return this.snapped && isCircuitDropzoneElement(this.dropzone)\n },\n isTrashed: () => {\n return !this.snapped\n }\n }\n }\n )\n public draggableService = interpret(this.draggableMachine).onTransition(state => {\n if (this.debugDraggable) {\n // eslint-disable-next-line no-console\n console.log(`draggable: ${describe(state.value)}`)\n }\n })\n\n get draggable(): boolean {\n return this.draggableService.state !== undefined\n }\n\n set draggable(value: boolean) {\n if (value) {\n this.draggableService.send({type: 'SET_INTERACT'})\n } else {\n this.draggableService.send({type: 'UNSET_INTERACT'})\n }\n }\n\n initDraggable(): void {\n if (this.draggableService.state !== undefined) {\n return\n }\n\n this.draggableService.start()\n }\n\n get dropzone(): PaletteDropzoneElement | CircuitDropzoneElement | null {\n const el = this.parentElement\n Util.notNull(el)\n\n if (!isPaletteDropzoneElement(el) && !isCircuitDropzoneElement(el)) {\n return null\n }\n return el as PaletteDropzoneElement | CircuitDropzoneElement\n }\n\n set snapTargets(values: Array<{x: number; y: number}>) {\n interact(this).draggable({\n modifiers: [\n interact.modifiers.snap({\n targets: values,\n range: this.snapRange,\n relativePoints: [{x: 0.5, y: 0.5}]\n })\n ],\n listeners: {\n move: this.moveEventListener.bind(this)\n }\n })\n }\n\n get snapRange(): number {\n return 32\n }\n\n private moveEventListener(event: InteractEvent) {\n const snapModifier = event.modifiers![0]\n\n if (snapModifier.inRange) {\n const snapTargetInfo = snapModifier.target.source\n this.dispatchEvent(new CustomEvent('operation-in-snap-range', {detail: {snapTargetInfo}, bubbles: true}))\n\n this.moveTo(0, 0)\n\n if (this.snappedDropzone && this.snappedDropzone !== this.dropzone) {\n this.draggableService.send({type: 'UNSNAP'})\n }\n\n this.draggableService.send({type: 'SNAP'})\n } else {\n if (this.snapped) {\n this.draggableService.send({type: 'UNSNAP'})\n }\n }\n }\n\n private grab(event: MouseEvent): void {\n this.draggableService.send({type: 'GRAB', x: event.offsetX, y: event.offsetY})\n }\n\n private release(): void {\n this.draggableService.send({type: 'RELEASE'})\n }\n\n private startDragging(): void {\n this.draggableService.send({type: 'START_DRAGGING'})\n }\n\n private endDragging(): void {\n this.draggableService.send({type: 'END_DRAGGING'})\n }\n\n private dragMove(event: InteractEvent): void {\n this.move(event.dx, event.dy)\n }\n\n private move(dx: number, dy: number): void {\n const x = this.operationX + dx\n const y = this.operationY + dy\n this.moveTo(x, y)\n }\n\n private moveTo(x: number, y: number): void {\n this.operationX = x\n this.operationY = y\n this.style.transform = `translate(${x}px, ${y}px)`\n }\n\n private moveByOffset(offsetX: number, offsetY: number): void {\n const dx = offsetX - this.clientWidth / 2\n const dy = offsetY - this.clientHeight / 2\n this.move(dx, dy)\n }\n }\n\n return DraggableMixinClass as Constructor & TBase\n}\n", "import {Constructor} from './constructor'\nimport {attr} from '@github/catalyst'\n\nexport declare class Flaggable {\n get flag(): string\n set flag(value: string)\n}\n\nexport const isFlaggable = (arg: unknown): arg is Flaggable =>\n typeof arg === 'object' && arg !== null && typeof (arg as Flaggable).flag === 'string'\n\nexport function FlaggableMixin>(Base: TBase): Constructor & TBase {\n class FlaggableMixinClass extends Base {\n @attr flag = ''\n }\n\n return FlaggableMixinClass as Constructor & TBase\n}\n", "export var top = 'top';\nexport var bottom = 'bottom';\nexport var right = 'right';\nexport var left = 'left';\nexport var auto = 'auto';\nexport var basePlacements = [top, bottom, right, left];\nexport var start = 'start';\nexport var end = 'end';\nexport var clippingParents = 'clippingParents';\nexport var viewport = 'viewport';\nexport var popper = 'popper';\nexport var reference = 'reference';\nexport var variationPlacements = /*#__PURE__*/basePlacements.reduce(function (acc, placement) {\n return acc.concat([placement + \"-\" + start, placement + \"-\" + end]);\n}, []);\nexport var placements = /*#__PURE__*/[].concat(basePlacements, [auto]).reduce(function (acc, placement) {\n return acc.concat([placement, placement + \"-\" + start, placement + \"-\" + end]);\n}, []); // modifiers that need to read the DOM\n\nexport var beforeRead = 'beforeRead';\nexport var read = 'read';\nexport var afterRead = 'afterRead'; // pure-logic modifiers\n\nexport var beforeMain = 'beforeMain';\nexport var main = 'main';\nexport var afterMain = 'afterMain'; // modifier with the purpose to write to the DOM (or write into a framework state)\n\nexport var beforeWrite = 'beforeWrite';\nexport var write = 'write';\nexport var afterWrite = 'afterWrite';\nexport var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite];", "export default function getNodeName(element) {\n return element ? (element.nodeName || '').toLowerCase() : null;\n}", "export default function getWindow(node) {\n if (node == null) {\n return window;\n }\n\n if (node.toString() !== '[object Window]') {\n var ownerDocument = node.ownerDocument;\n return ownerDocument ? ownerDocument.defaultView || window : window;\n }\n\n return node;\n}", "import getWindow from \"./getWindow.js\";\n\nfunction isElement(node) {\n var OwnElement = getWindow(node).Element;\n return node instanceof OwnElement || node instanceof Element;\n}\n\nfunction isHTMLElement(node) {\n var OwnElement = getWindow(node).HTMLElement;\n return node instanceof OwnElement || node instanceof HTMLElement;\n}\n\nfunction isShadowRoot(node) {\n // IE 11 has no ShadowRoot\n if (typeof ShadowRoot === 'undefined') {\n return false;\n }\n\n var OwnElement = getWindow(node).ShadowRoot;\n return node instanceof OwnElement || node instanceof ShadowRoot;\n}\n\nexport { isElement, isHTMLElement, isShadowRoot };", "import getNodeName from \"../dom-utils/getNodeName.js\";\nimport { isHTMLElement } from \"../dom-utils/instanceOf.js\"; // This modifier takes the styles prepared by the `computeStyles` modifier\n// and applies them to the HTMLElements such as popper and arrow\n\nfunction applyStyles(_ref) {\n var state = _ref.state;\n Object.keys(state.elements).forEach(function (name) {\n var style = state.styles[name] || {};\n var attributes = state.attributes[name] || {};\n var element = state.elements[name]; // arrow is optional + virtual elements\n\n if (!isHTMLElement(element) || !getNodeName(element)) {\n return;\n } // Flow doesn't support to extend this property, but it's the most\n // effective way to apply styles to an HTMLElement\n // $FlowFixMe[cannot-write]\n\n\n Object.assign(element.style, style);\n Object.keys(attributes).forEach(function (name) {\n var value = attributes[name];\n\n if (value === false) {\n element.removeAttribute(name);\n } else {\n element.setAttribute(name, value === true ? '' : value);\n }\n });\n });\n}\n\nfunction effect(_ref2) {\n var state = _ref2.state;\n var initialStyles = {\n popper: {\n position: state.options.strategy,\n left: '0',\n top: '0',\n margin: '0'\n },\n arrow: {\n position: 'absolute'\n },\n reference: {}\n };\n Object.assign(state.elements.popper.style, initialStyles.popper);\n state.styles = initialStyles;\n\n if (state.elements.arrow) {\n Object.assign(state.elements.arrow.style, initialStyles.arrow);\n }\n\n return function () {\n Object.keys(state.elements).forEach(function (name) {\n var element = state.elements[name];\n var attributes = state.attributes[name] || {};\n var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]); // Set all values to an empty string to unset them\n\n var style = styleProperties.reduce(function (style, property) {\n style[property] = '';\n return style;\n }, {}); // arrow is optional + virtual elements\n\n if (!isHTMLElement(element) || !getNodeName(element)) {\n return;\n }\n\n Object.assign(element.style, style);\n Object.keys(attributes).forEach(function (attribute) {\n element.removeAttribute(attribute);\n });\n });\n };\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'applyStyles',\n enabled: true,\n phase: 'write',\n fn: applyStyles,\n effect: effect,\n requires: ['computeStyles']\n};", "import { auto } from \"../enums.js\";\nexport default function getBasePlacement(placement) {\n return placement.split('-')[0];\n}", "export var max = Math.max;\nexport var min = Math.min;\nexport var round = Math.round;", "import { isHTMLElement } from \"./instanceOf.js\";\nimport { round } from \"../utils/math.js\";\nexport default function getBoundingClientRect(element, includeScale) {\n if (includeScale === void 0) {\n includeScale = false;\n }\n\n var rect = element.getBoundingClientRect();\n var scaleX = 1;\n var scaleY = 1;\n\n if (isHTMLElement(element) && includeScale) {\n var offsetHeight = element.offsetHeight;\n var offsetWidth = element.offsetWidth; // Do not attempt to divide by 0, otherwise we get `Infinity` as scale\n // Fallback to 1 in case both values are `0`\n\n if (offsetWidth > 0) {\n scaleX = round(rect.width) / offsetWidth || 1;\n }\n\n if (offsetHeight > 0) {\n scaleY = round(rect.height) / offsetHeight || 1;\n }\n }\n\n return {\n width: rect.width / scaleX,\n height: rect.height / scaleY,\n top: rect.top / scaleY,\n right: rect.right / scaleX,\n bottom: rect.bottom / scaleY,\n left: rect.left / scaleX,\n x: rect.left / scaleX,\n y: rect.top / scaleY\n };\n}", "import getBoundingClientRect from \"./getBoundingClientRect.js\"; // Returns the layout rect of an element relative to its offsetParent. Layout\n// means it doesn't take into account transforms.\n\nexport default function getLayoutRect(element) {\n var clientRect = getBoundingClientRect(element); // Use the clientRect sizes if it's not been transformed.\n // Fixes https://github.com/popperjs/popper-core/issues/1223\n\n var width = element.offsetWidth;\n var height = element.offsetHeight;\n\n if (Math.abs(clientRect.width - width) <= 1) {\n width = clientRect.width;\n }\n\n if (Math.abs(clientRect.height - height) <= 1) {\n height = clientRect.height;\n }\n\n return {\n x: element.offsetLeft,\n y: element.offsetTop,\n width: width,\n height: height\n };\n}", "import { isShadowRoot } from \"./instanceOf.js\";\nexport default function contains(parent, child) {\n var rootNode = child.getRootNode && child.getRootNode(); // First, attempt with faster native method\n\n if (parent.contains(child)) {\n return true;\n } // then fallback to custom implementation with Shadow DOM support\n else if (rootNode && isShadowRoot(rootNode)) {\n var next = child;\n\n do {\n if (next && parent.isSameNode(next)) {\n return true;\n } // $FlowFixMe[prop-missing]: need a better way to handle this...\n\n\n next = next.parentNode || next.host;\n } while (next);\n } // Give up, the result is false\n\n\n return false;\n}", "import getWindow from \"./getWindow.js\";\nexport default function getComputedStyle(element) {\n return getWindow(element).getComputedStyle(element);\n}", "import getNodeName from \"./getNodeName.js\";\nexport default function isTableElement(element) {\n return ['table', 'td', 'th'].indexOf(getNodeName(element)) >= 0;\n}", "import { isElement } from \"./instanceOf.js\";\nexport default function getDocumentElement(element) {\n // $FlowFixMe[incompatible-return]: assume body is always available\n return ((isElement(element) ? element.ownerDocument : // $FlowFixMe[prop-missing]\n element.document) || window.document).documentElement;\n}", "import getNodeName from \"./getNodeName.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport { isShadowRoot } from \"./instanceOf.js\";\nexport default function getParentNode(element) {\n if (getNodeName(element) === 'html') {\n return element;\n }\n\n return (// this is a quicker (but less type safe) way to save quite some bytes from the bundle\n // $FlowFixMe[incompatible-return]\n // $FlowFixMe[prop-missing]\n element.assignedSlot || // step into the shadow DOM of the parent of a slotted node\n element.parentNode || ( // DOM Element detected\n isShadowRoot(element) ? element.host : null) || // ShadowRoot detected\n // $FlowFixMe[incompatible-call]: HTMLElement is a Node\n getDocumentElement(element) // fallback\n\n );\n}", "import getWindow from \"./getWindow.js\";\nimport getNodeName from \"./getNodeName.js\";\nimport getComputedStyle from \"./getComputedStyle.js\";\nimport { isHTMLElement } from \"./instanceOf.js\";\nimport isTableElement from \"./isTableElement.js\";\nimport getParentNode from \"./getParentNode.js\";\n\nfunction getTrueOffsetParent(element) {\n if (!isHTMLElement(element) || // https://github.com/popperjs/popper-core/issues/837\n getComputedStyle(element).position === 'fixed') {\n return null;\n }\n\n return element.offsetParent;\n} // `.offsetParent` reports `null` for fixed elements, while absolute elements\n// return the containing block\n\n\nfunction getContainingBlock(element) {\n var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') !== -1;\n var isIE = navigator.userAgent.indexOf('Trident') !== -1;\n\n if (isIE && isHTMLElement(element)) {\n // In IE 9, 10 and 11 fixed elements containing block is always established by the viewport\n var elementCss = getComputedStyle(element);\n\n if (elementCss.position === 'fixed') {\n return null;\n }\n }\n\n var currentNode = getParentNode(element);\n\n while (isHTMLElement(currentNode) && ['html', 'body'].indexOf(getNodeName(currentNode)) < 0) {\n var css = getComputedStyle(currentNode); // This is non-exhaustive but covers the most common CSS properties that\n // create a containing block.\n // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block\n\n 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') {\n return currentNode;\n } else {\n currentNode = currentNode.parentNode;\n }\n }\n\n return null;\n} // Gets the closest ancestor positioned element. Handles some edge cases,\n// such as table ancestors and cross browser bugs.\n\n\nexport default function getOffsetParent(element) {\n var window = getWindow(element);\n var offsetParent = getTrueOffsetParent(element);\n\n while (offsetParent && isTableElement(offsetParent) && getComputedStyle(offsetParent).position === 'static') {\n offsetParent = getTrueOffsetParent(offsetParent);\n }\n\n if (offsetParent && (getNodeName(offsetParent) === 'html' || getNodeName(offsetParent) === 'body' && getComputedStyle(offsetParent).position === 'static')) {\n return window;\n }\n\n return offsetParent || getContainingBlock(element) || window;\n}", "export default function getMainAxisFromPlacement(placement) {\n return ['top', 'bottom'].indexOf(placement) >= 0 ? 'x' : 'y';\n}", "import { max as mathMax, min as mathMin } from \"./math.js\";\nexport function within(min, value, max) {\n return mathMax(min, mathMin(value, max));\n}\nexport function withinMaxClamp(min, value, max) {\n var v = within(min, value, max);\n return v > max ? max : v;\n}", "export default function getFreshSideObject() {\n return {\n top: 0,\n right: 0,\n bottom: 0,\n left: 0\n };\n}", "import getFreshSideObject from \"./getFreshSideObject.js\";\nexport default function mergePaddingObject(paddingObject) {\n return Object.assign({}, getFreshSideObject(), paddingObject);\n}", "export default function expandToHashMap(value, keys) {\n return keys.reduce(function (hashMap, key) {\n hashMap[key] = value;\n return hashMap;\n }, {});\n}", "import getBasePlacement from \"../utils/getBasePlacement.js\";\nimport getLayoutRect from \"../dom-utils/getLayoutRect.js\";\nimport contains from \"../dom-utils/contains.js\";\nimport getOffsetParent from \"../dom-utils/getOffsetParent.js\";\nimport getMainAxisFromPlacement from \"../utils/getMainAxisFromPlacement.js\";\nimport { within } from \"../utils/within.js\";\nimport mergePaddingObject from \"../utils/mergePaddingObject.js\";\nimport expandToHashMap from \"../utils/expandToHashMap.js\";\nimport { left, right, basePlacements, top, bottom } from \"../enums.js\";\nimport { isHTMLElement } from \"../dom-utils/instanceOf.js\"; // eslint-disable-next-line import/no-unused-modules\n\nvar toPaddingObject = function toPaddingObject(padding, state) {\n padding = typeof padding === 'function' ? padding(Object.assign({}, state.rects, {\n placement: state.placement\n })) : padding;\n return mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));\n};\n\nfunction arrow(_ref) {\n var _state$modifiersData$;\n\n var state = _ref.state,\n name = _ref.name,\n options = _ref.options;\n var arrowElement = state.elements.arrow;\n var popperOffsets = state.modifiersData.popperOffsets;\n var basePlacement = getBasePlacement(state.placement);\n var axis = getMainAxisFromPlacement(basePlacement);\n var isVertical = [left, right].indexOf(basePlacement) >= 0;\n var len = isVertical ? 'height' : 'width';\n\n if (!arrowElement || !popperOffsets) {\n return;\n }\n\n var paddingObject = toPaddingObject(options.padding, state);\n var arrowRect = getLayoutRect(arrowElement);\n var minProp = axis === 'y' ? top : left;\n var maxProp = axis === 'y' ? bottom : right;\n var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets[axis] - state.rects.popper[len];\n var startDiff = popperOffsets[axis] - state.rects.reference[axis];\n var arrowOffsetParent = getOffsetParent(arrowElement);\n var clientSize = arrowOffsetParent ? axis === 'y' ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0;\n var centerToReference = endDiff / 2 - startDiff / 2; // Make sure the arrow doesn't overflow the popper if the center point is\n // outside of the popper bounds\n\n var min = paddingObject[minProp];\n var max = clientSize - arrowRect[len] - paddingObject[maxProp];\n var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference;\n var offset = within(min, center, max); // Prevents breaking syntax highlighting...\n\n var axisProp = axis;\n state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset, _state$modifiersData$.centerOffset = offset - center, _state$modifiersData$);\n}\n\nfunction effect(_ref2) {\n var state = _ref2.state,\n options = _ref2.options;\n var _options$element = options.element,\n arrowElement = _options$element === void 0 ? '[data-popper-arrow]' : _options$element;\n\n if (arrowElement == null) {\n return;\n } // CSS selector\n\n\n if (typeof arrowElement === 'string') {\n arrowElement = state.elements.popper.querySelector(arrowElement);\n\n if (!arrowElement) {\n return;\n }\n }\n\n if (process.env.NODE_ENV !== \"production\") {\n if (!isHTMLElement(arrowElement)) {\n console.error(['Popper: \"arrow\" element must be an HTMLElement (not an SVGElement).', 'To use an SVG arrow, wrap it in an HTMLElement that will be used as', 'the arrow.'].join(' '));\n }\n }\n\n if (!contains(state.elements.popper, arrowElement)) {\n if (process.env.NODE_ENV !== \"production\") {\n console.error(['Popper: \"arrow\" modifier\\'s `element` must be a child of the popper', 'element.'].join(' '));\n }\n\n return;\n }\n\n state.elements.arrow = arrowElement;\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'arrow',\n enabled: true,\n phase: 'main',\n fn: arrow,\n effect: effect,\n requires: ['popperOffsets'],\n requiresIfExists: ['preventOverflow']\n};", "export default function getVariation(placement) {\n return placement.split('-')[1];\n}", "import { top, left, right, bottom, end } from \"../enums.js\";\nimport getOffsetParent from \"../dom-utils/getOffsetParent.js\";\nimport getWindow from \"../dom-utils/getWindow.js\";\nimport getDocumentElement from \"../dom-utils/getDocumentElement.js\";\nimport getComputedStyle from \"../dom-utils/getComputedStyle.js\";\nimport getBasePlacement from \"../utils/getBasePlacement.js\";\nimport getVariation from \"../utils/getVariation.js\";\nimport { round } from \"../utils/math.js\"; // eslint-disable-next-line import/no-unused-modules\n\nvar unsetSides = {\n top: 'auto',\n right: 'auto',\n bottom: 'auto',\n left: 'auto'\n}; // Round the offsets to the nearest suitable subpixel based on the DPR.\n// Zooming can change the DPR, but it seems to report a value that will\n// cleanly divide the values into the appropriate subpixels.\n\nfunction roundOffsetsByDPR(_ref) {\n var x = _ref.x,\n y = _ref.y;\n var win = window;\n var dpr = win.devicePixelRatio || 1;\n return {\n x: round(x * dpr) / dpr || 0,\n y: round(y * dpr) / dpr || 0\n };\n}\n\nexport function mapToStyles(_ref2) {\n var _Object$assign2;\n\n var popper = _ref2.popper,\n popperRect = _ref2.popperRect,\n placement = _ref2.placement,\n variation = _ref2.variation,\n offsets = _ref2.offsets,\n position = _ref2.position,\n gpuAcceleration = _ref2.gpuAcceleration,\n adaptive = _ref2.adaptive,\n roundOffsets = _ref2.roundOffsets,\n isFixed = _ref2.isFixed;\n var _offsets$x = offsets.x,\n x = _offsets$x === void 0 ? 0 : _offsets$x,\n _offsets$y = offsets.y,\n y = _offsets$y === void 0 ? 0 : _offsets$y;\n\n var _ref3 = typeof roundOffsets === 'function' ? roundOffsets({\n x: x,\n y: y\n }) : {\n x: x,\n y: y\n };\n\n x = _ref3.x;\n y = _ref3.y;\n var hasX = offsets.hasOwnProperty('x');\n var hasY = offsets.hasOwnProperty('y');\n var sideX = left;\n var sideY = top;\n var win = window;\n\n if (adaptive) {\n var offsetParent = getOffsetParent(popper);\n var heightProp = 'clientHeight';\n var widthProp = 'clientWidth';\n\n if (offsetParent === getWindow(popper)) {\n offsetParent = getDocumentElement(popper);\n\n if (getComputedStyle(offsetParent).position !== 'static' && position === 'absolute') {\n heightProp = 'scrollHeight';\n widthProp = 'scrollWidth';\n }\n } // $FlowFixMe[incompatible-cast]: force type refinement, we compare offsetParent with window above, but Flow doesn't detect it\n\n\n offsetParent = offsetParent;\n\n if (placement === top || (placement === left || placement === right) && variation === end) {\n sideY = bottom;\n var offsetY = isFixed && win.visualViewport ? win.visualViewport.height : // $FlowFixMe[prop-missing]\n offsetParent[heightProp];\n y -= offsetY - popperRect.height;\n y *= gpuAcceleration ? 1 : -1;\n }\n\n if (placement === left || (placement === top || placement === bottom) && variation === end) {\n sideX = right;\n var offsetX = isFixed && win.visualViewport ? win.visualViewport.width : // $FlowFixMe[prop-missing]\n offsetParent[widthProp];\n x -= offsetX - popperRect.width;\n x *= gpuAcceleration ? 1 : -1;\n }\n }\n\n var commonStyles = Object.assign({\n position: position\n }, adaptive && unsetSides);\n\n var _ref4 = roundOffsets === true ? roundOffsetsByDPR({\n x: x,\n y: y\n }) : {\n x: x,\n y: y\n };\n\n x = _ref4.x;\n y = _ref4.y;\n\n if (gpuAcceleration) {\n var _Object$assign;\n\n 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));\n }\n\n return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + \"px\" : '', _Object$assign2[sideX] = hasX ? x + \"px\" : '', _Object$assign2.transform = '', _Object$assign2));\n}\n\nfunction computeStyles(_ref5) {\n var state = _ref5.state,\n options = _ref5.options;\n var _options$gpuAccelerat = options.gpuAcceleration,\n gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat,\n _options$adaptive = options.adaptive,\n adaptive = _options$adaptive === void 0 ? true : _options$adaptive,\n _options$roundOffsets = options.roundOffsets,\n roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets;\n\n if (process.env.NODE_ENV !== \"production\") {\n var transitionProperty = getComputedStyle(state.elements.popper).transitionProperty || '';\n\n if (adaptive && ['transform', 'top', 'right', 'bottom', 'left'].some(function (property) {\n return transitionProperty.indexOf(property) >= 0;\n })) {\n console.warn(['Popper: Detected CSS transitions on at least one of the following', 'CSS properties: \"transform\", \"top\", \"right\", \"bottom\", \"left\".', '\\n\\n', 'Disable the \"computeStyles\" modifier\\'s `adaptive` option to allow', 'for smooth transitions, or remove these properties from the CSS', 'transition declaration on the popper element if only transitioning', 'opacity or background-color for example.', '\\n\\n', 'We recommend using the popper element as a wrapper around an inner', 'element that can have any CSS property transitioned for animations.'].join(' '));\n }\n }\n\n var commonStyles = {\n placement: getBasePlacement(state.placement),\n variation: getVariation(state.placement),\n popper: state.elements.popper,\n popperRect: state.rects.popper,\n gpuAcceleration: gpuAcceleration,\n isFixed: state.options.strategy === 'fixed'\n };\n\n if (state.modifiersData.popperOffsets != null) {\n state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(Object.assign({}, commonStyles, {\n offsets: state.modifiersData.popperOffsets,\n position: state.options.strategy,\n adaptive: adaptive,\n roundOffsets: roundOffsets\n })));\n }\n\n if (state.modifiersData.arrow != null) {\n state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, {\n offsets: state.modifiersData.arrow,\n position: 'absolute',\n adaptive: false,\n roundOffsets: roundOffsets\n })));\n }\n\n state.attributes.popper = Object.assign({}, state.attributes.popper, {\n 'data-popper-placement': state.placement\n });\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'computeStyles',\n enabled: true,\n phase: 'beforeWrite',\n fn: computeStyles,\n data: {}\n};", "import getWindow from \"../dom-utils/getWindow.js\"; // eslint-disable-next-line import/no-unused-modules\n\nvar passive = {\n passive: true\n};\n\nfunction effect(_ref) {\n var state = _ref.state,\n instance = _ref.instance,\n options = _ref.options;\n var _options$scroll = options.scroll,\n scroll = _options$scroll === void 0 ? true : _options$scroll,\n _options$resize = options.resize,\n resize = _options$resize === void 0 ? true : _options$resize;\n var window = getWindow(state.elements.popper);\n var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper);\n\n if (scroll) {\n scrollParents.forEach(function (scrollParent) {\n scrollParent.addEventListener('scroll', instance.update, passive);\n });\n }\n\n if (resize) {\n window.addEventListener('resize', instance.update, passive);\n }\n\n return function () {\n if (scroll) {\n scrollParents.forEach(function (scrollParent) {\n scrollParent.removeEventListener('scroll', instance.update, passive);\n });\n }\n\n if (resize) {\n window.removeEventListener('resize', instance.update, passive);\n }\n };\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'eventListeners',\n enabled: true,\n phase: 'write',\n fn: function fn() {},\n effect: effect,\n data: {}\n};", "var hash = {\n left: 'right',\n right: 'left',\n bottom: 'top',\n top: 'bottom'\n};\nexport default function getOppositePlacement(placement) {\n return placement.replace(/left|right|bottom|top/g, function (matched) {\n return hash[matched];\n });\n}", "var hash = {\n start: 'end',\n end: 'start'\n};\nexport default function getOppositeVariationPlacement(placement) {\n return placement.replace(/start|end/g, function (matched) {\n return hash[matched];\n });\n}", "import getWindow from \"./getWindow.js\";\nexport default function getWindowScroll(node) {\n var win = getWindow(node);\n var scrollLeft = win.pageXOffset;\n var scrollTop = win.pageYOffset;\n return {\n scrollLeft: scrollLeft,\n scrollTop: scrollTop\n };\n}", "import getBoundingClientRect from \"./getBoundingClientRect.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport getWindowScroll from \"./getWindowScroll.js\";\nexport default function getWindowScrollBarX(element) {\n // If has a CSS width greater than the viewport, then this will be\n // incorrect for RTL.\n // Popper 1 is broken in this case and never had a bug report so let's assume\n // it's not an issue. I don't think anyone ever specifies width on \n // anyway.\n // Browsers where the left scrollbar doesn't cause an issue report `0` for\n // this (e.g. Edge 2019, IE11, Safari)\n return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft;\n}", "import getWindow from \"./getWindow.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport getWindowScrollBarX from \"./getWindowScrollBarX.js\";\nexport default function getViewportRect(element) {\n var win = getWindow(element);\n var html = getDocumentElement(element);\n var visualViewport = win.visualViewport;\n var width = html.clientWidth;\n var height = html.clientHeight;\n var x = 0;\n var y = 0; // NB: This isn't supported on iOS <= 12. If the keyboard is open, the popper\n // can be obscured underneath it.\n // Also, `html.clientHeight` adds the bottom bar height in Safari iOS, even\n // if it isn't open, so if this isn't available, the popper will be detected\n // to overflow the bottom of the screen too early.\n\n if (visualViewport) {\n width = visualViewport.width;\n height = visualViewport.height; // Uses Layout Viewport (like Chrome; Safari does not currently)\n // In Chrome, it returns a value very close to 0 (+/-) but contains rounding\n // errors due to floating point numbers, so we need to check precision.\n // Safari returns a number <= 0, usually < -1 when pinch-zoomed\n // Feature detection fails in mobile emulation mode in Chrome.\n // Math.abs(win.innerWidth / visualViewport.scale - visualViewport.width) <\n // 0.001\n // Fallback here: \"Not Safari\" userAgent\n\n if (!/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {\n x = visualViewport.offsetLeft;\n y = visualViewport.offsetTop;\n }\n }\n\n return {\n width: width,\n height: height,\n x: x + getWindowScrollBarX(element),\n y: y\n };\n}", "import getDocumentElement from \"./getDocumentElement.js\";\nimport getComputedStyle from \"./getComputedStyle.js\";\nimport getWindowScrollBarX from \"./getWindowScrollBarX.js\";\nimport getWindowScroll from \"./getWindowScroll.js\";\nimport { max } from \"../utils/math.js\"; // Gets the entire size of the scrollable document area, even extending outside\n// of the `` and `` rect bounds if horizontally scrollable\n\nexport default function getDocumentRect(element) {\n var _element$ownerDocumen;\n\n var html = getDocumentElement(element);\n var winScroll = getWindowScroll(element);\n var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body;\n var width = max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0);\n var height = max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0);\n var x = -winScroll.scrollLeft + getWindowScrollBarX(element);\n var y = -winScroll.scrollTop;\n\n if (getComputedStyle(body || html).direction === 'rtl') {\n x += max(html.clientWidth, body ? body.clientWidth : 0) - width;\n }\n\n return {\n width: width,\n height: height,\n x: x,\n y: y\n };\n}", "import getComputedStyle from \"./getComputedStyle.js\";\nexport default function isScrollParent(element) {\n // Firefox wants us to check `-x` and `-y` variations as well\n var _getComputedStyle = getComputedStyle(element),\n overflow = _getComputedStyle.overflow,\n overflowX = _getComputedStyle.overflowX,\n overflowY = _getComputedStyle.overflowY;\n\n return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX);\n}", "import getParentNode from \"./getParentNode.js\";\nimport isScrollParent from \"./isScrollParent.js\";\nimport getNodeName from \"./getNodeName.js\";\nimport { isHTMLElement } from \"./instanceOf.js\";\nexport default function getScrollParent(node) {\n if (['html', 'body', '#document'].indexOf(getNodeName(node)) >= 0) {\n // $FlowFixMe[incompatible-return]: assume body is always available\n return node.ownerDocument.body;\n }\n\n if (isHTMLElement(node) && isScrollParent(node)) {\n return node;\n }\n\n return getScrollParent(getParentNode(node));\n}", "import getScrollParent from \"./getScrollParent.js\";\nimport getParentNode from \"./getParentNode.js\";\nimport getWindow from \"./getWindow.js\";\nimport isScrollParent from \"./isScrollParent.js\";\n/*\ngiven a DOM element, return the list of all scroll parents, up the list of ancesors\nuntil we get to the top window object. This list is what we attach scroll listeners\nto, because if any of these parent elements scroll, we'll need to re-calculate the\nreference element's position.\n*/\n\nexport default function listScrollParents(element, list) {\n var _element$ownerDocumen;\n\n if (list === void 0) {\n list = [];\n }\n\n var scrollParent = getScrollParent(element);\n var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body);\n var win = getWindow(scrollParent);\n var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent;\n var updatedList = list.concat(target);\n return isBody ? updatedList : // $FlowFixMe[incompatible-call]: isBody tells us target will be an HTMLElement here\n updatedList.concat(listScrollParents(getParentNode(target)));\n}", "export default function rectToClientRect(rect) {\n return Object.assign({}, rect, {\n left: rect.x,\n top: rect.y,\n right: rect.x + rect.width,\n bottom: rect.y + rect.height\n });\n}", "import { viewport } from \"../enums.js\";\nimport getViewportRect from \"./getViewportRect.js\";\nimport getDocumentRect from \"./getDocumentRect.js\";\nimport listScrollParents from \"./listScrollParents.js\";\nimport getOffsetParent from \"./getOffsetParent.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport getComputedStyle from \"./getComputedStyle.js\";\nimport { isElement, isHTMLElement } from \"./instanceOf.js\";\nimport getBoundingClientRect from \"./getBoundingClientRect.js\";\nimport getParentNode from \"./getParentNode.js\";\nimport contains from \"./contains.js\";\nimport getNodeName from \"./getNodeName.js\";\nimport rectToClientRect from \"../utils/rectToClientRect.js\";\nimport { max, min } from \"../utils/math.js\";\n\nfunction getInnerBoundingClientRect(element) {\n var rect = getBoundingClientRect(element);\n rect.top = rect.top + element.clientTop;\n rect.left = rect.left + element.clientLeft;\n rect.bottom = rect.top + element.clientHeight;\n rect.right = rect.left + element.clientWidth;\n rect.width = element.clientWidth;\n rect.height = element.clientHeight;\n rect.x = rect.left;\n rect.y = rect.top;\n return rect;\n}\n\nfunction getClientRectFromMixedType(element, clippingParent) {\n return clippingParent === viewport ? rectToClientRect(getViewportRect(element)) : isElement(clippingParent) ? getInnerBoundingClientRect(clippingParent) : rectToClientRect(getDocumentRect(getDocumentElement(element)));\n} // A \"clipping parent\" is an overflowable container with the characteristic of\n// clipping (or hiding) overflowing elements with a position different from\n// `initial`\n\n\nfunction getClippingParents(element) {\n var clippingParents = listScrollParents(getParentNode(element));\n var canEscapeClipping = ['absolute', 'fixed'].indexOf(getComputedStyle(element).position) >= 0;\n var clipperElement = canEscapeClipping && isHTMLElement(element) ? getOffsetParent(element) : element;\n\n if (!isElement(clipperElement)) {\n return [];\n } // $FlowFixMe[incompatible-return]: https://github.com/facebook/flow/issues/1414\n\n\n return clippingParents.filter(function (clippingParent) {\n return isElement(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== 'body';\n });\n} // Gets the maximum area that the element is visible in due to any number of\n// clipping parents\n\n\nexport default function getClippingRect(element, boundary, rootBoundary) {\n var mainClippingParents = boundary === 'clippingParents' ? getClippingParents(element) : [].concat(boundary);\n var clippingParents = [].concat(mainClippingParents, [rootBoundary]);\n var firstClippingParent = clippingParents[0];\n var clippingRect = clippingParents.reduce(function (accRect, clippingParent) {\n var rect = getClientRectFromMixedType(element, clippingParent);\n accRect.top = max(rect.top, accRect.top);\n accRect.right = min(rect.right, accRect.right);\n accRect.bottom = min(rect.bottom, accRect.bottom);\n accRect.left = max(rect.left, accRect.left);\n return accRect;\n }, getClientRectFromMixedType(element, firstClippingParent));\n clippingRect.width = clippingRect.right - clippingRect.left;\n clippingRect.height = clippingRect.bottom - clippingRect.top;\n clippingRect.x = clippingRect.left;\n clippingRect.y = clippingRect.top;\n return clippingRect;\n}", "import getBasePlacement from \"./getBasePlacement.js\";\nimport getVariation from \"./getVariation.js\";\nimport getMainAxisFromPlacement from \"./getMainAxisFromPlacement.js\";\nimport { top, right, bottom, left, start, end } from \"../enums.js\";\nexport default function computeOffsets(_ref) {\n var reference = _ref.reference,\n element = _ref.element,\n placement = _ref.placement;\n var basePlacement = placement ? getBasePlacement(placement) : null;\n var variation = placement ? getVariation(placement) : null;\n var commonX = reference.x + reference.width / 2 - element.width / 2;\n var commonY = reference.y + reference.height / 2 - element.height / 2;\n var offsets;\n\n switch (basePlacement) {\n case top:\n offsets = {\n x: commonX,\n y: reference.y - element.height\n };\n break;\n\n case bottom:\n offsets = {\n x: commonX,\n y: reference.y + reference.height\n };\n break;\n\n case right:\n offsets = {\n x: reference.x + reference.width,\n y: commonY\n };\n break;\n\n case left:\n offsets = {\n x: reference.x - element.width,\n y: commonY\n };\n break;\n\n default:\n offsets = {\n x: reference.x,\n y: reference.y\n };\n }\n\n var mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null;\n\n if (mainAxis != null) {\n var len = mainAxis === 'y' ? 'height' : 'width';\n\n switch (variation) {\n case start:\n offsets[mainAxis] = offsets[mainAxis] - (reference[len] / 2 - element[len] / 2);\n break;\n\n case end:\n offsets[mainAxis] = offsets[mainAxis] + (reference[len] / 2 - element[len] / 2);\n break;\n\n default:\n }\n }\n\n return offsets;\n}", "import getClippingRect from \"../dom-utils/getClippingRect.js\";\nimport getDocumentElement from \"../dom-utils/getDocumentElement.js\";\nimport getBoundingClientRect from \"../dom-utils/getBoundingClientRect.js\";\nimport computeOffsets from \"./computeOffsets.js\";\nimport rectToClientRect from \"./rectToClientRect.js\";\nimport { clippingParents, reference, popper, bottom, top, right, basePlacements, viewport } from \"../enums.js\";\nimport { isElement } from \"../dom-utils/instanceOf.js\";\nimport mergePaddingObject from \"./mergePaddingObject.js\";\nimport expandToHashMap from \"./expandToHashMap.js\"; // eslint-disable-next-line import/no-unused-modules\n\nexport default function detectOverflow(state, options) {\n if (options === void 0) {\n options = {};\n }\n\n var _options = options,\n _options$placement = _options.placement,\n placement = _options$placement === void 0 ? state.placement : _options$placement,\n _options$boundary = _options.boundary,\n boundary = _options$boundary === void 0 ? clippingParents : _options$boundary,\n _options$rootBoundary = _options.rootBoundary,\n rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary,\n _options$elementConte = _options.elementContext,\n elementContext = _options$elementConte === void 0 ? popper : _options$elementConte,\n _options$altBoundary = _options.altBoundary,\n altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary,\n _options$padding = _options.padding,\n padding = _options$padding === void 0 ? 0 : _options$padding;\n var paddingObject = mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements));\n var altContext = elementContext === popper ? reference : popper;\n var popperRect = state.rects.popper;\n var element = state.elements[altBoundary ? altContext : elementContext];\n var clippingClientRect = getClippingRect(isElement(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary);\n var referenceClientRect = getBoundingClientRect(state.elements.reference);\n var popperOffsets = computeOffsets({\n reference: referenceClientRect,\n element: popperRect,\n strategy: 'absolute',\n placement: placement\n });\n var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets));\n var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect; // positive = overflowing the clipping rect\n // 0 or negative = within the clipping rect\n\n var overflowOffsets = {\n top: clippingClientRect.top - elementClientRect.top + paddingObject.top,\n bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom,\n left: clippingClientRect.left - elementClientRect.left + paddingObject.left,\n right: elementClientRect.right - clippingClientRect.right + paddingObject.right\n };\n var offsetData = state.modifiersData.offset; // Offsets can be applied only to the popper element\n\n if (elementContext === popper && offsetData) {\n var offset = offsetData[placement];\n Object.keys(overflowOffsets).forEach(function (key) {\n var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1;\n var axis = [top, bottom].indexOf(key) >= 0 ? 'y' : 'x';\n overflowOffsets[key] += offset[axis] * multiply;\n });\n }\n\n return overflowOffsets;\n}", "import getVariation from \"./getVariation.js\";\nimport { variationPlacements, basePlacements, placements as allPlacements } from \"../enums.js\";\nimport detectOverflow from \"./detectOverflow.js\";\nimport getBasePlacement from \"./getBasePlacement.js\";\nexport default function computeAutoPlacement(state, options) {\n if (options === void 0) {\n options = {};\n }\n\n var _options = options,\n placement = _options.placement,\n boundary = _options.boundary,\n rootBoundary = _options.rootBoundary,\n padding = _options.padding,\n flipVariations = _options.flipVariations,\n _options$allowedAutoP = _options.allowedAutoPlacements,\n allowedAutoPlacements = _options$allowedAutoP === void 0 ? allPlacements : _options$allowedAutoP;\n var variation = getVariation(placement);\n var placements = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function (placement) {\n return getVariation(placement) === variation;\n }) : basePlacements;\n var allowedPlacements = placements.filter(function (placement) {\n return allowedAutoPlacements.indexOf(placement) >= 0;\n });\n\n if (allowedPlacements.length === 0) {\n allowedPlacements = placements;\n\n if (process.env.NODE_ENV !== \"production\") {\n console.error(['Popper: The `allowedAutoPlacements` option did not allow any', 'placements. Ensure the `placement` option matches the variation', 'of the allowed placements.', 'For example, \"auto\" cannot be used to allow \"bottom-start\".', 'Use \"auto-start\" instead.'].join(' '));\n }\n } // $FlowFixMe[incompatible-type]: Flow seems to have problems with two array unions...\n\n\n var overflows = allowedPlacements.reduce(function (acc, placement) {\n acc[placement] = detectOverflow(state, {\n placement: placement,\n boundary: boundary,\n rootBoundary: rootBoundary,\n padding: padding\n })[getBasePlacement(placement)];\n return acc;\n }, {});\n return Object.keys(overflows).sort(function (a, b) {\n return overflows[a] - overflows[b];\n });\n}", "import getOppositePlacement from \"../utils/getOppositePlacement.js\";\nimport getBasePlacement from \"../utils/getBasePlacement.js\";\nimport getOppositeVariationPlacement from \"../utils/getOppositeVariationPlacement.js\";\nimport detectOverflow from \"../utils/detectOverflow.js\";\nimport computeAutoPlacement from \"../utils/computeAutoPlacement.js\";\nimport { bottom, top, start, right, left, auto } from \"../enums.js\";\nimport getVariation from \"../utils/getVariation.js\"; // eslint-disable-next-line import/no-unused-modules\n\nfunction getExpandedFallbackPlacements(placement) {\n if (getBasePlacement(placement) === auto) {\n return [];\n }\n\n var oppositePlacement = getOppositePlacement(placement);\n return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)];\n}\n\nfunction flip(_ref) {\n var state = _ref.state,\n options = _ref.options,\n name = _ref.name;\n\n if (state.modifiersData[name]._skip) {\n return;\n }\n\n var _options$mainAxis = options.mainAxis,\n checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,\n _options$altAxis = options.altAxis,\n checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis,\n specifiedFallbackPlacements = options.fallbackPlacements,\n padding = options.padding,\n boundary = options.boundary,\n rootBoundary = options.rootBoundary,\n altBoundary = options.altBoundary,\n _options$flipVariatio = options.flipVariations,\n flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio,\n allowedAutoPlacements = options.allowedAutoPlacements;\n var preferredPlacement = state.options.placement;\n var basePlacement = getBasePlacement(preferredPlacement);\n var isBasePlacement = basePlacement === preferredPlacement;\n var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement));\n var placements = [preferredPlacement].concat(fallbackPlacements).reduce(function (acc, placement) {\n return acc.concat(getBasePlacement(placement) === auto ? computeAutoPlacement(state, {\n placement: placement,\n boundary: boundary,\n rootBoundary: rootBoundary,\n padding: padding,\n flipVariations: flipVariations,\n allowedAutoPlacements: allowedAutoPlacements\n }) : placement);\n }, []);\n var referenceRect = state.rects.reference;\n var popperRect = state.rects.popper;\n var checksMap = new Map();\n var makeFallbackChecks = true;\n var firstFittingPlacement = placements[0];\n\n for (var i = 0; i < placements.length; i++) {\n var placement = placements[i];\n\n var _basePlacement = getBasePlacement(placement);\n\n var isStartVariation = getVariation(placement) === start;\n var isVertical = [top, bottom].indexOf(_basePlacement) >= 0;\n var len = isVertical ? 'width' : 'height';\n var overflow = detectOverflow(state, {\n placement: placement,\n boundary: boundary,\n rootBoundary: rootBoundary,\n altBoundary: altBoundary,\n padding: padding\n });\n var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : top;\n\n if (referenceRect[len] > popperRect[len]) {\n mainVariationSide = getOppositePlacement(mainVariationSide);\n }\n\n var altVariationSide = getOppositePlacement(mainVariationSide);\n var checks = [];\n\n if (checkMainAxis) {\n checks.push(overflow[_basePlacement] <= 0);\n }\n\n if (checkAltAxis) {\n checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0);\n }\n\n if (checks.every(function (check) {\n return check;\n })) {\n firstFittingPlacement = placement;\n makeFallbackChecks = false;\n break;\n }\n\n checksMap.set(placement, checks);\n }\n\n if (makeFallbackChecks) {\n // `2` may be desired in some cases \u2013 research later\n var numberOfChecks = flipVariations ? 3 : 1;\n\n var _loop = function _loop(_i) {\n var fittingPlacement = placements.find(function (placement) {\n var checks = checksMap.get(placement);\n\n if (checks) {\n return checks.slice(0, _i).every(function (check) {\n return check;\n });\n }\n });\n\n if (fittingPlacement) {\n firstFittingPlacement = fittingPlacement;\n return \"break\";\n }\n };\n\n for (var _i = numberOfChecks; _i > 0; _i--) {\n var _ret = _loop(_i);\n\n if (_ret === \"break\") break;\n }\n }\n\n if (state.placement !== firstFittingPlacement) {\n state.modifiersData[name]._skip = true;\n state.placement = firstFittingPlacement;\n state.reset = true;\n }\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'flip',\n enabled: true,\n phase: 'main',\n fn: flip,\n requiresIfExists: ['offset'],\n data: {\n _skip: false\n }\n};", "import { top, bottom, left, right } from \"../enums.js\";\nimport detectOverflow from \"../utils/detectOverflow.js\";\n\nfunction getSideOffsets(overflow, rect, preventedOffsets) {\n if (preventedOffsets === void 0) {\n preventedOffsets = {\n x: 0,\n y: 0\n };\n }\n\n return {\n top: overflow.top - rect.height - preventedOffsets.y,\n right: overflow.right - rect.width + preventedOffsets.x,\n bottom: overflow.bottom - rect.height + preventedOffsets.y,\n left: overflow.left - rect.width - preventedOffsets.x\n };\n}\n\nfunction isAnySideFullyClipped(overflow) {\n return [top, right, bottom, left].some(function (side) {\n return overflow[side] >= 0;\n });\n}\n\nfunction hide(_ref) {\n var state = _ref.state,\n name = _ref.name;\n var referenceRect = state.rects.reference;\n var popperRect = state.rects.popper;\n var preventedOffsets = state.modifiersData.preventOverflow;\n var referenceOverflow = detectOverflow(state, {\n elementContext: 'reference'\n });\n var popperAltOverflow = detectOverflow(state, {\n altBoundary: true\n });\n var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect);\n var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets);\n var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets);\n var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets);\n state.modifiersData[name] = {\n referenceClippingOffsets: referenceClippingOffsets,\n popperEscapeOffsets: popperEscapeOffsets,\n isReferenceHidden: isReferenceHidden,\n hasPopperEscaped: hasPopperEscaped\n };\n state.attributes.popper = Object.assign({}, state.attributes.popper, {\n 'data-popper-reference-hidden': isReferenceHidden,\n 'data-popper-escaped': hasPopperEscaped\n });\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'hide',\n enabled: true,\n phase: 'main',\n requiresIfExists: ['preventOverflow'],\n fn: hide\n};", "import getBasePlacement from \"../utils/getBasePlacement.js\";\nimport { top, left, right, placements } from \"../enums.js\"; // eslint-disable-next-line import/no-unused-modules\n\nexport function distanceAndSkiddingToXY(placement, rects, offset) {\n var basePlacement = getBasePlacement(placement);\n var invertDistance = [left, top].indexOf(basePlacement) >= 0 ? -1 : 1;\n\n var _ref = typeof offset === 'function' ? offset(Object.assign({}, rects, {\n placement: placement\n })) : offset,\n skidding = _ref[0],\n distance = _ref[1];\n\n skidding = skidding || 0;\n distance = (distance || 0) * invertDistance;\n return [left, right].indexOf(basePlacement) >= 0 ? {\n x: distance,\n y: skidding\n } : {\n x: skidding,\n y: distance\n };\n}\n\nfunction offset(_ref2) {\n var state = _ref2.state,\n options = _ref2.options,\n name = _ref2.name;\n var _options$offset = options.offset,\n offset = _options$offset === void 0 ? [0, 0] : _options$offset;\n var data = placements.reduce(function (acc, placement) {\n acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset);\n return acc;\n }, {});\n var _data$state$placement = data[state.placement],\n x = _data$state$placement.x,\n y = _data$state$placement.y;\n\n if (state.modifiersData.popperOffsets != null) {\n state.modifiersData.popperOffsets.x += x;\n state.modifiersData.popperOffsets.y += y;\n }\n\n state.modifiersData[name] = data;\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'offset',\n enabled: true,\n phase: 'main',\n requires: ['popperOffsets'],\n fn: offset\n};", "import computeOffsets from \"../utils/computeOffsets.js\";\n\nfunction popperOffsets(_ref) {\n var state = _ref.state,\n name = _ref.name;\n // Offsets are the actual position the popper needs to have to be\n // properly positioned near its reference element\n // This is the most basic placement, and will be adjusted by\n // the modifiers in the next step\n state.modifiersData[name] = computeOffsets({\n reference: state.rects.reference,\n element: state.rects.popper,\n strategy: 'absolute',\n placement: state.placement\n });\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'popperOffsets',\n enabled: true,\n phase: 'read',\n fn: popperOffsets,\n data: {}\n};", "export default function getAltAxis(axis) {\n return axis === 'x' ? 'y' : 'x';\n}", "import { top, left, right, bottom, start } from \"../enums.js\";\nimport getBasePlacement from \"../utils/getBasePlacement.js\";\nimport getMainAxisFromPlacement from \"../utils/getMainAxisFromPlacement.js\";\nimport getAltAxis from \"../utils/getAltAxis.js\";\nimport { within, withinMaxClamp } from \"../utils/within.js\";\nimport getLayoutRect from \"../dom-utils/getLayoutRect.js\";\nimport getOffsetParent from \"../dom-utils/getOffsetParent.js\";\nimport detectOverflow from \"../utils/detectOverflow.js\";\nimport getVariation from \"../utils/getVariation.js\";\nimport getFreshSideObject from \"../utils/getFreshSideObject.js\";\nimport { min as mathMin, max as mathMax } from \"../utils/math.js\";\n\nfunction preventOverflow(_ref) {\n var state = _ref.state,\n options = _ref.options,\n name = _ref.name;\n var _options$mainAxis = options.mainAxis,\n checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis,\n _options$altAxis = options.altAxis,\n checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis,\n boundary = options.boundary,\n rootBoundary = options.rootBoundary,\n altBoundary = options.altBoundary,\n padding = options.padding,\n _options$tether = options.tether,\n tether = _options$tether === void 0 ? true : _options$tether,\n _options$tetherOffset = options.tetherOffset,\n tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset;\n var overflow = detectOverflow(state, {\n boundary: boundary,\n rootBoundary: rootBoundary,\n padding: padding,\n altBoundary: altBoundary\n });\n var basePlacement = getBasePlacement(state.placement);\n var variation = getVariation(state.placement);\n var isBasePlacement = !variation;\n var mainAxis = getMainAxisFromPlacement(basePlacement);\n var altAxis = getAltAxis(mainAxis);\n var popperOffsets = state.modifiersData.popperOffsets;\n var referenceRect = state.rects.reference;\n var popperRect = state.rects.popper;\n var tetherOffsetValue = typeof tetherOffset === 'function' ? tetherOffset(Object.assign({}, state.rects, {\n placement: state.placement\n })) : tetherOffset;\n var normalizedTetherOffsetValue = typeof tetherOffsetValue === 'number' ? {\n mainAxis: tetherOffsetValue,\n altAxis: tetherOffsetValue\n } : Object.assign({\n mainAxis: 0,\n altAxis: 0\n }, tetherOffsetValue);\n var offsetModifierState = state.modifiersData.offset ? state.modifiersData.offset[state.placement] : null;\n var data = {\n x: 0,\n y: 0\n };\n\n if (!popperOffsets) {\n return;\n }\n\n if (checkMainAxis) {\n var _offsetModifierState$;\n\n var mainSide = mainAxis === 'y' ? top : left;\n var altSide = mainAxis === 'y' ? bottom : right;\n var len = mainAxis === 'y' ? 'height' : 'width';\n var offset = popperOffsets[mainAxis];\n var min = offset + overflow[mainSide];\n var max = offset - overflow[altSide];\n var additive = tether ? -popperRect[len] / 2 : 0;\n var minLen = variation === start ? referenceRect[len] : popperRect[len];\n var maxLen = variation === start ? -popperRect[len] : -referenceRect[len]; // We need to include the arrow in the calculation so the arrow doesn't go\n // outside the reference bounds\n\n var arrowElement = state.elements.arrow;\n var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : {\n width: 0,\n height: 0\n };\n var arrowPaddingObject = state.modifiersData['arrow#persistent'] ? state.modifiersData['arrow#persistent'].padding : getFreshSideObject();\n var arrowPaddingMin = arrowPaddingObject[mainSide];\n var arrowPaddingMax = arrowPaddingObject[altSide]; // If the reference length is smaller than the arrow length, we don't want\n // to include its full size in the calculation. If the reference is small\n // and near the edge of a boundary, the popper can overflow even if the\n // reference is not overflowing as well (e.g. virtual elements with no\n // width or height)\n\n var arrowLen = within(0, referenceRect[len], arrowRect[len]);\n var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis : minLen - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis;\n var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis : maxLen + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis;\n var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow);\n var clientOffset = arrowOffsetParent ? mainAxis === 'y' ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0;\n var offsetModifierValue = (_offsetModifierState$ = offsetModifierState == null ? void 0 : offsetModifierState[mainAxis]) != null ? _offsetModifierState$ : 0;\n var tetherMin = offset + minOffset - offsetModifierValue - clientOffset;\n var tetherMax = offset + maxOffset - offsetModifierValue;\n var preventedOffset = within(tether ? mathMin(min, tetherMin) : min, offset, tether ? mathMax(max, tetherMax) : max);\n popperOffsets[mainAxis] = preventedOffset;\n data[mainAxis] = preventedOffset - offset;\n }\n\n if (checkAltAxis) {\n var _offsetModifierState$2;\n\n var _mainSide = mainAxis === 'x' ? top : left;\n\n var _altSide = mainAxis === 'x' ? bottom : right;\n\n var _offset = popperOffsets[altAxis];\n\n var _len = altAxis === 'y' ? 'height' : 'width';\n\n var _min = _offset + overflow[_mainSide];\n\n var _max = _offset - overflow[_altSide];\n\n var isOriginSide = [top, left].indexOf(basePlacement) !== -1;\n\n var _offsetModifierValue = (_offsetModifierState$2 = offsetModifierState == null ? void 0 : offsetModifierState[altAxis]) != null ? _offsetModifierState$2 : 0;\n\n var _tetherMin = isOriginSide ? _min : _offset - referenceRect[_len] - popperRect[_len] - _offsetModifierValue + normalizedTetherOffsetValue.altAxis;\n\n var _tetherMax = isOriginSide ? _offset + referenceRect[_len] + popperRect[_len] - _offsetModifierValue - normalizedTetherOffsetValue.altAxis : _max;\n\n var _preventedOffset = tether && isOriginSide ? withinMaxClamp(_tetherMin, _offset, _tetherMax) : within(tether ? _tetherMin : _min, _offset, tether ? _tetherMax : _max);\n\n popperOffsets[altAxis] = _preventedOffset;\n data[altAxis] = _preventedOffset - _offset;\n }\n\n state.modifiersData[name] = data;\n} // eslint-disable-next-line import/no-unused-modules\n\n\nexport default {\n name: 'preventOverflow',\n enabled: true,\n phase: 'main',\n fn: preventOverflow,\n requiresIfExists: ['offset']\n};", "export default function getHTMLElementScroll(element) {\n return {\n scrollLeft: element.scrollLeft,\n scrollTop: element.scrollTop\n };\n}", "import getWindowScroll from \"./getWindowScroll.js\";\nimport getWindow from \"./getWindow.js\";\nimport { isHTMLElement } from \"./instanceOf.js\";\nimport getHTMLElementScroll from \"./getHTMLElementScroll.js\";\nexport default function getNodeScroll(node) {\n if (node === getWindow(node) || !isHTMLElement(node)) {\n return getWindowScroll(node);\n } else {\n return getHTMLElementScroll(node);\n }\n}", "import getBoundingClientRect from \"./getBoundingClientRect.js\";\nimport getNodeScroll from \"./getNodeScroll.js\";\nimport getNodeName from \"./getNodeName.js\";\nimport { isHTMLElement } from \"./instanceOf.js\";\nimport getWindowScrollBarX from \"./getWindowScrollBarX.js\";\nimport getDocumentElement from \"./getDocumentElement.js\";\nimport isScrollParent from \"./isScrollParent.js\";\nimport { round } from \"../utils/math.js\";\n\nfunction isElementScaled(element) {\n var rect = element.getBoundingClientRect();\n var scaleX = round(rect.width) / element.offsetWidth || 1;\n var scaleY = round(rect.height) / element.offsetHeight || 1;\n return scaleX !== 1 || scaleY !== 1;\n} // Returns the composite rect of an element relative to its offsetParent.\n// Composite means it takes into account transforms as well as layout.\n\n\nexport default function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) {\n if (isFixed === void 0) {\n isFixed = false;\n }\n\n var isOffsetParentAnElement = isHTMLElement(offsetParent);\n var offsetParentIsScaled = isHTMLElement(offsetParent) && isElementScaled(offsetParent);\n var documentElement = getDocumentElement(offsetParent);\n var rect = getBoundingClientRect(elementOrVirtualElement, offsetParentIsScaled);\n var scroll = {\n scrollLeft: 0,\n scrollTop: 0\n };\n var offsets = {\n x: 0,\n y: 0\n };\n\n if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {\n if (getNodeName(offsetParent) !== 'body' || // https://github.com/popperjs/popper-core/issues/1078\n isScrollParent(documentElement)) {\n scroll = getNodeScroll(offsetParent);\n }\n\n if (isHTMLElement(offsetParent)) {\n offsets = getBoundingClientRect(offsetParent, true);\n offsets.x += offsetParent.clientLeft;\n offsets.y += offsetParent.clientTop;\n } else if (documentElement) {\n offsets.x = getWindowScrollBarX(documentElement);\n }\n }\n\n return {\n x: rect.left + scroll.scrollLeft - offsets.x,\n y: rect.top + scroll.scrollTop - offsets.y,\n width: rect.width,\n height: rect.height\n };\n}", "import { modifierPhases } from \"../enums.js\"; // source: https://stackoverflow.com/questions/49875255\n\nfunction order(modifiers) {\n var map = new Map();\n var visited = new Set();\n var result = [];\n modifiers.forEach(function (modifier) {\n map.set(modifier.name, modifier);\n }); // On visiting object, check for its dependencies and visit them recursively\n\n function sort(modifier) {\n visited.add(modifier.name);\n var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []);\n requires.forEach(function (dep) {\n if (!visited.has(dep)) {\n var depModifier = map.get(dep);\n\n if (depModifier) {\n sort(depModifier);\n }\n }\n });\n result.push(modifier);\n }\n\n modifiers.forEach(function (modifier) {\n if (!visited.has(modifier.name)) {\n // check for visited object\n sort(modifier);\n }\n });\n return result;\n}\n\nexport default function orderModifiers(modifiers) {\n // order based on dependencies\n var orderedModifiers = order(modifiers); // order based on phase\n\n return modifierPhases.reduce(function (acc, phase) {\n return acc.concat(orderedModifiers.filter(function (modifier) {\n return modifier.phase === phase;\n }));\n }, []);\n}", "export default function debounce(fn) {\n var pending;\n return function () {\n if (!pending) {\n pending = new Promise(function (resolve) {\n Promise.resolve().then(function () {\n pending = undefined;\n resolve(fn());\n });\n });\n }\n\n return pending;\n };\n}", "export default function mergeByName(modifiers) {\n var merged = modifiers.reduce(function (merged, current) {\n var existing = merged[current.name];\n merged[current.name] = existing ? Object.assign({}, existing, current, {\n options: Object.assign({}, existing.options, current.options),\n data: Object.assign({}, existing.data, current.data)\n }) : current;\n return merged;\n }, {}); // IE11 does not support Object.values\n\n return Object.keys(merged).map(function (key) {\n return merged[key];\n });\n}", "import getCompositeRect from \"./dom-utils/getCompositeRect.js\";\nimport getLayoutRect from \"./dom-utils/getLayoutRect.js\";\nimport listScrollParents from \"./dom-utils/listScrollParents.js\";\nimport getOffsetParent from \"./dom-utils/getOffsetParent.js\";\nimport getComputedStyle from \"./dom-utils/getComputedStyle.js\";\nimport orderModifiers from \"./utils/orderModifiers.js\";\nimport debounce from \"./utils/debounce.js\";\nimport validateModifiers from \"./utils/validateModifiers.js\";\nimport uniqueBy from \"./utils/uniqueBy.js\";\nimport getBasePlacement from \"./utils/getBasePlacement.js\";\nimport mergeByName from \"./utils/mergeByName.js\";\nimport detectOverflow from \"./utils/detectOverflow.js\";\nimport { isElement } from \"./dom-utils/instanceOf.js\";\nimport { auto } from \"./enums.js\";\nvar INVALID_ELEMENT_ERROR = 'Popper: Invalid reference or popper argument provided. They must be either a DOM element or virtual element.';\nvar INFINITE_LOOP_ERROR = 'Popper: An infinite loop in the modifiers cycle has been detected! The cycle has been interrupted to prevent a browser crash.';\nvar DEFAULT_OPTIONS = {\n placement: 'bottom',\n modifiers: [],\n strategy: 'absolute'\n};\n\nfunction areValidElements() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return !args.some(function (element) {\n return !(element && typeof element.getBoundingClientRect === 'function');\n });\n}\n\nexport function popperGenerator(generatorOptions) {\n if (generatorOptions === void 0) {\n generatorOptions = {};\n }\n\n var _generatorOptions = generatorOptions,\n _generatorOptions$def = _generatorOptions.defaultModifiers,\n defaultModifiers = _generatorOptions$def === void 0 ? [] : _generatorOptions$def,\n _generatorOptions$def2 = _generatorOptions.defaultOptions,\n defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2;\n return function createPopper(reference, popper, options) {\n if (options === void 0) {\n options = defaultOptions;\n }\n\n var state = {\n placement: 'bottom',\n orderedModifiers: [],\n options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions),\n modifiersData: {},\n elements: {\n reference: reference,\n popper: popper\n },\n attributes: {},\n styles: {}\n };\n var effectCleanupFns = [];\n var isDestroyed = false;\n var instance = {\n state: state,\n setOptions: function setOptions(setOptionsAction) {\n var options = typeof setOptionsAction === 'function' ? setOptionsAction(state.options) : setOptionsAction;\n cleanupModifierEffects();\n state.options = Object.assign({}, defaultOptions, state.options, options);\n state.scrollParents = {\n reference: isElement(reference) ? listScrollParents(reference) : reference.contextElement ? listScrollParents(reference.contextElement) : [],\n popper: listScrollParents(popper)\n }; // Orders the modifiers based on their dependencies and `phase`\n // properties\n\n var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers, state.options.modifiers))); // Strip out disabled modifiers\n\n state.orderedModifiers = orderedModifiers.filter(function (m) {\n return m.enabled;\n }); // Validate the provided modifiers so that the consumer will get warned\n // if one of the modifiers is invalid for any reason\n\n if (process.env.NODE_ENV !== \"production\") {\n var modifiers = uniqueBy([].concat(orderedModifiers, state.options.modifiers), function (_ref) {\n var name = _ref.name;\n return name;\n });\n validateModifiers(modifiers);\n\n if (getBasePlacement(state.options.placement) === auto) {\n var flipModifier = state.orderedModifiers.find(function (_ref2) {\n var name = _ref2.name;\n return name === 'flip';\n });\n\n if (!flipModifier) {\n console.error(['Popper: \"auto\" placements require the \"flip\" modifier be', 'present and enabled to work.'].join(' '));\n }\n }\n\n var _getComputedStyle = getComputedStyle(popper),\n marginTop = _getComputedStyle.marginTop,\n marginRight = _getComputedStyle.marginRight,\n marginBottom = _getComputedStyle.marginBottom,\n marginLeft = _getComputedStyle.marginLeft; // We no longer take into account `margins` on the popper, and it can\n // cause bugs with positioning, so we'll warn the consumer\n\n\n if ([marginTop, marginRight, marginBottom, marginLeft].some(function (margin) {\n return parseFloat(margin);\n })) {\n console.warn(['Popper: CSS \"margin\" styles cannot be used to apply padding', 'between the popper and its reference element or boundary.', 'To replicate margin, use the `offset` modifier, as well as', 'the `padding` option in the `preventOverflow` and `flip`', 'modifiers.'].join(' '));\n }\n }\n\n runModifierEffects();\n return instance.update();\n },\n // Sync update \u2013 it will always be executed, even if not necessary. This\n // is useful for low frequency updates where sync behavior simplifies the\n // logic.\n // For high frequency updates (e.g. `resize` and `scroll` events), always\n // prefer the async Popper#update method\n forceUpdate: function forceUpdate() {\n if (isDestroyed) {\n return;\n }\n\n var _state$elements = state.elements,\n reference = _state$elements.reference,\n popper = _state$elements.popper; // Don't proceed if `reference` or `popper` are not valid elements\n // anymore\n\n if (!areValidElements(reference, popper)) {\n if (process.env.NODE_ENV !== \"production\") {\n console.error(INVALID_ELEMENT_ERROR);\n }\n\n return;\n } // Store the reference and popper rects to be read by modifiers\n\n\n state.rects = {\n reference: getCompositeRect(reference, getOffsetParent(popper), state.options.strategy === 'fixed'),\n popper: getLayoutRect(popper)\n }; // Modifiers have the ability to reset the current update cycle. The\n // most common use case for this is the `flip` modifier changing the\n // placement, which then needs to re-run all the modifiers, because the\n // logic was previously ran for the previous placement and is therefore\n // stale/incorrect\n\n state.reset = false;\n state.placement = state.options.placement; // On each update cycle, the `modifiersData` property for each modifier\n // is filled with the initial data specified by the modifier. This means\n // it doesn't persist and is fresh on each update.\n // To ensure persistent data, use `${name}#persistent`\n\n state.orderedModifiers.forEach(function (modifier) {\n return state.modifiersData[modifier.name] = Object.assign({}, modifier.data);\n });\n var __debug_loops__ = 0;\n\n for (var index = 0; index < state.orderedModifiers.length; index++) {\n if (process.env.NODE_ENV !== \"production\") {\n __debug_loops__ += 1;\n\n if (__debug_loops__ > 100) {\n console.error(INFINITE_LOOP_ERROR);\n break;\n }\n }\n\n if (state.reset === true) {\n state.reset = false;\n index = -1;\n continue;\n }\n\n var _state$orderedModifie = state.orderedModifiers[index],\n fn = _state$orderedModifie.fn,\n _state$orderedModifie2 = _state$orderedModifie.options,\n _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2,\n name = _state$orderedModifie.name;\n\n if (typeof fn === 'function') {\n state = fn({\n state: state,\n options: _options,\n name: name,\n instance: instance\n }) || state;\n }\n }\n },\n // Async and optimistically optimized update \u2013 it will not be executed if\n // not necessary (debounced to run at most once-per-tick)\n update: debounce(function () {\n return new Promise(function (resolve) {\n instance.forceUpdate();\n resolve(state);\n });\n }),\n destroy: function destroy() {\n cleanupModifierEffects();\n isDestroyed = true;\n }\n };\n\n if (!areValidElements(reference, popper)) {\n if (process.env.NODE_ENV !== \"production\") {\n console.error(INVALID_ELEMENT_ERROR);\n }\n\n return instance;\n }\n\n instance.setOptions(options).then(function (state) {\n if (!isDestroyed && options.onFirstUpdate) {\n options.onFirstUpdate(state);\n }\n }); // Modifiers have the ability to execute arbitrary code before the first\n // update cycle runs. They will be executed in the same order as the update\n // cycle. This is useful when a modifier adds some persistent data that\n // other modifiers need to use, but the modifier is run after the dependent\n // one.\n\n function runModifierEffects() {\n state.orderedModifiers.forEach(function (_ref3) {\n var name = _ref3.name,\n _ref3$options = _ref3.options,\n options = _ref3$options === void 0 ? {} : _ref3$options,\n effect = _ref3.effect;\n\n if (typeof effect === 'function') {\n var cleanupFn = effect({\n state: state,\n name: name,\n instance: instance,\n options: options\n });\n\n var noopFn = function noopFn() {};\n\n effectCleanupFns.push(cleanupFn || noopFn);\n }\n });\n }\n\n function cleanupModifierEffects() {\n effectCleanupFns.forEach(function (fn) {\n return fn();\n });\n effectCleanupFns = [];\n }\n\n return instance;\n };\n}\nexport var createPopper = /*#__PURE__*/popperGenerator(); // eslint-disable-next-line import/no-unused-modules\n\nexport { detectOverflow };", "import { popperGenerator, detectOverflow } from \"./createPopper.js\";\nimport eventListeners from \"./modifiers/eventListeners.js\";\nimport popperOffsets from \"./modifiers/popperOffsets.js\";\nimport computeStyles from \"./modifiers/computeStyles.js\";\nimport applyStyles from \"./modifiers/applyStyles.js\";\nimport offset from \"./modifiers/offset.js\";\nimport flip from \"./modifiers/flip.js\";\nimport preventOverflow from \"./modifiers/preventOverflow.js\";\nimport arrow from \"./modifiers/arrow.js\";\nimport hide from \"./modifiers/hide.js\";\nvar defaultModifiers = [eventListeners, popperOffsets, computeStyles, applyStyles, offset, flip, preventOverflow, arrow, hide];\nvar createPopper = /*#__PURE__*/popperGenerator({\n defaultModifiers: defaultModifiers\n}); // eslint-disable-next-line import/no-unused-modules\n\nexport { createPopper, popperGenerator, defaultModifiers, detectOverflow }; // eslint-disable-next-line import/no-unused-modules\n\nexport { createPopper as createPopperLite } from \"./popper-lite.js\"; // eslint-disable-next-line import/no-unused-modules\n\nexport * from \"./modifiers/index.js\";", "export const ROUND_ARROW =\n '';\n\nexport const BOX_CLASS = `__NAMESPACE_PREFIX__-box`;\nexport const CONTENT_CLASS = `__NAMESPACE_PREFIX__-content`;\nexport const BACKDROP_CLASS = `__NAMESPACE_PREFIX__-backdrop`;\nexport const ARROW_CLASS = `__NAMESPACE_PREFIX__-arrow`;\nexport const SVG_ARROW_CLASS = `__NAMESPACE_PREFIX__-svg-arrow`;\n\nexport const TOUCH_OPTIONS = {passive: true, capture: true};\n\nexport const TIPPY_DEFAULT_APPEND_TO = () => document.body;\n", "import {BasePlacement, Placement} from './types';\n\nexport function hasOwnProperty(\n obj: Record,\n key: string\n): boolean {\n return {}.hasOwnProperty.call(obj, key);\n}\n\nexport function getValueAtIndexOrReturn(\n value: T | [T | null, T | null],\n index: number,\n defaultValue: T | [T, T]\n): T {\n if (Array.isArray(value)) {\n const v = value[index];\n return v == null\n ? Array.isArray(defaultValue)\n ? defaultValue[index]\n : defaultValue\n : v;\n }\n\n return value;\n}\n\nexport function isType(value: any, type: string): boolean {\n const str = {}.toString.call(value);\n return str.indexOf('[object') === 0 && str.indexOf(`${type}]`) > -1;\n}\n\nexport function invokeWithArgsOrReturn(value: any, args: any[]): any {\n return typeof value === 'function' ? value(...args) : value;\n}\n\nexport function debounce(\n fn: (arg: T) => void,\n ms: number\n): (arg: T) => void {\n // Avoid wrapping in `setTimeout` if ms is 0 anyway\n if (ms === 0) {\n return fn;\n }\n\n let timeout: any;\n\n return (arg): void => {\n clearTimeout(timeout);\n timeout = setTimeout(() => {\n fn(arg);\n }, ms);\n };\n}\n\nexport function removeProperties(obj: T, keys: string[]): Partial {\n const clone = {...obj};\n keys.forEach((key) => {\n delete (clone as any)[key];\n });\n return clone;\n}\n\nexport function splitBySpaces(value: string): string[] {\n return value.split(/\\s+/).filter(Boolean);\n}\n\nexport function normalizeToArray(value: T | T[]): T[] {\n return ([] as T[]).concat(value);\n}\n\nexport function pushIfUnique(arr: T[], value: T): void {\n if (arr.indexOf(value) === -1) {\n arr.push(value);\n }\n}\n\nexport function appendPxIfNumber(value: string | number): string {\n return typeof value === 'number' ? `${value}px` : value;\n}\n\nexport function unique(arr: T[]): T[] {\n return arr.filter((item, index) => arr.indexOf(item) === index);\n}\n\nexport function getNumber(value: string | number): number {\n return typeof value === 'number' ? value : parseFloat(value);\n}\n\nexport function getBasePlacement(placement: Placement): BasePlacement {\n return placement.split('-')[0] as BasePlacement;\n}\n\nexport function arrayFrom(value: ArrayLike): any[] {\n return [].slice.call(value);\n}\n\nexport function removeUndefinedProps(\n obj: Record\n): Partial> {\n return Object.keys(obj).reduce((acc, key) => {\n if (obj[key] !== undefined) {\n (acc as any)[key] = obj[key];\n }\n\n return acc;\n }, {});\n}\n", "import {ReferenceElement, Targets} from './types';\nimport {PopperTreeData} from './types-internal';\nimport {arrayFrom, isType, normalizeToArray, getBasePlacement} from './utils';\n\nexport function div(): HTMLDivElement {\n return document.createElement('div');\n}\n\nexport function isElement(value: unknown): value is Element | DocumentFragment {\n return ['Element', 'Fragment'].some((type) => isType(value, type));\n}\n\nexport function isNodeList(value: unknown): value is NodeList {\n return isType(value, 'NodeList');\n}\n\nexport function isMouseEvent(value: unknown): value is MouseEvent {\n return isType(value, 'MouseEvent');\n}\n\nexport function isReferenceElement(value: any): value is ReferenceElement {\n return !!(value && value._tippy && value._tippy.reference === value);\n}\n\nexport function getArrayOfElements(value: Targets): Element[] {\n if (isElement(value)) {\n return [value];\n }\n\n if (isNodeList(value)) {\n return arrayFrom(value);\n }\n\n if (Array.isArray(value)) {\n return value;\n }\n\n return arrayFrom(document.querySelectorAll(value));\n}\n\nexport function setTransitionDuration(\n els: (HTMLDivElement | null)[],\n value: number\n): void {\n els.forEach((el) => {\n if (el) {\n el.style.transitionDuration = `${value}ms`;\n }\n });\n}\n\nexport function setVisibilityState(\n els: (HTMLDivElement | null)[],\n state: 'visible' | 'hidden'\n): void {\n els.forEach((el) => {\n if (el) {\n el.setAttribute('data-state', state);\n }\n });\n}\n\nexport function getOwnerDocument(\n elementOrElements: Element | Element[]\n): Document {\n const [element] = normalizeToArray(elementOrElements);\n\n // Elements created via a