( ′∀`)σ≡σ☆))Д′)レ(゚∀゚;)ヘ=З=З=Зε≡(ノ´_ゝ`)ノ HEX
HEX
Server: Apache/2.4.58 (Ubuntu)
System: Linux mail.thebrand.ai 6.8.0-107-generic #107-Ubuntu SMP PREEMPT_DYNAMIC Fri Mar 13 19:51:50 UTC 2026 x86_64
User: www-data (33)
PHP: 8.3.6
Disabled: NONE
Upload Files
File: /var/www/html/tmpr/../tmpr/../tmpr/../tmpr/../tmpr/../dist/pixie.es.js
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a2, b2) => {
  for (var prop in b2 || (b2 = {}))
    if (__hasOwnProp.call(b2, prop))
      __defNormalProp(a2, prop, b2[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b2)) {
      if (__propIsEnum.call(b2, prop))
        __defNormalProp(a2, prop, b2[prop]);
    }
  return a2;
};
var __spreadProps = (a2, b2) => __defProps(a2, __getOwnPropDescs(b2));
var __objRest = (source, exclude) => {
  var target = {};
  for (var prop in source)
    if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
      target[prop] = source[prop];
  if (source != null && __getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(source)) {
      if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
        target[prop] = source[prop];
    }
  return target;
};
var __publicField = (obj, key, value) => {
  __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  return value;
};
var _e, _f;
import * as React from "react";
import React__default, { forwardRef, useReducer, useRef, useDebugValue, useEffect, useLayoutEffect, createContext, useContext, useCallback, useMemo, createElement, useState, cloneElement, Children, isValidElement, useImperativeHandle, Fragment as Fragment$1 } from "react";
import $icz4I$reactdom from "react-dom";
var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
function getDefaultExportFromCjs(x2) {
  return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2;
}
function getAugmentedNamespace(n2) {
  if (n2.__esModule)
    return n2;
  var a2 = Object.defineProperty({}, "__esModule", {
    value: true
  });
  Object.keys(n2).forEach(function(k2) {
    var d2 = Object.getOwnPropertyDescriptor(n2, k2);
    Object.defineProperty(a2, k2, d2.get ? d2 : {
      enumerable: true,
      get: function() {
        return n2[k2];
      }
    });
  });
  return a2;
}
var isMergeableObject = function isMergeableObject2(value) {
  return isNonNullObject(value) && !isSpecial(value);
};
function isNonNullObject(value) {
  return !!value && typeof value === "object";
}
function isSpecial(value) {
  var stringValue = Object.prototype.toString.call(value);
  return stringValue === "[object RegExp]" || stringValue === "[object Date]" || isReactElement(value);
}
var canUseSymbol = typeof Symbol === "function" && Symbol.for;
var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for("react.element") : 60103;
function isReactElement(value) {
  return value.$$typeof === REACT_ELEMENT_TYPE;
}
function emptyTarget(val) {
  return Array.isArray(val) ? [] : {};
}
function cloneUnlessOtherwiseSpecified(value, options) {
  return options.clone !== false && options.isMergeableObject(value) ? deepmerge(emptyTarget(value), value, options) : value;
}
function defaultArrayMerge(target, source, options) {
  return target.concat(source).map(function(element) {
    return cloneUnlessOtherwiseSpecified(element, options);
  });
}
function getMergeFunction(key, options) {
  if (!options.customMerge) {
    return deepmerge;
  }
  var customMerge = options.customMerge(key);
  return typeof customMerge === "function" ? customMerge : deepmerge;
}
function getEnumerableOwnPropertySymbols(target) {
  return Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(target).filter(function(symbol) {
    return target.propertyIsEnumerable(symbol);
  }) : [];
}
function getKeys(target) {
  return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target));
}
function propertyIsOnObject(object, property) {
  try {
    return property in object;
  } catch (_2) {
    return false;
  }
}
function propertyIsUnsafe(target, key) {
  return propertyIsOnObject(target, key) && !(Object.hasOwnProperty.call(target, key) && Object.propertyIsEnumerable.call(target, key));
}
function mergeObject(target, source, options) {
  var destination = {};
  if (options.isMergeableObject(target)) {
    getKeys(target).forEach(function(key) {
      destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
    });
  }
  getKeys(source).forEach(function(key) {
    if (propertyIsUnsafe(target, key)) {
      return;
    }
    if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) {
      destination[key] = getMergeFunction(key, options)(target[key], source[key], options);
    } else {
      destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
    }
  });
  return destination;
}
function deepmerge(target, source, options) {
  options = options || {};
  options.arrayMerge = options.arrayMerge || defaultArrayMerge;
  options.isMergeableObject = options.isMergeableObject || isMergeableObject;
  options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified;
  var sourceIsArray = Array.isArray(source);
  var targetIsArray = Array.isArray(target);
  var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  if (!sourceAndTargetTypesMatch) {
    return cloneUnlessOtherwiseSpecified(source, options);
  } else if (sourceIsArray) {
    return options.arrayMerge(target, source, options);
  } else {
    return mergeObject(target, source, options);
  }
}
deepmerge.all = function deepmergeAll(array, options) {
  if (!Array.isArray(array)) {
    throw new Error("first argument should be an array");
  }
  return array.reduce(function(prev, next) {
    return deepmerge(prev, next, options);
  }, {});
};
var deepmerge_1 = deepmerge;
var cjs = deepmerge_1;
function styleInject(css2, ref) {
  if (ref === void 0)
    ref = {};
  var insertAt = ref.insertAt;
  if (!css2 || typeof document === "undefined") {
    return;
  }
  var head = document.head || document.getElementsByTagName("head")[0];
  var style2 = document.createElement("style");
  style2.type = "text/css";
  if (insertAt === "top") {
    if (head.firstChild) {
      head.insertBefore(style2, head.firstChild);
    } else {
      head.appendChild(style2);
    }
  } else {
    head.appendChild(style2);
  }
  if (style2.styleSheet) {
    style2.styleSheet.cssText = css2;
  } else {
    style2.appendChild(document.createTextNode(css2));
  }
}
function strip(num, precision) {
  if (precision === void 0) {
    precision = 15;
  }
  return +parseFloat(Number(num).toPrecision(precision));
}
function digitLength(num) {
  var eSplit = num.toString().split(/[eE]/);
  var len = (eSplit[0].split(".")[1] || "").length - +(eSplit[1] || 0);
  return len > 0 ? len : 0;
}
function float2Fixed(num) {
  if (num.toString().indexOf("e") === -1) {
    return Number(num.toString().replace(".", ""));
  }
  var dLen = digitLength(num);
  return dLen > 0 ? strip(Number(num) * Math.pow(10, dLen)) : Number(num);
}
function checkBoundary(num) {
  if (_boundaryCheckingState) {
    if (num > Number.MAX_SAFE_INTEGER || num < Number.MIN_SAFE_INTEGER) {
      console.warn(num + " is beyond boundary when transfer to integer, the results may not be accurate");
    }
  }
}
function iteratorOperation(arr, operation) {
  var num1 = arr[0], num2 = arr[1], others = arr.slice(2);
  var res = operation(num1, num2);
  others.forEach(function(num) {
    res = operation(res, num);
  });
  return res;
}
function times() {
  var nums = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    nums[_i] = arguments[_i];
  }
  if (nums.length > 2) {
    return iteratorOperation(nums, times);
  }
  var num1 = nums[0], num2 = nums[1];
  var num1Changed = float2Fixed(num1);
  var num2Changed = float2Fixed(num2);
  var baseNum = digitLength(num1) + digitLength(num2);
  var leftValue = num1Changed * num2Changed;
  checkBoundary(leftValue);
  return leftValue / Math.pow(10, baseNum);
}
function plus() {
  var nums = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    nums[_i] = arguments[_i];
  }
  if (nums.length > 2) {
    return iteratorOperation(nums, plus);
  }
  var num1 = nums[0], num2 = nums[1];
  var baseNum = Math.pow(10, Math.max(digitLength(num1), digitLength(num2)));
  return (times(num1, baseNum) + times(num2, baseNum)) / baseNum;
}
function minus() {
  var nums = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    nums[_i] = arguments[_i];
  }
  if (nums.length > 2) {
    return iteratorOperation(nums, minus);
  }
  var num1 = nums[0], num2 = nums[1];
  var baseNum = Math.pow(10, Math.max(digitLength(num1), digitLength(num2)));
  return (times(num1, baseNum) - times(num2, baseNum)) / baseNum;
}
function divide() {
  var nums = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    nums[_i] = arguments[_i];
  }
  if (nums.length > 2) {
    return iteratorOperation(nums, divide);
  }
  var num1 = nums[0], num2 = nums[1];
  var num1Changed = float2Fixed(num1);
  var num2Changed = float2Fixed(num2);
  checkBoundary(num1Changed);
  checkBoundary(num2Changed);
  return times(num1Changed / num2Changed, strip(Math.pow(10, digitLength(num2) - digitLength(num1))));
}
function round(num, ratio) {
  var base = Math.pow(10, ratio);
  var result = divide(Math.round(Math.abs(times(num, base))), base);
  if (num < 0 && result !== 0) {
    result = times(result, -1);
  }
  return result;
}
var _boundaryCheckingState = true;
function enableBoundaryChecking(flag) {
  if (flag === void 0) {
    flag = true;
  }
  _boundaryCheckingState = flag;
}
var index$1 = {
  strip,
  plus,
  minus,
  times,
  divide,
  round,
  digitLength,
  float2Fixed,
  enableBoundaryChecking
};
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
var extendStatics$3 = function(d2, b2) {
  extendStatics$3 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d3, b3) {
    d3.__proto__ = b3;
  } || function(d3, b3) {
    for (var p2 in b3)
      if (b3.hasOwnProperty(p2))
        d3[p2] = b3[p2];
  };
  return extendStatics$3(d2, b2);
};
function __extends$3(d2, b2) {
  extendStatics$3(d2, b2);
  function __() {
    this.constructor = d2;
  }
  d2.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __());
}
var __assign$5 = function() {
  __assign$5 = Object.assign || function __assign2(t2) {
    for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
      s2 = arguments[i2];
      for (var p2 in s2)
        if (Object.prototype.hasOwnProperty.call(s2, p2))
          t2[p2] = s2[p2];
    }
    return t2;
  };
  return __assign$5.apply(this, arguments);
};
function __values$4(o2) {
  var s2 = typeof Symbol === "function" && Symbol.iterator, m2 = s2 && o2[s2], i2 = 0;
  if (m2)
    return m2.call(o2);
  if (o2 && typeof o2.length === "number")
    return {
      next: function() {
        if (o2 && i2 >= o2.length)
          o2 = void 0;
        return { value: o2 && o2[i2++], done: !o2 };
      }
    };
  throw new TypeError(s2 ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read$6(o2, n2) {
  var m2 = typeof Symbol === "function" && o2[Symbol.iterator];
  if (!m2)
    return o2;
  var i2 = m2.call(o2), r2, ar = [], e2;
  try {
    while ((n2 === void 0 || n2-- > 0) && !(r2 = i2.next()).done)
      ar.push(r2.value);
  } catch (error) {
    e2 = { error };
  } finally {
    try {
      if (r2 && !r2.done && (m2 = i2["return"]))
        m2.call(i2);
    } finally {
      if (e2)
        throw e2.error;
    }
  }
  return ar;
}
function __spread$5() {
  for (var ar = [], i2 = 0; i2 < arguments.length; i2++)
    ar = ar.concat(__read$6(arguments[i2]));
  return ar;
}
var Severity;
(function(Severity2) {
  Severity2["Fatal"] = "fatal";
  Severity2["Error"] = "error";
  Severity2["Warning"] = "warning";
  Severity2["Log"] = "log";
  Severity2["Info"] = "info";
  Severity2["Debug"] = "debug";
  Severity2["Critical"] = "critical";
})(Severity || (Severity = {}));
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __read$5(o2, n2) {
  var m2 = typeof Symbol === "function" && o2[Symbol.iterator];
  if (!m2)
    return o2;
  var i2 = m2.call(o2), r2, ar = [], e2;
  try {
    while ((n2 === void 0 || n2-- > 0) && !(r2 = i2.next()).done)
      ar.push(r2.value);
  } catch (error) {
    e2 = { error };
  } finally {
    try {
      if (r2 && !r2.done && (m2 = i2["return"]))
        m2.call(i2);
    } finally {
      if (e2)
        throw e2.error;
    }
  }
  return ar;
}
function __spread$4() {
  for (var ar = [], i2 = 0; i2 < arguments.length; i2++)
    ar = ar.concat(__read$5(arguments[i2]));
  return ar;
}
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
var __assign$4 = function() {
  __assign$4 = Object.assign || function __assign2(t2) {
    for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
      s2 = arguments[i2];
      for (var p2 in s2)
        if (Object.prototype.hasOwnProperty.call(s2, p2))
          t2[p2] = s2[p2];
    }
    return t2;
  };
  return __assign$4.apply(this, arguments);
};
function __read$4(o2, n2) {
  var m2 = typeof Symbol === "function" && o2[Symbol.iterator];
  if (!m2)
    return o2;
  var i2 = m2.call(o2), r2, ar = [], e2;
  try {
    while ((n2 === void 0 || n2-- > 0) && !(r2 = i2.next()).done)
      ar.push(r2.value);
  } catch (error) {
    e2 = { error };
  } finally {
    try {
      if (r2 && !r2.done && (m2 = i2["return"]))
        m2.call(i2);
    } finally {
      if (e2)
        throw e2.error;
    }
  }
  return ar;
}
function __spread$3() {
  for (var ar = [], i2 = 0; i2 < arguments.length; i2++)
    ar = ar.concat(__read$4(arguments[i2]));
  return ar;
}
function forget(promise) {
  void promise.then(null, function(e2) {
    console.error(e2);
  });
}
function isDebugBuild() {
  return typeof __SENTRY_NO_DEBUG__ !== "undefined" && !__SENTRY_BROWSER_BUNDLE__;
}
function isBrowserBundle() {
  return typeof __SENTRY_BROWSER_BUNDLE__ !== "undefined" && !!__SENTRY_BROWSER_BUNDLE__;
}
function isNodeEnv() {
  return !isBrowserBundle() && Object.prototype.toString.call(typeof process !== "undefined" ? process : 0) === "[object process]";
}
function dynamicRequire(mod, request) {
  return mod.require(request);
}
function loadModule(moduleName) {
  var mod;
  try {
    mod = dynamicRequire(module, moduleName);
  } catch (e2) {
  }
  try {
    var cwd = dynamicRequire(module, "process").cwd;
    mod = dynamicRequire(module, cwd() + "/node_modules/" + moduleName);
  } catch (e2) {
  }
  return mod;
}
var fallbackGlobalObject = {};
function getGlobalObject() {
  return isNodeEnv() ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : fallbackGlobalObject;
}
var objectToString = Object.prototype.toString;
function isError(wat) {
  switch (objectToString.call(wat)) {
    case "[object Error]":
    case "[object Exception]":
    case "[object DOMException]":
      return true;
    default:
      return isInstanceOf(wat, Error);
  }
}
function isBuiltin(wat, ty) {
  return objectToString.call(wat) === "[object " + ty + "]";
}
function isErrorEvent(wat) {
  return isBuiltin(wat, "ErrorEvent");
}
function isDOMError(wat) {
  return isBuiltin(wat, "DOMError");
}
function isDOMException(wat) {
  return isBuiltin(wat, "DOMException");
}
function isString$1(wat) {
  return isBuiltin(wat, "String");
}
function isPrimitive$1(wat) {
  return wat === null || typeof wat !== "object" && typeof wat !== "function";
}
function isPlainObject(wat) {
  return isBuiltin(wat, "Object");
}
function isEvent(wat) {
  return typeof Event !== "undefined" && isInstanceOf(wat, Event);
}
function isElement(wat) {
  return typeof Element !== "undefined" && isInstanceOf(wat, Element);
}
function isRegExp(wat) {
  return isBuiltin(wat, "RegExp");
}
function isThenable(wat) {
  return Boolean(wat && wat.then && typeof wat.then === "function");
}
function isSyntheticEvent(wat) {
  return isPlainObject(wat) && "nativeEvent" in wat && "preventDefault" in wat && "stopPropagation" in wat;
}
function isInstanceOf(wat, base) {
  try {
    return wat instanceof base;
  } catch (_e2) {
    return false;
  }
}
function htmlTreeAsString(elem, keyAttrs) {
  try {
    var currentElem = elem;
    var MAX_TRAVERSE_HEIGHT = 5;
    var MAX_OUTPUT_LEN = 80;
    var out = [];
    var height = 0;
    var len = 0;
    var separator = " > ";
    var sepLength = separator.length;
    var nextStr = void 0;
    while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {
      nextStr = _htmlElementAsString(currentElem, keyAttrs);
      if (nextStr === "html" || height > 1 && len + out.length * sepLength + nextStr.length >= MAX_OUTPUT_LEN) {
        break;
      }
      out.push(nextStr);
      len += nextStr.length;
      currentElem = currentElem.parentNode;
    }
    return out.reverse().join(separator);
  } catch (_oO) {
    return "<unknown>";
  }
}
function _htmlElementAsString(el, keyAttrs) {
  var elem = el;
  var out = [];
  var className;
  var classes;
  var key;
  var attr;
  var i2;
  if (!elem || !elem.tagName) {
    return "";
  }
  out.push(elem.tagName.toLowerCase());
  var keyAttrPairs = keyAttrs && keyAttrs.length ? keyAttrs.filter(function(keyAttr) {
    return elem.getAttribute(keyAttr);
  }).map(function(keyAttr) {
    return [keyAttr, elem.getAttribute(keyAttr)];
  }) : null;
  if (keyAttrPairs && keyAttrPairs.length) {
    keyAttrPairs.forEach(function(keyAttrPair) {
      out.push("[" + keyAttrPair[0] + '="' + keyAttrPair[1] + '"]');
    });
  } else {
    if (elem.id) {
      out.push("#" + elem.id);
    }
    className = elem.className;
    if (className && isString$1(className)) {
      classes = className.split(/\s+/);
      for (i2 = 0; i2 < classes.length; i2++) {
        out.push("." + classes[i2]);
      }
    }
  }
  var allowedAttrs = ["type", "name", "title", "alt"];
  for (i2 = 0; i2 < allowedAttrs.length; i2++) {
    key = allowedAttrs[i2];
    attr = elem.getAttribute(key);
    if (attr) {
      out.push("[" + key + '="' + attr + '"]');
    }
  }
  return out.join("");
}
function getLocationHref() {
  var global2 = getGlobalObject();
  try {
    return global2.document.location.href;
  } catch (oO) {
    return "";
  }
}
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
var extendStatics$2 = function(d2, b2) {
  extendStatics$2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d3, b3) {
    d3.__proto__ = b3;
  } || function(d3, b3) {
    for (var p2 in b3)
      if (b3.hasOwnProperty(p2))
        d3[p2] = b3[p2];
  };
  return extendStatics$2(d2, b2);
};
function __extends$2(d2, b2) {
  extendStatics$2(d2, b2);
  function __() {
    this.constructor = d2;
  }
  d2.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __());
}
var __assign$3 = function() {
  __assign$3 = Object.assign || function __assign2(t2) {
    for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
      s2 = arguments[i2];
      for (var p2 in s2)
        if (Object.prototype.hasOwnProperty.call(s2, p2))
          t2[p2] = s2[p2];
    }
    return t2;
  };
  return __assign$3.apply(this, arguments);
};
function __values$3(o2) {
  var s2 = typeof Symbol === "function" && Symbol.iterator, m2 = s2 && o2[s2], i2 = 0;
  if (m2)
    return m2.call(o2);
  if (o2 && typeof o2.length === "number")
    return {
      next: function() {
        if (o2 && i2 >= o2.length)
          o2 = void 0;
        return { value: o2 && o2[i2++], done: !o2 };
      }
    };
  throw new TypeError(s2 ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read$3(o2, n2) {
  var m2 = typeof Symbol === "function" && o2[Symbol.iterator];
  if (!m2)
    return o2;
  var i2 = m2.call(o2), r2, ar = [], e2;
  try {
    while ((n2 === void 0 || n2-- > 0) && !(r2 = i2.next()).done)
      ar.push(r2.value);
  } catch (error) {
    e2 = { error };
  } finally {
    try {
      if (r2 && !r2.done && (m2 = i2["return"]))
        m2.call(i2);
    } finally {
      if (e2)
        throw e2.error;
    }
  }
  return ar;
}
var setPrototypeOf = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array ? setProtoOf : mixinProperties);
function setProtoOf(obj, proto) {
  obj.__proto__ = proto;
  return obj;
}
function mixinProperties(obj, proto) {
  for (var prop in proto) {
    if (!Object.prototype.hasOwnProperty.call(obj, prop)) {
      obj[prop] = proto[prop];
    }
  }
  return obj;
}
var SentryError = function(_super) {
  __extends$2(SentryError2, _super);
  function SentryError2(message) {
    var _newTarget = this.constructor;
    var _this = _super.call(this, message) || this;
    _this.message = message;
    _this.name = _newTarget.prototype.constructor.name;
    setPrototypeOf(_this, _newTarget.prototype);
    return _this;
  }
  return SentryError2;
}(Error);
var DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+))?@)([\w.-]+)(?::(\d+))?\/(.+)/;
function isValidProtocol(protocol) {
  return protocol === "http" || protocol === "https";
}
function dsnToString(dsn, withPassword) {
  if (withPassword === void 0) {
    withPassword = false;
  }
  var host = dsn.host, path = dsn.path, pass = dsn.pass, port = dsn.port, projectId = dsn.projectId, protocol = dsn.protocol, publicKey = dsn.publicKey;
  return protocol + "://" + publicKey + (withPassword && pass ? ":" + pass : "") + ("@" + host + (port ? ":" + port : "") + "/" + (path ? path + "/" : path) + projectId);
}
function dsnFromString(str) {
  var match = DSN_REGEX.exec(str);
  if (!match) {
    throw new SentryError("Invalid Sentry Dsn: " + str);
  }
  var _a2 = __read$3(match.slice(1), 6), protocol = _a2[0], publicKey = _a2[1], _b = _a2[2], pass = _b === void 0 ? "" : _b, host = _a2[3], _c = _a2[4], port = _c === void 0 ? "" : _c, lastPath = _a2[5];
  var path = "";
  var projectId = lastPath;
  var split = projectId.split("/");
  if (split.length > 1) {
    path = split.slice(0, -1).join("/");
    projectId = split.pop();
  }
  if (projectId) {
    var projectMatch = projectId.match(/^\d+/);
    if (projectMatch) {
      projectId = projectMatch[0];
    }
  }
  return dsnFromComponents({ host, pass, path, projectId, port, protocol, publicKey });
}
function dsnFromComponents(components) {
  if ("user" in components && !("publicKey" in components)) {
    components.publicKey = components.user;
  }
  return {
    user: components.publicKey || "",
    protocol: components.protocol,
    publicKey: components.publicKey || "",
    pass: components.pass || "",
    host: components.host,
    port: components.port || "",
    path: components.path || "",
    projectId: components.projectId
  };
}
function validateDsn(dsn) {
  if (!isDebugBuild()) {
    return;
  }
  var port = dsn.port, projectId = dsn.projectId, protocol = dsn.protocol;
  var requiredComponents = ["protocol", "publicKey", "host", "projectId"];
  requiredComponents.forEach(function(component) {
    if (!dsn[component]) {
      throw new SentryError("Invalid Sentry Dsn: " + component + " missing");
    }
  });
  if (!projectId.match(/^\d+$/)) {
    throw new SentryError("Invalid Sentry Dsn: Invalid projectId " + projectId);
  }
  if (!isValidProtocol(protocol)) {
    throw new SentryError("Invalid Sentry Dsn: Invalid protocol " + protocol);
  }
  if (port && isNaN(parseInt(port, 10))) {
    throw new SentryError("Invalid Sentry Dsn: Invalid port " + port);
  }
  return true;
}
function makeDsn(from) {
  var components = typeof from === "string" ? dsnFromString(from) : dsnFromComponents(from);
  validateDsn(components);
  return components;
}
var SeverityLevels = ["fatal", "error", "warning", "log", "info", "debug", "critical"];
var global$9 = getGlobalObject();
var PREFIX = "Sentry Logger ";
function consoleSandbox(callback) {
  var global2 = getGlobalObject();
  var levels = ["debug", "info", "warn", "error", "log", "assert"];
  if (!("console" in global2)) {
    return callback();
  }
  var originalConsole = global2.console;
  var wrappedLevels = {};
  levels.forEach(function(level) {
    if (level in global2.console && originalConsole[level].__sentry_original__) {
      wrappedLevels[level] = originalConsole[level];
      originalConsole[level] = originalConsole[level].__sentry_original__;
    }
  });
  var result = callback();
  Object.keys(wrappedLevels).forEach(function(level) {
    originalConsole[level] = wrappedLevels[level];
  });
  return result;
}
var Logger = function() {
  function Logger2() {
    this._enabled = false;
  }
  Logger2.prototype.disable = function() {
    this._enabled = false;
  };
  Logger2.prototype.enable = function() {
    this._enabled = true;
  };
  Logger2.prototype.log = function() {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
      args[_i] = arguments[_i];
    }
    if (!this._enabled) {
      return;
    }
    consoleSandbox(function() {
      global$9.console.log(PREFIX + "[Log]: " + args.join(" "));
    });
  };
  Logger2.prototype.warn = function() {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
      args[_i] = arguments[_i];
    }
    if (!this._enabled) {
      return;
    }
    consoleSandbox(function() {
      global$9.console.warn(PREFIX + "[Warn]: " + args.join(" "));
    });
  };
  Logger2.prototype.error = function() {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
      args[_i] = arguments[_i];
    }
    if (!this._enabled) {
      return;
    }
    consoleSandbox(function() {
      global$9.console.error(PREFIX + "[Error]: " + args.join(" "));
    });
  };
  return Logger2;
}();
global$9.__SENTRY__ = global$9.__SENTRY__ || {};
var logger = global$9.__SENTRY__.logger || (global$9.__SENTRY__.logger = new Logger());
function memoBuilder() {
  var hasWeakSet = typeof WeakSet === "function";
  var inner = hasWeakSet ? /* @__PURE__ */ new WeakSet() : [];
  function memoize2(obj) {
    if (hasWeakSet) {
      if (inner.has(obj)) {
        return true;
      }
      inner.add(obj);
      return false;
    }
    for (var i2 = 0; i2 < inner.length; i2++) {
      var value = inner[i2];
      if (value === obj) {
        return true;
      }
    }
    inner.push(obj);
    return false;
  }
  function unmemoize(obj) {
    if (hasWeakSet) {
      inner.delete(obj);
    } else {
      for (var i2 = 0; i2 < inner.length; i2++) {
        if (inner[i2] === obj) {
          inner.splice(i2, 1);
          break;
        }
      }
    }
  }
  return [memoize2, unmemoize];
}
var STACKTRACE_LIMIT = 50;
function createStackParser() {
  var parsers = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    parsers[_i] = arguments[_i];
  }
  return function(stack, skipFirst) {
    var e_1, _a2, e_2, _b;
    if (skipFirst === void 0) {
      skipFirst = 0;
    }
    var frames = [];
    try {
      for (var _c = __values$3(stack.split("\n").slice(skipFirst)), _d = _c.next(); !_d.done; _d = _c.next()) {
        var line = _d.value;
        try {
          for (var parsers_1 = (e_2 = void 0, __values$3(parsers)), parsers_1_1 = parsers_1.next(); !parsers_1_1.done; parsers_1_1 = parsers_1.next()) {
            var parser = parsers_1_1.value;
            var frame2 = parser(line);
            if (frame2) {
              frames.push(frame2);
              break;
            }
          }
        } catch (e_2_1) {
          e_2 = { error: e_2_1 };
        } finally {
          try {
            if (parsers_1_1 && !parsers_1_1.done && (_b = parsers_1.return))
              _b.call(parsers_1);
          } finally {
            if (e_2)
              throw e_2.error;
          }
        }
      }
    } catch (e_1_1) {
      e_1 = { error: e_1_1 };
    } finally {
      try {
        if (_d && !_d.done && (_a2 = _c.return))
          _a2.call(_c);
      } finally {
        if (e_1)
          throw e_1.error;
      }
    }
    return stripSentryFramesAndReverse(frames);
  };
}
function stripSentryFramesAndReverse(stack) {
  if (!stack.length) {
    return [];
  }
  var localStack = stack;
  var firstFrameFunction = localStack[0].function || "";
  var lastFrameFunction = localStack[localStack.length - 1].function || "";
  if (firstFrameFunction.indexOf("captureMessage") !== -1 || firstFrameFunction.indexOf("captureException") !== -1) {
    localStack = localStack.slice(1);
  }
  if (lastFrameFunction.indexOf("sentryWrapped") !== -1) {
    localStack = localStack.slice(0, -1);
  }
  return localStack.slice(0, STACKTRACE_LIMIT).map(function(frame2) {
    return __assign$3(__assign$3({}, frame2), { filename: frame2.filename || localStack[0].filename, function: frame2.function || "?" });
  }).reverse();
}
var defaultFunctionName = "<anonymous>";
function getFunctionName(fn2) {
  try {
    if (!fn2 || typeof fn2 !== "function") {
      return defaultFunctionName;
    }
    return fn2.name || defaultFunctionName;
  } catch (e2) {
    return defaultFunctionName;
  }
}
function truncate(str, max) {
  if (max === void 0) {
    max = 0;
  }
  if (typeof str !== "string" || max === 0) {
    return str;
  }
  return str.length <= max ? str : str.substr(0, max) + "...";
}
function safeJoin(input, delimiter) {
  if (!Array.isArray(input)) {
    return "";
  }
  var output = [];
  for (var i2 = 0; i2 < input.length; i2++) {
    var value = input[i2];
    try {
      output.push(String(value));
    } catch (e2) {
      output.push("[value cannot be serialized]");
    }
  }
  return output.join(delimiter);
}
function isMatchingPattern(value, pattern) {
  if (!isString$1(value)) {
    return false;
  }
  if (isRegExp(pattern)) {
    return pattern.test(value);
  }
  if (typeof pattern === "string") {
    return value.indexOf(pattern) !== -1;
  }
  return false;
}
function fill(source, name, replacementFactory) {
  if (!(name in source)) {
    return;
  }
  var original = source[name];
  var wrapped = replacementFactory(original);
  if (typeof wrapped === "function") {
    try {
      markFunctionWrapped(wrapped, original);
    } catch (_Oo) {
    }
  }
  source[name] = wrapped;
}
function addNonEnumerableProperty(obj, name, value) {
  Object.defineProperty(obj, name, {
    value,
    writable: true,
    configurable: true
  });
}
function markFunctionWrapped(wrapped, original) {
  var proto = original.prototype || {};
  wrapped.prototype = original.prototype = proto;
  addNonEnumerableProperty(wrapped, "__sentry_original__", original);
}
function getOriginalFunction(func) {
  return func.__sentry_original__;
}
function urlEncode(object) {
  return Object.keys(object).map(function(key) {
    return encodeURIComponent(key) + "=" + encodeURIComponent(object[key]);
  }).join("&");
}
function getWalkSource(value) {
  if (isError(value)) {
    var error = value;
    var err = {
      message: error.message,
      name: error.name,
      stack: error.stack
    };
    for (var i2 in error) {
      if (Object.prototype.hasOwnProperty.call(error, i2)) {
        err[i2] = error[i2];
      }
    }
    return err;
  }
  if (isEvent(value)) {
    var event_1 = value;
    var source = {};
    source.type = event_1.type;
    try {
      source.target = isElement(event_1.target) ? htmlTreeAsString(event_1.target) : Object.prototype.toString.call(event_1.target);
    } catch (_oO) {
      source.target = "<unknown>";
    }
    try {
      source.currentTarget = isElement(event_1.currentTarget) ? htmlTreeAsString(event_1.currentTarget) : Object.prototype.toString.call(event_1.currentTarget);
    } catch (_oO) {
      source.currentTarget = "<unknown>";
    }
    if (typeof CustomEvent !== "undefined" && isInstanceOf(value, CustomEvent)) {
      source.detail = event_1.detail;
    }
    for (var attr in event_1) {
      if (Object.prototype.hasOwnProperty.call(event_1, attr)) {
        source[attr] = event_1[attr];
      }
    }
    return source;
  }
  return value;
}
function utf8Length(value) {
  return ~-encodeURI(value).split(/%..|./).length;
}
function jsonSize(value) {
  return utf8Length(JSON.stringify(value));
}
function normalizeToSize(object, depth, maxSize) {
  if (depth === void 0) {
    depth = 3;
  }
  if (maxSize === void 0) {
    maxSize = 100 * 1024;
  }
  var serialized = normalize(object, depth);
  if (jsonSize(serialized) > maxSize) {
    return normalizeToSize(object, depth - 1, maxSize);
  }
  return serialized;
}
function serializeValue(value) {
  if (typeof value === "string") {
    return value;
  }
  var type = Object.prototype.toString.call(value);
  if (type === "[object Object]") {
    return "[Object]";
  }
  if (type === "[object Array]") {
    return "[Array]";
  }
  var normalized = normalizeValue(value);
  return isPrimitive$1(normalized) ? normalized : type;
}
function normalizeValue(value, key) {
  if (key === "domain" && value && typeof value === "object" && value._events) {
    return "[Domain]";
  }
  if (key === "domainEmitter") {
    return "[DomainEmitter]";
  }
  if (typeof global !== "undefined" && value === global) {
    return "[Global]";
  }
  if (typeof window !== "undefined" && value === window) {
    return "[Window]";
  }
  if (typeof document !== "undefined" && value === document) {
    return "[Document]";
  }
  if (isSyntheticEvent(value)) {
    return "[SyntheticEvent]";
  }
  if (typeof value === "number" && value !== value) {
    return "[NaN]";
  }
  if (value === void 0) {
    return "[undefined]";
  }
  if (typeof value === "function") {
    return "[Function: " + getFunctionName(value) + "]";
  }
  if (typeof value === "symbol") {
    return "[" + String(value) + "]";
  }
  if (typeof value === "bigint") {
    return "[BigInt: " + String(value) + "]";
  }
  return value;
}
function walk(key, value, depth, memo) {
  if (depth === void 0) {
    depth = Infinity;
  }
  if (memo === void 0) {
    memo = memoBuilder();
  }
  if (depth === 0) {
    return serializeValue(value);
  }
  if (value !== null && value !== void 0 && typeof value.toJSON === "function") {
    return value.toJSON();
  }
  var normalized = normalizeValue(value, key);
  if (isPrimitive$1(normalized)) {
    return normalized;
  }
  var source = getWalkSource(value);
  var acc = Array.isArray(value) ? [] : {};
  if (memo[0](value)) {
    return "[Circular ~]";
  }
  for (var innerKey in source) {
    if (!Object.prototype.hasOwnProperty.call(source, innerKey)) {
      continue;
    }
    acc[innerKey] = walk(innerKey, source[innerKey], depth - 1, memo);
  }
  memo[1](value);
  return acc;
}
function normalize(input, depth) {
  try {
    return JSON.parse(JSON.stringify(input, function(key, value) {
      return walk(key, value, depth);
    }));
  } catch (_oO) {
    return "**non-serializable**";
  }
}
function extractExceptionKeysForMessage(exception, maxLength) {
  if (maxLength === void 0) {
    maxLength = 40;
  }
  var keys = Object.keys(getWalkSource(exception));
  keys.sort();
  if (!keys.length) {
    return "[object has no keys]";
  }
  if (keys[0].length >= maxLength) {
    return truncate(keys[0], maxLength);
  }
  for (var includedKeys = keys.length; includedKeys > 0; includedKeys--) {
    var serialized = keys.slice(0, includedKeys).join(", ");
    if (serialized.length > maxLength) {
      continue;
    }
    if (includedKeys === keys.length) {
      return serialized;
    }
    return truncate(serialized, maxLength);
  }
  return "";
}
function dropUndefinedKeys(val) {
  var e_1, _a2;
  if (isPlainObject(val)) {
    var obj = val;
    var rv = {};
    try {
      for (var _b = __values$3(Object.keys(obj)), _c = _b.next(); !_c.done; _c = _b.next()) {
        var key = _c.value;
        if (typeof obj[key] !== "undefined") {
          rv[key] = dropUndefinedKeys(obj[key]);
        }
      }
    } catch (e_1_1) {
      e_1 = { error: e_1_1 };
    } finally {
      try {
        if (_c && !_c.done && (_a2 = _b.return))
          _a2.call(_b);
      } finally {
        if (e_1)
          throw e_1.error;
      }
    }
    return rv;
  }
  if (Array.isArray(val)) {
    return val.map(dropUndefinedKeys);
  }
  return val;
}
function supportsFetch() {
  if (!("fetch" in getGlobalObject())) {
    return false;
  }
  try {
    new Headers();
    new Request("");
    new Response();
    return true;
  } catch (e2) {
    return false;
  }
}
function isNativeFetch(func) {
  return func && /^function fetch\(\)\s+\{\s+\[native code\]\s+\}$/.test(func.toString());
}
function supportsNativeFetch() {
  if (!supportsFetch()) {
    return false;
  }
  var global2 = getGlobalObject();
  if (isNativeFetch(global2.fetch)) {
    return true;
  }
  var result = false;
  var doc = global2.document;
  if (doc && typeof doc.createElement === "function") {
    try {
      var sandbox = doc.createElement("iframe");
      sandbox.hidden = true;
      doc.head.appendChild(sandbox);
      if (sandbox.contentWindow && sandbox.contentWindow.fetch) {
        result = isNativeFetch(sandbox.contentWindow.fetch);
      }
      doc.head.removeChild(sandbox);
    } catch (err) {
      if (isDebugBuild()) {
        logger.warn("Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ", err);
      }
    }
  }
  return result;
}
function supportsReferrerPolicy() {
  if (!supportsFetch()) {
    return false;
  }
  try {
    new Request("_", {
      referrerPolicy: "origin"
    });
    return true;
  } catch (e2) {
    return false;
  }
}
function supportsHistory() {
  var global2 = getGlobalObject();
  var chrome2 = global2.chrome;
  var isChromePackagedApp = chrome2 && chrome2.app && chrome2.app.runtime;
  var hasHistoryApi = "history" in global2 && !!global2.history.pushState && !!global2.history.replaceState;
  return !isChromePackagedApp && hasHistoryApi;
}
var global$8 = getGlobalObject();
var handlers = {};
var instrumented = {};
function instrument(type) {
  if (instrumented[type]) {
    return;
  }
  instrumented[type] = true;
  switch (type) {
    case "console":
      instrumentConsole();
      break;
    case "dom":
      instrumentDOM();
      break;
    case "xhr":
      instrumentXHR();
      break;
    case "fetch":
      instrumentFetch();
      break;
    case "history":
      instrumentHistory();
      break;
    case "error":
      instrumentError();
      break;
    case "unhandledrejection":
      instrumentUnhandledRejection();
      break;
    default:
      logger.warn("unknown instrumentation type:", type);
  }
}
function addInstrumentationHandler(type, callback) {
  handlers[type] = handlers[type] || [];
  handlers[type].push(callback);
  instrument(type);
}
function triggerHandlers(type, data) {
  var e_1, _a2;
  if (!type || !handlers[type]) {
    return;
  }
  try {
    for (var _b = __values$3(handlers[type] || []), _c = _b.next(); !_c.done; _c = _b.next()) {
      var handler = _c.value;
      try {
        handler(data);
      } catch (e2) {
        if (isDebugBuild()) {
          logger.error("Error while triggering instrumentation handler.\nType: " + type + "\nName: " + getFunctionName(handler) + "\nError: " + e2);
        }
      }
    }
  } catch (e_1_1) {
    e_1 = { error: e_1_1 };
  } finally {
    try {
      if (_c && !_c.done && (_a2 = _b.return))
        _a2.call(_b);
    } finally {
      if (e_1)
        throw e_1.error;
    }
  }
}
function instrumentConsole() {
  if (!("console" in global$8)) {
    return;
  }
  ["debug", "info", "warn", "error", "log", "assert"].forEach(function(level) {
    if (!(level in global$8.console)) {
      return;
    }
    fill(global$8.console, level, function(originalConsoleMethod) {
      return function() {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
          args[_i] = arguments[_i];
        }
        triggerHandlers("console", { args, level });
        if (originalConsoleMethod) {
          originalConsoleMethod.apply(global$8.console, args);
        }
      };
    });
  });
}
function instrumentFetch() {
  if (!supportsNativeFetch()) {
    return;
  }
  fill(global$8, "fetch", function(originalFetch) {
    return function() {
      var args = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
      }
      var handlerData = {
        args,
        fetchData: {
          method: getFetchMethod(args),
          url: getFetchUrl(args)
        },
        startTimestamp: Date.now()
      };
      triggerHandlers("fetch", __assign$3({}, handlerData));
      return originalFetch.apply(global$8, args).then(function(response) {
        triggerHandlers("fetch", __assign$3(__assign$3({}, handlerData), { endTimestamp: Date.now(), response }));
        return response;
      }, function(error) {
        triggerHandlers("fetch", __assign$3(__assign$3({}, handlerData), { endTimestamp: Date.now(), error }));
        throw error;
      });
    };
  });
}
function getFetchMethod(fetchArgs) {
  if (fetchArgs === void 0) {
    fetchArgs = [];
  }
  if ("Request" in global$8 && isInstanceOf(fetchArgs[0], Request) && fetchArgs[0].method) {
    return String(fetchArgs[0].method).toUpperCase();
  }
  if (fetchArgs[1] && fetchArgs[1].method) {
    return String(fetchArgs[1].method).toUpperCase();
  }
  return "GET";
}
function getFetchUrl(fetchArgs) {
  if (fetchArgs === void 0) {
    fetchArgs = [];
  }
  if (typeof fetchArgs[0] === "string") {
    return fetchArgs[0];
  }
  if ("Request" in global$8 && isInstanceOf(fetchArgs[0], Request)) {
    return fetchArgs[0].url;
  }
  return String(fetchArgs[0]);
}
function instrumentXHR() {
  if (!("XMLHttpRequest" in global$8)) {
    return;
  }
  var xhrproto = XMLHttpRequest.prototype;
  fill(xhrproto, "open", function(originalOpen) {
    return function() {
      var args = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
      }
      var xhr = this;
      var url = args[1];
      var xhrInfo = xhr.__sentry_xhr__ = {
        method: isString$1(args[0]) ? args[0].toUpperCase() : args[0],
        url: args[1]
      };
      if (isString$1(url) && xhrInfo.method === "POST" && url.match(/sentry_key/)) {
        xhr.__sentry_own_request__ = true;
      }
      var onreadystatechangeHandler = function() {
        if (xhr.readyState === 4) {
          try {
            xhrInfo.status_code = xhr.status;
          } catch (e2) {
          }
          triggerHandlers("xhr", {
            args,
            endTimestamp: Date.now(),
            startTimestamp: Date.now(),
            xhr
          });
        }
      };
      if ("onreadystatechange" in xhr && typeof xhr.onreadystatechange === "function") {
        fill(xhr, "onreadystatechange", function(original) {
          return function() {
            var readyStateArgs = [];
            for (var _i2 = 0; _i2 < arguments.length; _i2++) {
              readyStateArgs[_i2] = arguments[_i2];
            }
            onreadystatechangeHandler();
            return original.apply(xhr, readyStateArgs);
          };
        });
      } else {
        xhr.addEventListener("readystatechange", onreadystatechangeHandler);
      }
      return originalOpen.apply(xhr, args);
    };
  });
  fill(xhrproto, "send", function(originalSend) {
    return function() {
      var args = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
      }
      if (this.__sentry_xhr__ && args[0] !== void 0) {
        this.__sentry_xhr__.body = args[0];
      }
      triggerHandlers("xhr", {
        args,
        startTimestamp: Date.now(),
        xhr: this
      });
      return originalSend.apply(this, args);
    };
  });
}
var lastHref;
function instrumentHistory() {
  if (!supportsHistory()) {
    return;
  }
  var oldOnPopState = global$8.onpopstate;
  global$8.onpopstate = function() {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
      args[_i] = arguments[_i];
    }
    var to = global$8.location.href;
    var from = lastHref;
    lastHref = to;
    triggerHandlers("history", {
      from,
      to
    });
    if (oldOnPopState) {
      try {
        return oldOnPopState.apply(this, args);
      } catch (_oO) {
      }
    }
  };
  function historyReplacementFunction(originalHistoryFunction) {
    return function() {
      var args = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
      }
      var url = args.length > 2 ? args[2] : void 0;
      if (url) {
        var from = lastHref;
        var to = String(url);
        lastHref = to;
        triggerHandlers("history", {
          from,
          to
        });
      }
      return originalHistoryFunction.apply(this, args);
    };
  }
  fill(global$8.history, "pushState", historyReplacementFunction);
  fill(global$8.history, "replaceState", historyReplacementFunction);
}
var debounceDuration = 1e3;
var debounceTimerID;
var lastCapturedEvent;
function shouldShortcircuitPreviousDebounce(previous, current) {
  if (!previous) {
    return true;
  }
  if (previous.type !== current.type) {
    return true;
  }
  try {
    if (previous.target !== current.target) {
      return true;
    }
  } catch (e2) {
  }
  return false;
}
function shouldSkipDOMEvent(event) {
  if (event.type !== "keypress") {
    return false;
  }
  try {
    var target = event.target;
    if (!target || !target.tagName) {
      return true;
    }
    if (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable) {
      return false;
    }
  } catch (e2) {
  }
  return true;
}
function makeDOMEventHandler(handler, globalListener) {
  if (globalListener === void 0) {
    globalListener = false;
  }
  return function(event) {
    if (!event || lastCapturedEvent === event) {
      return;
    }
    if (shouldSkipDOMEvent(event)) {
      return;
    }
    var name = event.type === "keypress" ? "input" : event.type;
    if (debounceTimerID === void 0) {
      handler({
        event,
        name,
        global: globalListener
      });
      lastCapturedEvent = event;
    } else if (shouldShortcircuitPreviousDebounce(lastCapturedEvent, event)) {
      handler({
        event,
        name,
        global: globalListener
      });
      lastCapturedEvent = event;
    }
    clearTimeout(debounceTimerID);
    debounceTimerID = global$8.setTimeout(function() {
      debounceTimerID = void 0;
    }, debounceDuration);
  };
}
function instrumentDOM() {
  if (!("document" in global$8)) {
    return;
  }
  var triggerDOMHandler = triggerHandlers.bind(null, "dom");
  var globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true);
  global$8.document.addEventListener("click", globalDOMEventHandler, false);
  global$8.document.addEventListener("keypress", globalDOMEventHandler, false);
  ["EventTarget", "Node"].forEach(function(target) {
    var proto = global$8[target] && global$8[target].prototype;
    if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty("addEventListener")) {
      return;
    }
    fill(proto, "addEventListener", function(originalAddEventListener) {
      return function(type, listener, options) {
        if (type === "click" || type == "keypress") {
          try {
            var el = this;
            var handlers_1 = el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {};
            var handlerForType = handlers_1[type] = handlers_1[type] || { refCount: 0 };
            if (!handlerForType.handler) {
              var handler = makeDOMEventHandler(triggerDOMHandler);
              handlerForType.handler = handler;
              originalAddEventListener.call(this, type, handler, options);
            }
            handlerForType.refCount += 1;
          } catch (e2) {
          }
        }
        return originalAddEventListener.call(this, type, listener, options);
      };
    });
    fill(proto, "removeEventListener", function(originalRemoveEventListener) {
      return function(type, listener, options) {
        if (type === "click" || type == "keypress") {
          try {
            var el = this;
            var handlers_2 = el.__sentry_instrumentation_handlers__ || {};
            var handlerForType = handlers_2[type];
            if (handlerForType) {
              handlerForType.refCount -= 1;
              if (handlerForType.refCount <= 0) {
                originalRemoveEventListener.call(this, type, handlerForType.handler, options);
                handlerForType.handler = void 0;
                delete handlers_2[type];
              }
              if (Object.keys(handlers_2).length === 0) {
                delete el.__sentry_instrumentation_handlers__;
              }
            }
          } catch (e2) {
          }
        }
        return originalRemoveEventListener.call(this, type, listener, options);
      };
    });
  });
}
var _oldOnErrorHandler = null;
function instrumentError() {
  _oldOnErrorHandler = global$8.onerror;
  global$8.onerror = function(msg, url, line, column, error) {
    triggerHandlers("error", {
      column,
      error,
      line,
      msg,
      url
    });
    if (_oldOnErrorHandler) {
      return _oldOnErrorHandler.apply(this, arguments);
    }
    return false;
  };
}
var _oldOnUnhandledRejectionHandler = null;
function instrumentUnhandledRejection() {
  _oldOnUnhandledRejectionHandler = global$8.onunhandledrejection;
  global$8.onunhandledrejection = function(e2) {
    triggerHandlers("unhandledrejection", e2);
    if (_oldOnUnhandledRejectionHandler) {
      return _oldOnUnhandledRejectionHandler.apply(this, arguments);
    }
    return true;
  };
}
function uuid4() {
  var global2 = getGlobalObject();
  var crypto = global2.crypto || global2.msCrypto;
  if (!(crypto === void 0) && crypto.getRandomValues) {
    var arr = new Uint16Array(8);
    crypto.getRandomValues(arr);
    arr[3] = arr[3] & 4095 | 16384;
    arr[4] = arr[4] & 16383 | 32768;
    var pad = function(num) {
      var v2 = num.toString(16);
      while (v2.length < 4) {
        v2 = "0" + v2;
      }
      return v2;
    };
    return pad(arr[0]) + pad(arr[1]) + pad(arr[2]) + pad(arr[3]) + pad(arr[4]) + pad(arr[5]) + pad(arr[6]) + pad(arr[7]);
  }
  return "xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g, function(c2) {
    var r2 = Math.random() * 16 | 0;
    var v2 = c2 === "x" ? r2 : r2 & 3 | 8;
    return v2.toString(16);
  });
}
function parseUrl(url) {
  if (!url) {
    return {};
  }
  var match = url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);
  if (!match) {
    return {};
  }
  var query = match[6] || "";
  var fragment = match[8] || "";
  return {
    host: match[4],
    path: match[5],
    protocol: match[2],
    relative: match[5] + query + fragment
  };
}
function getFirstException(event) {
  return event.exception && event.exception.values ? event.exception.values[0] : void 0;
}
function getEventDescription(event) {
  var message = event.message, eventId = event.event_id;
  if (message) {
    return message;
  }
  var firstException = getFirstException(event);
  if (firstException) {
    if (firstException.type && firstException.value) {
      return firstException.type + ": " + firstException.value;
    }
    return firstException.type || firstException.value || eventId || "<unknown>";
  }
  return eventId || "<unknown>";
}
function addExceptionTypeValue(event, value, type) {
  var exception = event.exception = event.exception || {};
  var values = exception.values = exception.values || [];
  var firstException = values[0] = values[0] || {};
  if (!firstException.value) {
    firstException.value = value || "";
  }
  if (!firstException.type) {
    firstException.type = type || "Error";
  }
}
function addExceptionMechanism(event, newMechanism) {
  var firstException = getFirstException(event);
  if (!firstException) {
    return;
  }
  var defaultMechanism = { type: "generic", handled: true };
  var currentMechanism = firstException.mechanism;
  firstException.mechanism = __assign$3(__assign$3(__assign$3({}, defaultMechanism), currentMechanism), newMechanism);
  if (newMechanism && "data" in newMechanism) {
    var mergedData = __assign$3(__assign$3({}, currentMechanism && currentMechanism.data), newMechanism.data);
    firstException.mechanism.data = mergedData;
  }
}
var defaultRetryAfter = 60 * 1e3;
function parseRetryAfterHeader(now2, header) {
  if (!header) {
    return defaultRetryAfter;
  }
  var headerDelay = parseInt("" + header, 10);
  if (!isNaN(headerDelay)) {
    return headerDelay * 1e3;
  }
  var headerDate = Date.parse("" + header);
  if (!isNaN(headerDate)) {
    return headerDate - now2;
  }
  return defaultRetryAfter;
}
function checkOrSetAlreadyCaught(exception) {
  if (exception && exception.__sentry_captured__) {
    return true;
  }
  try {
    addNonEnumerableProperty(exception, "__sentry_captured__", true);
  } catch (err) {
  }
  return false;
}
function resolvedSyncPromise(value) {
  return new SyncPromise(function(resolve) {
    resolve(value);
  });
}
function rejectedSyncPromise(reason) {
  return new SyncPromise(function(_2, reject) {
    reject(reason);
  });
}
var SyncPromise = function() {
  function SyncPromise2(executor) {
    var _this = this;
    this._state = 0;
    this._handlers = [];
    this._resolve = function(value) {
      _this._setResult(1, value);
    };
    this._reject = function(reason) {
      _this._setResult(2, reason);
    };
    this._setResult = function(state2, value) {
      if (_this._state !== 0) {
        return;
      }
      if (isThenable(value)) {
        void value.then(_this._resolve, _this._reject);
        return;
      }
      _this._state = state2;
      _this._value = value;
      _this._executeHandlers();
    };
    this._executeHandlers = function() {
      if (_this._state === 0) {
        return;
      }
      var cachedHandlers = _this._handlers.slice();
      _this._handlers = [];
      cachedHandlers.forEach(function(handler) {
        if (handler[0]) {
          return;
        }
        if (_this._state === 1) {
          handler[1](_this._value);
        }
        if (_this._state === 2) {
          handler[2](_this._value);
        }
        handler[0] = true;
      });
    };
    try {
      executor(this._resolve, this._reject);
    } catch (e2) {
      this._reject(e2);
    }
  }
  SyncPromise2.prototype.then = function(onfulfilled, onrejected) {
    var _this = this;
    return new SyncPromise2(function(resolve, reject) {
      _this._handlers.push([
        false,
        function(result) {
          if (!onfulfilled) {
            resolve(result);
          } else {
            try {
              resolve(onfulfilled(result));
            } catch (e2) {
              reject(e2);
            }
          }
        },
        function(reason) {
          if (!onrejected) {
            reject(reason);
          } else {
            try {
              resolve(onrejected(reason));
            } catch (e2) {
              reject(e2);
            }
          }
        }
      ]);
      _this._executeHandlers();
    });
  };
  SyncPromise2.prototype.catch = function(onrejected) {
    return this.then(function(val) {
      return val;
    }, onrejected);
  };
  SyncPromise2.prototype.finally = function(onfinally) {
    var _this = this;
    return new SyncPromise2(function(resolve, reject) {
      var val;
      var isRejected;
      return _this.then(function(value) {
        isRejected = false;
        val = value;
        if (onfinally) {
          onfinally();
        }
      }, function(reason) {
        isRejected = true;
        val = reason;
        if (onfinally) {
          onfinally();
        }
      }).then(function() {
        if (isRejected) {
          reject(val);
          return;
        }
        resolve(val);
      });
    });
  };
  return SyncPromise2;
}();
function makePromiseBuffer(limit) {
  var buffer = [];
  function isReady() {
    return limit === void 0 || buffer.length < limit;
  }
  function remove(task) {
    return buffer.splice(buffer.indexOf(task), 1)[0];
  }
  function add(taskProducer) {
    if (!isReady()) {
      return rejectedSyncPromise(new SentryError("Not adding Promise due to buffer limit reached."));
    }
    var task = taskProducer();
    if (buffer.indexOf(task) === -1) {
      buffer.push(task);
    }
    void task.then(function() {
      return remove(task);
    }).then(null, function() {
      return remove(task).then(null, function() {
      });
    });
    return task;
  }
  function drain(timeout) {
    return new SyncPromise(function(resolve, reject) {
      var counter2 = buffer.length;
      if (!counter2) {
        return resolve(true);
      }
      var capturedSetTimeout = setTimeout(function() {
        if (timeout && timeout > 0) {
          resolve(false);
        }
      }, timeout);
      buffer.forEach(function(item) {
        void resolvedSyncPromise(item).then(function() {
          if (!--counter2) {
            clearTimeout(capturedSetTimeout);
            resolve(true);
          }
        }, reject);
      });
    });
  }
  return {
    $: buffer,
    add,
    drain
  };
}
function isSupportedSeverity(level) {
  return SeverityLevels.indexOf(level) !== -1;
}
function severityFromString(level) {
  if (level === "warn")
    return Severity.Warning;
  if (isSupportedSeverity(level)) {
    return level;
  }
  return Severity.Log;
}
function eventStatusFromHttpCode(code) {
  if (code >= 200 && code < 300) {
    return "success";
  }
  if (code === 429) {
    return "rate_limit";
  }
  if (code >= 400 && code < 500) {
    return "invalid";
  }
  if (code >= 500) {
    return "failed";
  }
  return "unknown";
}
var dateTimestampSource = {
  nowSeconds: function() {
    return Date.now() / 1e3;
  }
};
function getBrowserPerformance() {
  var performance2 = getGlobalObject().performance;
  if (!performance2 || !performance2.now) {
    return void 0;
  }
  var timeOrigin = Date.now() - performance2.now();
  return {
    now: function() {
      return performance2.now();
    },
    timeOrigin
  };
}
function getNodePerformance() {
  try {
    var perfHooks = dynamicRequire(module, "perf_hooks");
    return perfHooks.performance;
  } catch (_2) {
    return void 0;
  }
}
var platformPerformance = isNodeEnv() ? getNodePerformance() : getBrowserPerformance();
var timestampSource = platformPerformance === void 0 ? dateTimestampSource : {
  nowSeconds: function() {
    return (platformPerformance.timeOrigin + platformPerformance.now()) / 1e3;
  }
};
var dateTimestampInSeconds = dateTimestampSource.nowSeconds.bind(dateTimestampSource);
var timestampInSeconds = timestampSource.nowSeconds.bind(timestampSource);
var timestampWithMs = timestampInSeconds;
var browserPerformanceTimeOrigin = function() {
  var performance2 = getGlobalObject().performance;
  if (!performance2 || !performance2.now) {
    return void 0;
  }
  var threshold = 3600 * 1e3;
  var performanceNow = performance2.now();
  var dateNow = Date.now();
  var timeOriginDelta = performance2.timeOrigin ? Math.abs(performance2.timeOrigin + performanceNow - dateNow) : threshold;
  var timeOriginIsReliable = timeOriginDelta < threshold;
  var navigationStart = performance2.timing && performance2.timing.navigationStart;
  var hasNavigationStart = typeof navigationStart === "number";
  var navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold;
  var navigationStartIsReliable = navigationStartDelta < threshold;
  if (timeOriginIsReliable || navigationStartIsReliable) {
    if (timeOriginDelta <= navigationStartDelta) {
      return performance2.timeOrigin;
    } else {
      return navigationStart;
    }
  }
  return dateNow;
}();
var MAX_BREADCRUMBS = 100;
var Scope = function() {
  function Scope2() {
    this._notifyingListeners = false;
    this._scopeListeners = [];
    this._eventProcessors = [];
    this._breadcrumbs = [];
    this._user = {};
    this._tags = {};
    this._extra = {};
    this._contexts = {};
    this._sdkProcessingMetadata = {};
  }
  Scope2.clone = function(scope) {
    var newScope = new Scope2();
    if (scope) {
      newScope._breadcrumbs = __spread$3(scope._breadcrumbs);
      newScope._tags = __assign$4({}, scope._tags);
      newScope._extra = __assign$4({}, scope._extra);
      newScope._contexts = __assign$4({}, scope._contexts);
      newScope._user = scope._user;
      newScope._level = scope._level;
      newScope._span = scope._span;
      newScope._session = scope._session;
      newScope._transactionName = scope._transactionName;
      newScope._fingerprint = scope._fingerprint;
      newScope._eventProcessors = __spread$3(scope._eventProcessors);
      newScope._requestSession = scope._requestSession;
    }
    return newScope;
  };
  Scope2.prototype.addScopeListener = function(callback) {
    this._scopeListeners.push(callback);
  };
  Scope2.prototype.addEventProcessor = function(callback) {
    this._eventProcessors.push(callback);
    return this;
  };
  Scope2.prototype.setUser = function(user) {
    this._user = user || {};
    if (this._session) {
      this._session.update({ user });
    }
    this._notifyScopeListeners();
    return this;
  };
  Scope2.prototype.getUser = function() {
    return this._user;
  };
  Scope2.prototype.getRequestSession = function() {
    return this._requestSession;
  };
  Scope2.prototype.setRequestSession = function(requestSession) {
    this._requestSession = requestSession;
    return this;
  };
  Scope2.prototype.setTags = function(tags) {
    this._tags = __assign$4(__assign$4({}, this._tags), tags);
    this._notifyScopeListeners();
    return this;
  };
  Scope2.prototype.setTag = function(key, value) {
    var _a2;
    this._tags = __assign$4(__assign$4({}, this._tags), (_a2 = {}, _a2[key] = value, _a2));
    this._notifyScopeListeners();
    return this;
  };
  Scope2.prototype.setExtras = function(extras) {
    this._extra = __assign$4(__assign$4({}, this._extra), extras);
    this._notifyScopeListeners();
    return this;
  };
  Scope2.prototype.setExtra = function(key, extra) {
    var _a2;
    this._extra = __assign$4(__assign$4({}, this._extra), (_a2 = {}, _a2[key] = extra, _a2));
    this._notifyScopeListeners();
    return this;
  };
  Scope2.prototype.setFingerprint = function(fingerprint) {
    this._fingerprint = fingerprint;
    this._notifyScopeListeners();
    return this;
  };
  Scope2.prototype.setLevel = function(level) {
    this._level = level;
    this._notifyScopeListeners();
    return this;
  };
  Scope2.prototype.setTransactionName = function(name) {
    this._transactionName = name;
    this._notifyScopeListeners();
    return this;
  };
  Scope2.prototype.setTransaction = function(name) {
    return this.setTransactionName(name);
  };
  Scope2.prototype.setContext = function(key, context) {
    var _a2;
    if (context === null) {
      delete this._contexts[key];
    } else {
      this._contexts = __assign$4(__assign$4({}, this._contexts), (_a2 = {}, _a2[key] = context, _a2));
    }
    this._notifyScopeListeners();
    return this;
  };
  Scope2.prototype.setSpan = function(span) {
    this._span = span;
    this._notifyScopeListeners();
    return this;
  };
  Scope2.prototype.getSpan = function() {
    return this._span;
  };
  Scope2.prototype.getTransaction = function() {
    var span = this.getSpan();
    return span && span.transaction;
  };
  Scope2.prototype.setSession = function(session) {
    if (!session) {
      delete this._session;
    } else {
      this._session = session;
    }
    this._notifyScopeListeners();
    return this;
  };
  Scope2.prototype.getSession = function() {
    return this._session;
  };
  Scope2.prototype.update = function(captureContext) {
    if (!captureContext) {
      return this;
    }
    if (typeof captureContext === "function") {
      var updatedScope = captureContext(this);
      return updatedScope instanceof Scope2 ? updatedScope : this;
    }
    if (captureContext instanceof Scope2) {
      this._tags = __assign$4(__assign$4({}, this._tags), captureContext._tags);
      this._extra = __assign$4(__assign$4({}, this._extra), captureContext._extra);
      this._contexts = __assign$4(__assign$4({}, this._contexts), captureContext._contexts);
      if (captureContext._user && Object.keys(captureContext._user).length) {
        this._user = captureContext._user;
      }
      if (captureContext._level) {
        this._level = captureContext._level;
      }
      if (captureContext._fingerprint) {
        this._fingerprint = captureContext._fingerprint;
      }
      if (captureContext._requestSession) {
        this._requestSession = captureContext._requestSession;
      }
    } else if (isPlainObject(captureContext)) {
      captureContext = captureContext;
      this._tags = __assign$4(__assign$4({}, this._tags), captureContext.tags);
      this._extra = __assign$4(__assign$4({}, this._extra), captureContext.extra);
      this._contexts = __assign$4(__assign$4({}, this._contexts), captureContext.contexts);
      if (captureContext.user) {
        this._user = captureContext.user;
      }
      if (captureContext.level) {
        this._level = captureContext.level;
      }
      if (captureContext.fingerprint) {
        this._fingerprint = captureContext.fingerprint;
      }
      if (captureContext.requestSession) {
        this._requestSession = captureContext.requestSession;
      }
    }
    return this;
  };
  Scope2.prototype.clear = function() {
    this._breadcrumbs = [];
    this._tags = {};
    this._extra = {};
    this._user = {};
    this._contexts = {};
    this._level = void 0;
    this._transactionName = void 0;
    this._fingerprint = void 0;
    this._requestSession = void 0;
    this._span = void 0;
    this._session = void 0;
    this._notifyScopeListeners();
    return this;
  };
  Scope2.prototype.addBreadcrumb = function(breadcrumb, maxBreadcrumbs) {
    var maxCrumbs = typeof maxBreadcrumbs === "number" ? Math.min(maxBreadcrumbs, MAX_BREADCRUMBS) : MAX_BREADCRUMBS;
    if (maxCrumbs <= 0) {
      return this;
    }
    var mergedBreadcrumb = __assign$4({ timestamp: dateTimestampInSeconds() }, breadcrumb);
    this._breadcrumbs = __spread$3(this._breadcrumbs, [mergedBreadcrumb]).slice(-maxCrumbs);
    this._notifyScopeListeners();
    return this;
  };
  Scope2.prototype.clearBreadcrumbs = function() {
    this._breadcrumbs = [];
    this._notifyScopeListeners();
    return this;
  };
  Scope2.prototype.applyToEvent = function(event, hint) {
    if (this._extra && Object.keys(this._extra).length) {
      event.extra = __assign$4(__assign$4({}, this._extra), event.extra);
    }
    if (this._tags && Object.keys(this._tags).length) {
      event.tags = __assign$4(__assign$4({}, this._tags), event.tags);
    }
    if (this._user && Object.keys(this._user).length) {
      event.user = __assign$4(__assign$4({}, this._user), event.user);
    }
    if (this._contexts && Object.keys(this._contexts).length) {
      event.contexts = __assign$4(__assign$4({}, this._contexts), event.contexts);
    }
    if (this._level) {
      event.level = this._level;
    }
    if (this._transactionName) {
      event.transaction = this._transactionName;
    }
    if (this._span) {
      event.contexts = __assign$4({ trace: this._span.getTraceContext() }, event.contexts);
      var transactionName = this._span.transaction && this._span.transaction.name;
      if (transactionName) {
        event.tags = __assign$4({ transaction: transactionName }, event.tags);
      }
    }
    this._applyFingerprint(event);
    event.breadcrumbs = __spread$3(event.breadcrumbs || [], this._breadcrumbs);
    event.breadcrumbs = event.breadcrumbs.length > 0 ? event.breadcrumbs : void 0;
    event.sdkProcessingMetadata = this._sdkProcessingMetadata;
    return this._notifyEventProcessors(__spread$3(getGlobalEventProcessors(), this._eventProcessors), event, hint);
  };
  Scope2.prototype.setSDKProcessingMetadata = function(newData) {
    this._sdkProcessingMetadata = __assign$4(__assign$4({}, this._sdkProcessingMetadata), newData);
    return this;
  };
  Scope2.prototype._notifyEventProcessors = function(processors, event, hint, index2) {
    var _this = this;
    if (index2 === void 0) {
      index2 = 0;
    }
    return new SyncPromise(function(resolve, reject) {
      var processor = processors[index2];
      if (event === null || typeof processor !== "function") {
        resolve(event);
      } else {
        var result = processor(__assign$4({}, event), hint);
        if (isThenable(result)) {
          void result.then(function(final) {
            return _this._notifyEventProcessors(processors, final, hint, index2 + 1).then(resolve);
          }).then(null, reject);
        } else {
          void _this._notifyEventProcessors(processors, result, hint, index2 + 1).then(resolve).then(null, reject);
        }
      }
    });
  };
  Scope2.prototype._notifyScopeListeners = function() {
    var _this = this;
    if (!this._notifyingListeners) {
      this._notifyingListeners = true;
      this._scopeListeners.forEach(function(callback) {
        callback(_this);
      });
      this._notifyingListeners = false;
    }
  };
  Scope2.prototype._applyFingerprint = function(event) {
    event.fingerprint = event.fingerprint ? Array.isArray(event.fingerprint) ? event.fingerprint : [event.fingerprint] : [];
    if (this._fingerprint) {
      event.fingerprint = event.fingerprint.concat(this._fingerprint);
    }
    if (event.fingerprint && !event.fingerprint.length) {
      delete event.fingerprint;
    }
  };
  return Scope2;
}();
function getGlobalEventProcessors() {
  var global2 = getGlobalObject();
  global2.__SENTRY__ = global2.__SENTRY__ || {};
  global2.__SENTRY__.globalEventProcessors = global2.__SENTRY__.globalEventProcessors || [];
  return global2.__SENTRY__.globalEventProcessors;
}
function addGlobalEventProcessor(callback) {
  getGlobalEventProcessors().push(callback);
}
var Session = function() {
  function Session2(context) {
    this.errors = 0;
    this.sid = uuid4();
    this.duration = 0;
    this.status = "ok";
    this.init = true;
    this.ignoreDuration = false;
    var startingTime = timestampInSeconds();
    this.timestamp = startingTime;
    this.started = startingTime;
    if (context) {
      this.update(context);
    }
  }
  Session2.prototype.update = function(context) {
    if (context === void 0) {
      context = {};
    }
    if (context.user) {
      if (!this.ipAddress && context.user.ip_address) {
        this.ipAddress = context.user.ip_address;
      }
      if (!this.did && !context.did) {
        this.did = context.user.id || context.user.email || context.user.username;
      }
    }
    this.timestamp = context.timestamp || timestampInSeconds();
    if (context.ignoreDuration) {
      this.ignoreDuration = context.ignoreDuration;
    }
    if (context.sid) {
      this.sid = context.sid.length === 32 ? context.sid : uuid4();
    }
    if (context.init !== void 0) {
      this.init = context.init;
    }
    if (!this.did && context.did) {
      this.did = "" + context.did;
    }
    if (typeof context.started === "number") {
      this.started = context.started;
    }
    if (this.ignoreDuration) {
      this.duration = void 0;
    } else if (typeof context.duration === "number") {
      this.duration = context.duration;
    } else {
      var duration = this.timestamp - this.started;
      this.duration = duration >= 0 ? duration : 0;
    }
    if (context.release) {
      this.release = context.release;
    }
    if (context.environment) {
      this.environment = context.environment;
    }
    if (!this.ipAddress && context.ipAddress) {
      this.ipAddress = context.ipAddress;
    }
    if (!this.userAgent && context.userAgent) {
      this.userAgent = context.userAgent;
    }
    if (typeof context.errors === "number") {
      this.errors = context.errors;
    }
    if (context.status) {
      this.status = context.status;
    }
  };
  Session2.prototype.close = function(status) {
    if (status) {
      this.update({ status });
    } else if (this.status === "ok") {
      this.update({ status: "exited" });
    } else {
      this.update();
    }
  };
  Session2.prototype.toJSON = function() {
    return dropUndefinedKeys({
      sid: "" + this.sid,
      init: this.init,
      started: new Date(this.started * 1e3).toISOString(),
      timestamp: new Date(this.timestamp * 1e3).toISOString(),
      status: this.status,
      errors: this.errors,
      did: typeof this.did === "number" || typeof this.did === "string" ? "" + this.did : void 0,
      duration: this.duration,
      attrs: {
        release: this.release,
        environment: this.environment,
        ip_address: this.ipAddress,
        user_agent: this.userAgent
      }
    });
  };
  return Session2;
}();
var API_VERSION = 4;
var DEFAULT_BREADCRUMBS = 100;
var Hub = function() {
  function Hub2(client, scope, _version) {
    if (scope === void 0) {
      scope = new Scope();
    }
    if (_version === void 0) {
      _version = API_VERSION;
    }
    this._version = _version;
    this._stack = [{}];
    this.getStackTop().scope = scope;
    if (client) {
      this.bindClient(client);
    }
  }
  Hub2.prototype.isOlderThan = function(version2) {
    return this._version < version2;
  };
  Hub2.prototype.bindClient = function(client) {
    var top = this.getStackTop();
    top.client = client;
    if (client && client.setupIntegrations) {
      client.setupIntegrations();
    }
  };
  Hub2.prototype.pushScope = function() {
    var scope = Scope.clone(this.getScope());
    this.getStack().push({
      client: this.getClient(),
      scope
    });
    return scope;
  };
  Hub2.prototype.popScope = function() {
    if (this.getStack().length <= 1)
      return false;
    return !!this.getStack().pop();
  };
  Hub2.prototype.withScope = function(callback) {
    var scope = this.pushScope();
    try {
      callback(scope);
    } finally {
      this.popScope();
    }
  };
  Hub2.prototype.getClient = function() {
    return this.getStackTop().client;
  };
  Hub2.prototype.getScope = function() {
    return this.getStackTop().scope;
  };
  Hub2.prototype.getStack = function() {
    return this._stack;
  };
  Hub2.prototype.getStackTop = function() {
    return this._stack[this._stack.length - 1];
  };
  Hub2.prototype.captureException = function(exception, hint) {
    var eventId = this._lastEventId = uuid4();
    var finalHint = hint;
    if (!hint) {
      var syntheticException = void 0;
      try {
        throw new Error("Sentry syntheticException");
      } catch (exception2) {
        syntheticException = exception2;
      }
      finalHint = {
        originalException: exception,
        syntheticException
      };
    }
    this._invokeClient("captureException", exception, __assign$4(__assign$4({}, finalHint), { event_id: eventId }));
    return eventId;
  };
  Hub2.prototype.captureMessage = function(message, level, hint) {
    var eventId = this._lastEventId = uuid4();
    var finalHint = hint;
    if (!hint) {
      var syntheticException = void 0;
      try {
        throw new Error(message);
      } catch (exception) {
        syntheticException = exception;
      }
      finalHint = {
        originalException: message,
        syntheticException
      };
    }
    this._invokeClient("captureMessage", message, level, __assign$4(__assign$4({}, finalHint), { event_id: eventId }));
    return eventId;
  };
  Hub2.prototype.captureEvent = function(event, hint) {
    var eventId = uuid4();
    if (event.type !== "transaction") {
      this._lastEventId = eventId;
    }
    this._invokeClient("captureEvent", event, __assign$4(__assign$4({}, hint), { event_id: eventId }));
    return eventId;
  };
  Hub2.prototype.lastEventId = function() {
    return this._lastEventId;
  };
  Hub2.prototype.addBreadcrumb = function(breadcrumb, hint) {
    var _a2 = this.getStackTop(), scope = _a2.scope, client = _a2.client;
    if (!scope || !client)
      return;
    var _b = client.getOptions && client.getOptions() || {}, _c = _b.beforeBreadcrumb, beforeBreadcrumb = _c === void 0 ? null : _c, _d = _b.maxBreadcrumbs, maxBreadcrumbs = _d === void 0 ? DEFAULT_BREADCRUMBS : _d;
    if (maxBreadcrumbs <= 0)
      return;
    var timestamp = dateTimestampInSeconds();
    var mergedBreadcrumb = __assign$4({ timestamp }, breadcrumb);
    var finalBreadcrumb = beforeBreadcrumb ? consoleSandbox(function() {
      return beforeBreadcrumb(mergedBreadcrumb, hint);
    }) : mergedBreadcrumb;
    if (finalBreadcrumb === null)
      return;
    scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);
  };
  Hub2.prototype.setUser = function(user) {
    var scope = this.getScope();
    if (scope)
      scope.setUser(user);
  };
  Hub2.prototype.setTags = function(tags) {
    var scope = this.getScope();
    if (scope)
      scope.setTags(tags);
  };
  Hub2.prototype.setExtras = function(extras) {
    var scope = this.getScope();
    if (scope)
      scope.setExtras(extras);
  };
  Hub2.prototype.setTag = function(key, value) {
    var scope = this.getScope();
    if (scope)
      scope.setTag(key, value);
  };
  Hub2.prototype.setExtra = function(key, extra) {
    var scope = this.getScope();
    if (scope)
      scope.setExtra(key, extra);
  };
  Hub2.prototype.setContext = function(name, context) {
    var scope = this.getScope();
    if (scope)
      scope.setContext(name, context);
  };
  Hub2.prototype.configureScope = function(callback) {
    var _a2 = this.getStackTop(), scope = _a2.scope, client = _a2.client;
    if (scope && client) {
      callback(scope);
    }
  };
  Hub2.prototype.run = function(callback) {
    var oldHub = makeMain(this);
    try {
      callback(this);
    } finally {
      makeMain(oldHub);
    }
  };
  Hub2.prototype.getIntegration = function(integration) {
    var client = this.getClient();
    if (!client)
      return null;
    try {
      return client.getIntegration(integration);
    } catch (_oO) {
      logger.warn("Cannot retrieve integration " + integration.id + " from the current Hub");
      return null;
    }
  };
  Hub2.prototype.startSpan = function(context) {
    return this._callExtensionMethod("startSpan", context);
  };
  Hub2.prototype.startTransaction = function(context, customSamplingContext) {
    return this._callExtensionMethod("startTransaction", context, customSamplingContext);
  };
  Hub2.prototype.traceHeaders = function() {
    return this._callExtensionMethod("traceHeaders");
  };
  Hub2.prototype.captureSession = function(endSession) {
    if (endSession === void 0) {
      endSession = false;
    }
    if (endSession) {
      return this.endSession();
    }
    this._sendSessionUpdate();
  };
  Hub2.prototype.endSession = function() {
    var layer = this.getStackTop();
    var scope = layer && layer.scope;
    var session = scope && scope.getSession();
    if (session) {
      session.close();
    }
    this._sendSessionUpdate();
    if (scope) {
      scope.setSession();
    }
  };
  Hub2.prototype.startSession = function(context) {
    var _a2 = this.getStackTop(), scope = _a2.scope, client = _a2.client;
    var _b = client && client.getOptions() || {}, release = _b.release, environment = _b.environment;
    var global2 = getGlobalObject();
    var userAgent = (global2.navigator || {}).userAgent;
    var session = new Session(__assign$4(__assign$4(__assign$4({
      release,
      environment
    }, scope && { user: scope.getUser() }), userAgent && { userAgent }), context));
    if (scope) {
      var currentSession = scope.getSession && scope.getSession();
      if (currentSession && currentSession.status === "ok") {
        currentSession.update({ status: "exited" });
      }
      this.endSession();
      scope.setSession(session);
    }
    return session;
  };
  Hub2.prototype._sendSessionUpdate = function() {
    var _a2 = this.getStackTop(), scope = _a2.scope, client = _a2.client;
    if (!scope)
      return;
    var session = scope.getSession && scope.getSession();
    if (session) {
      if (client && client.captureSession) {
        client.captureSession(session);
      }
    }
  };
  Hub2.prototype._invokeClient = function(method) {
    var _a2;
    var args = [];
    for (var _i = 1; _i < arguments.length; _i++) {
      args[_i - 1] = arguments[_i];
    }
    var _b = this.getStackTop(), scope = _b.scope, client = _b.client;
    if (client && client[method]) {
      (_a2 = client)[method].apply(_a2, __spread$3(args, [scope]));
    }
  };
  Hub2.prototype._callExtensionMethod = function(method) {
    var args = [];
    for (var _i = 1; _i < arguments.length; _i++) {
      args[_i - 1] = arguments[_i];
    }
    var carrier = getMainCarrier();
    var sentry = carrier.__SENTRY__;
    if (sentry && sentry.extensions && typeof sentry.extensions[method] === "function") {
      return sentry.extensions[method].apply(this, args);
    }
    logger.warn("Extension method " + method + " couldn't be found, doing nothing.");
  };
  return Hub2;
}();
function getMainCarrier() {
  var carrier = getGlobalObject();
  carrier.__SENTRY__ = carrier.__SENTRY__ || {
    extensions: {},
    hub: void 0
  };
  return carrier;
}
function makeMain(hub) {
  var registry = getMainCarrier();
  var oldHub = getHubFromCarrier(registry);
  setHubOnCarrier(registry, hub);
  return oldHub;
}
function getCurrentHub() {
  var registry = getMainCarrier();
  if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(API_VERSION)) {
    setHubOnCarrier(registry, new Hub());
  }
  if (isNodeEnv()) {
    return getHubFromActiveDomain(registry);
  }
  return getHubFromCarrier(registry);
}
function getHubFromActiveDomain(registry) {
  try {
    var sentry = getMainCarrier().__SENTRY__;
    var activeDomain = sentry && sentry.extensions && sentry.extensions.domain && sentry.extensions.domain.active;
    if (!activeDomain) {
      return getHubFromCarrier(registry);
    }
    if (!hasHubOnCarrier(activeDomain) || getHubFromCarrier(activeDomain).isOlderThan(API_VERSION)) {
      var registryHubTopStack = getHubFromCarrier(registry).getStackTop();
      setHubOnCarrier(activeDomain, new Hub(registryHubTopStack.client, Scope.clone(registryHubTopStack.scope)));
    }
    return getHubFromCarrier(activeDomain);
  } catch (_Oo) {
    return getHubFromCarrier(registry);
  }
}
function hasHubOnCarrier(carrier) {
  return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub);
}
function getHubFromCarrier(carrier) {
  if (carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub)
    return carrier.__SENTRY__.hub;
  carrier.__SENTRY__ = carrier.__SENTRY__ || {};
  carrier.__SENTRY__.hub = new Hub();
  return carrier.__SENTRY__.hub;
}
function setHubOnCarrier(carrier, hub) {
  if (!carrier)
    return false;
  carrier.__SENTRY__ = carrier.__SENTRY__ || {};
  carrier.__SENTRY__.hub = hub;
  return true;
}
function callOnHub(method) {
  var args = [];
  for (var _i = 1; _i < arguments.length; _i++) {
    args[_i - 1] = arguments[_i];
  }
  var hub = getCurrentHub();
  if (hub && hub[method]) {
    return hub[method].apply(hub, __spread$4(args));
  }
  throw new Error("No hub defined or " + method + " was not found on the hub, please open a bug report.");
}
function captureException(exception, captureContext) {
  var syntheticException;
  try {
    throw new Error("Sentry syntheticException");
  } catch (exception2) {
    syntheticException = exception2;
  }
  return callOnHub("captureException", exception, {
    captureContext,
    originalException: exception,
    syntheticException
  });
}
function withScope(callback) {
  callOnHub("withScope", callback);
}
var SENTRY_API_VERSION = "7";
function initAPIDetails(dsn, metadata, tunnel) {
  return {
    initDsn: dsn,
    metadata: metadata || {},
    dsn: makeDsn(dsn),
    tunnel
  };
}
function getBaseApiEndpoint(dsn) {
  var protocol = dsn.protocol ? dsn.protocol + ":" : "";
  var port = dsn.port ? ":" + dsn.port : "";
  return protocol + "//" + dsn.host + port + (dsn.path ? "/" + dsn.path : "") + "/api/";
}
function _getIngestEndpoint(dsn, target) {
  return "" + getBaseApiEndpoint(dsn) + dsn.projectId + "/" + target + "/";
}
function _encodedAuth(dsn) {
  return urlEncode({
    sentry_key: dsn.publicKey,
    sentry_version: SENTRY_API_VERSION
  });
}
function getStoreEndpoint(dsn) {
  return _getIngestEndpoint(dsn, "store");
}
function getStoreEndpointWithUrlEncodedAuth(dsn) {
  return getStoreEndpoint(dsn) + "?" + _encodedAuth(dsn);
}
function _getEnvelopeEndpoint(dsn) {
  return _getIngestEndpoint(dsn, "envelope");
}
function getEnvelopeEndpointWithUrlEncodedAuth(dsn, tunnel) {
  return tunnel ? tunnel : _getEnvelopeEndpoint(dsn) + "?" + _encodedAuth(dsn);
}
function getReportDialogEndpoint(dsnLike, dialogOptions) {
  var dsn = makeDsn(dsnLike);
  var endpoint = getBaseApiEndpoint(dsn) + "embed/error-page/";
  var encodedOptions = "dsn=" + dsnToString(dsn);
  for (var key in dialogOptions) {
    if (key === "dsn") {
      continue;
    }
    if (key === "user") {
      if (!dialogOptions.user) {
        continue;
      }
      if (dialogOptions.user.name) {
        encodedOptions += "&name=" + encodeURIComponent(dialogOptions.user.name);
      }
      if (dialogOptions.user.email) {
        encodedOptions += "&email=" + encodeURIComponent(dialogOptions.user.email);
      }
    } else {
      encodedOptions += "&" + encodeURIComponent(key) + "=" + encodeURIComponent(dialogOptions[key]);
    }
  }
  return endpoint + "?" + encodedOptions;
}
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
var __assign$2 = function() {
  __assign$2 = Object.assign || function __assign2(t2) {
    for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
      s2 = arguments[i2];
      for (var p2 in s2)
        if (Object.prototype.hasOwnProperty.call(s2, p2))
          t2[p2] = s2[p2];
    }
    return t2;
  };
  return __assign$2.apply(this, arguments);
};
function __values$2(o2) {
  var s2 = typeof Symbol === "function" && Symbol.iterator, m2 = s2 && o2[s2], i2 = 0;
  if (m2)
    return m2.call(o2);
  if (o2 && typeof o2.length === "number")
    return {
      next: function() {
        if (o2 && i2 >= o2.length)
          o2 = void 0;
        return { value: o2 && o2[i2++], done: !o2 };
      }
    };
  throw new TypeError(s2 ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read$2(o2, n2) {
  var m2 = typeof Symbol === "function" && o2[Symbol.iterator];
  if (!m2)
    return o2;
  var i2 = m2.call(o2), r2, ar = [], e2;
  try {
    while ((n2 === void 0 || n2-- > 0) && !(r2 = i2.next()).done)
      ar.push(r2.value);
  } catch (error) {
    e2 = { error };
  } finally {
    try {
      if (r2 && !r2.done && (m2 = i2["return"]))
        m2.call(i2);
    } finally {
      if (e2)
        throw e2.error;
    }
  }
  return ar;
}
function __spread$2() {
  for (var ar = [], i2 = 0; i2 < arguments.length; i2++)
    ar = ar.concat(__read$2(arguments[i2]));
  return ar;
}
var installedIntegrations = [];
function filterDuplicates(integrations) {
  return integrations.reduce(function(acc, integrations2) {
    if (acc.every(function(accIntegration) {
      return integrations2.name !== accIntegration.name;
    })) {
      acc.push(integrations2);
    }
    return acc;
  }, []);
}
function getIntegrationsToSetup(options) {
  var defaultIntegrations2 = options.defaultIntegrations && __spread$2(options.defaultIntegrations) || [];
  var userIntegrations = options.integrations;
  var integrations = __spread$2(filterDuplicates(defaultIntegrations2));
  if (Array.isArray(userIntegrations)) {
    integrations = __spread$2(integrations.filter(function(integrations2) {
      return userIntegrations.every(function(userIntegration) {
        return userIntegration.name !== integrations2.name;
      });
    }), filterDuplicates(userIntegrations));
  } else if (typeof userIntegrations === "function") {
    integrations = userIntegrations(integrations);
    integrations = Array.isArray(integrations) ? integrations : [integrations];
  }
  var integrationsNames = integrations.map(function(i2) {
    return i2.name;
  });
  var alwaysLastToRun = "Debug";
  if (integrationsNames.indexOf(alwaysLastToRun) !== -1) {
    integrations.push.apply(integrations, __spread$2(integrations.splice(integrationsNames.indexOf(alwaysLastToRun), 1)));
  }
  return integrations;
}
function setupIntegration(integration) {
  if (installedIntegrations.indexOf(integration.name) !== -1) {
    return;
  }
  integration.setupOnce(addGlobalEventProcessor, getCurrentHub);
  installedIntegrations.push(integration.name);
  logger.log("Integration installed: " + integration.name);
}
function setupIntegrations(options) {
  var integrations = {};
  getIntegrationsToSetup(options).forEach(function(integration) {
    integrations[integration.name] = integration;
    setupIntegration(integration);
  });
  addNonEnumerableProperty(integrations, "initialized", true);
  return integrations;
}
var ALREADY_SEEN_ERROR = "Not capturing exception because it's already been captured.";
var BaseClient = function() {
  function BaseClient2(backendClass, options) {
    this._integrations = {};
    this._numProcessing = 0;
    this._backend = new backendClass(options);
    this._options = options;
    if (options.dsn) {
      this._dsn = makeDsn(options.dsn);
    }
  }
  BaseClient2.prototype.captureException = function(exception, hint, scope) {
    var _this = this;
    if (checkOrSetAlreadyCaught(exception)) {
      logger.log(ALREADY_SEEN_ERROR);
      return;
    }
    var eventId = hint && hint.event_id;
    this._process(this._getBackend().eventFromException(exception, hint).then(function(event) {
      return _this._captureEvent(event, hint, scope);
    }).then(function(result) {
      eventId = result;
    }));
    return eventId;
  };
  BaseClient2.prototype.captureMessage = function(message, level, hint, scope) {
    var _this = this;
    var eventId = hint && hint.event_id;
    var promisedEvent = isPrimitive$1(message) ? this._getBackend().eventFromMessage(String(message), level, hint) : this._getBackend().eventFromException(message, hint);
    this._process(promisedEvent.then(function(event) {
      return _this._captureEvent(event, hint, scope);
    }).then(function(result) {
      eventId = result;
    }));
    return eventId;
  };
  BaseClient2.prototype.captureEvent = function(event, hint, scope) {
    if (hint && hint.originalException && checkOrSetAlreadyCaught(hint.originalException)) {
      logger.log(ALREADY_SEEN_ERROR);
      return;
    }
    var eventId = hint && hint.event_id;
    this._process(this._captureEvent(event, hint, scope).then(function(result) {
      eventId = result;
    }));
    return eventId;
  };
  BaseClient2.prototype.captureSession = function(session) {
    if (!this._isEnabled()) {
      if (isDebugBuild()) {
        logger.warn("SDK not enabled, will not capture session.");
      }
      return;
    }
    if (!(typeof session.release === "string")) {
      if (isDebugBuild()) {
        logger.warn("Discarded session because of missing or non-string release");
      }
    } else {
      this._sendSession(session);
      session.update({ init: false });
    }
  };
  BaseClient2.prototype.getDsn = function() {
    return this._dsn;
  };
  BaseClient2.prototype.getOptions = function() {
    return this._options;
  };
  BaseClient2.prototype.getTransport = function() {
    return this._getBackend().getTransport();
  };
  BaseClient2.prototype.flush = function(timeout) {
    var _this = this;
    return this._isClientDoneProcessing(timeout).then(function(clientFinished) {
      return _this.getTransport().close(timeout).then(function(transportFlushed) {
        return clientFinished && transportFlushed;
      });
    });
  };
  BaseClient2.prototype.close = function(timeout) {
    var _this = this;
    return this.flush(timeout).then(function(result) {
      _this.getOptions().enabled = false;
      return result;
    });
  };
  BaseClient2.prototype.setupIntegrations = function() {
    if (this._isEnabled() && !this._integrations.initialized) {
      this._integrations = setupIntegrations(this._options);
    }
  };
  BaseClient2.prototype.getIntegration = function(integration) {
    try {
      return this._integrations[integration.id] || null;
    } catch (_oO) {
      logger.warn("Cannot retrieve integration " + integration.id + " from the current Client");
      return null;
    }
  };
  BaseClient2.prototype._updateSessionFromEvent = function(session, event) {
    var e_1, _a2;
    var crashed = false;
    var errored = false;
    var exceptions = event.exception && event.exception.values;
    if (exceptions) {
      errored = true;
      try {
        for (var exceptions_1 = __values$2(exceptions), exceptions_1_1 = exceptions_1.next(); !exceptions_1_1.done; exceptions_1_1 = exceptions_1.next()) {
          var ex = exceptions_1_1.value;
          var mechanism = ex.mechanism;
          if (mechanism && mechanism.handled === false) {
            crashed = true;
            break;
          }
        }
      } catch (e_1_1) {
        e_1 = { error: e_1_1 };
      } finally {
        try {
          if (exceptions_1_1 && !exceptions_1_1.done && (_a2 = exceptions_1.return))
            _a2.call(exceptions_1);
        } finally {
          if (e_1)
            throw e_1.error;
        }
      }
    }
    var sessionNonTerminal = session.status === "ok";
    var shouldUpdateAndSend = sessionNonTerminal && session.errors === 0 || sessionNonTerminal && crashed;
    if (shouldUpdateAndSend) {
      session.update(__assign$2(__assign$2({}, crashed && { status: "crashed" }), { errors: session.errors || Number(errored || crashed) }));
      this.captureSession(session);
    }
  };
  BaseClient2.prototype._sendSession = function(session) {
    this._getBackend().sendSession(session);
  };
  BaseClient2.prototype._isClientDoneProcessing = function(timeout) {
    var _this = this;
    return new SyncPromise(function(resolve) {
      var ticked = 0;
      var tick = 1;
      var interval = setInterval(function() {
        if (_this._numProcessing == 0) {
          clearInterval(interval);
          resolve(true);
        } else {
          ticked += tick;
          if (timeout && ticked >= timeout) {
            clearInterval(interval);
            resolve(false);
          }
        }
      }, tick);
    });
  };
  BaseClient2.prototype._getBackend = function() {
    return this._backend;
  };
  BaseClient2.prototype._isEnabled = function() {
    return this.getOptions().enabled !== false && this._dsn !== void 0;
  };
  BaseClient2.prototype._prepareEvent = function(event, scope, hint) {
    var _this = this;
    var _a2 = this.getOptions().normalizeDepth, normalizeDepth = _a2 === void 0 ? 3 : _a2;
    var prepared = __assign$2(__assign$2({}, event), { event_id: event.event_id || (hint && hint.event_id ? hint.event_id : uuid4()), timestamp: event.timestamp || dateTimestampInSeconds() });
    this._applyClientOptions(prepared);
    this._applyIntegrationsMetadata(prepared);
    var finalScope = scope;
    if (hint && hint.captureContext) {
      finalScope = Scope.clone(finalScope).update(hint.captureContext);
    }
    var result = resolvedSyncPromise(prepared);
    if (finalScope) {
      result = finalScope.applyToEvent(prepared, hint);
    }
    return result.then(function(evt) {
      if (evt) {
        evt.sdkProcessingMetadata = __assign$2(__assign$2({}, evt.sdkProcessingMetadata), { normalizeDepth: normalize(normalizeDepth) });
      }
      if (typeof normalizeDepth === "number" && normalizeDepth > 0) {
        return _this._normalizeEvent(evt, normalizeDepth);
      }
      return evt;
    });
  };
  BaseClient2.prototype._normalizeEvent = function(event, depth) {
    if (!event) {
      return null;
    }
    var normalized = __assign$2(__assign$2(__assign$2(__assign$2(__assign$2({}, event), event.breadcrumbs && {
      breadcrumbs: event.breadcrumbs.map(function(b2) {
        return __assign$2(__assign$2({}, b2), b2.data && {
          data: normalize(b2.data, depth)
        });
      })
    }), event.user && {
      user: normalize(event.user, depth)
    }), event.contexts && {
      contexts: normalize(event.contexts, depth)
    }), event.extra && {
      extra: normalize(event.extra, depth)
    });
    if (event.contexts && event.contexts.trace) {
      normalized.contexts.trace = event.contexts.trace;
    }
    event.sdkProcessingMetadata = __assign$2(__assign$2({}, event.sdkProcessingMetadata), { baseClientNormalized: true });
    return normalized;
  };
  BaseClient2.prototype._applyClientOptions = function(event) {
    var options = this.getOptions();
    var environment = options.environment, release = options.release, dist = options.dist, _a2 = options.maxValueLength, maxValueLength = _a2 === void 0 ? 250 : _a2;
    if (!("environment" in event)) {
      event.environment = "environment" in options ? environment : "production";
    }
    if (event.release === void 0 && release !== void 0) {
      event.release = release;
    }
    if (event.dist === void 0 && dist !== void 0) {
      event.dist = dist;
    }
    if (event.message) {
      event.message = truncate(event.message, maxValueLength);
    }
    var exception = event.exception && event.exception.values && event.exception.values[0];
    if (exception && exception.value) {
      exception.value = truncate(exception.value, maxValueLength);
    }
    var request = event.request;
    if (request && request.url) {
      request.url = truncate(request.url, maxValueLength);
    }
  };
  BaseClient2.prototype._applyIntegrationsMetadata = function(event) {
    var integrationsArray = Object.keys(this._integrations);
    if (integrationsArray.length > 0) {
      event.sdk = event.sdk || {};
      event.sdk.integrations = __spread$2(event.sdk.integrations || [], integrationsArray);
    }
  };
  BaseClient2.prototype._sendEvent = function(event) {
    this._getBackend().sendEvent(event);
  };
  BaseClient2.prototype._captureEvent = function(event, hint, scope) {
    return this._processEvent(event, hint, scope).then(function(finalEvent) {
      return finalEvent.event_id;
    }, function(reason) {
      logger.error(reason);
      return void 0;
    });
  };
  BaseClient2.prototype._processEvent = function(event, hint, scope) {
    var _this = this;
    var _a2 = this.getOptions(), beforeSend = _a2.beforeSend, sampleRate = _a2.sampleRate;
    var transport = this.getTransport();
    function recordLostEvent(outcome, category) {
      if (transport.recordLostEvent) {
        transport.recordLostEvent(outcome, category);
      }
    }
    if (!this._isEnabled()) {
      return rejectedSyncPromise(new SentryError("SDK not enabled, will not capture event."));
    }
    var isTransaction = event.type === "transaction";
    if (!isTransaction && typeof sampleRate === "number" && Math.random() > sampleRate) {
      recordLostEvent("sample_rate", "event");
      return rejectedSyncPromise(new SentryError("Discarding event because it's not included in the random sample (sampling rate = " + sampleRate + ")"));
    }
    return this._prepareEvent(event, scope, hint).then(function(prepared) {
      if (prepared === null) {
        recordLostEvent("event_processor", event.type || "event");
        throw new SentryError("An event processor returned null, will not send event.");
      }
      var isInternalException = hint && hint.data && hint.data.__sentry__ === true;
      if (isInternalException || isTransaction || !beforeSend) {
        return prepared;
      }
      var beforeSendResult = beforeSend(prepared, hint);
      return _ensureBeforeSendRv(beforeSendResult);
    }).then(function(processedEvent) {
      if (processedEvent === null) {
        recordLostEvent("before_send", event.type || "event");
        throw new SentryError("`beforeSend` returned `null`, will not send event.");
      }
      var session = scope && scope.getSession && scope.getSession();
      if (!isTransaction && session) {
        _this._updateSessionFromEvent(session, processedEvent);
      }
      _this._sendEvent(processedEvent);
      return processedEvent;
    }).then(null, function(reason) {
      if (reason instanceof SentryError) {
        throw reason;
      }
      _this.captureException(reason, {
        data: {
          __sentry__: true
        },
        originalException: reason
      });
      throw new SentryError("Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: " + reason);
    });
  };
  BaseClient2.prototype._process = function(promise) {
    var _this = this;
    this._numProcessing += 1;
    void promise.then(function(value) {
      _this._numProcessing -= 1;
      return value;
    }, function(reason) {
      _this._numProcessing -= 1;
      return reason;
    });
  };
  return BaseClient2;
}();
function _ensureBeforeSendRv(rv) {
  var nullErr = "`beforeSend` method has to return `null` or a valid event.";
  if (isThenable(rv)) {
    return rv.then(function(event) {
      if (!(isPlainObject(event) || event === null)) {
        throw new SentryError(nullErr);
      }
      return event;
    }, function(e2) {
      throw new SentryError("beforeSend rejected with " + e2);
    });
  } else if (!(isPlainObject(rv) || rv === null)) {
    throw new SentryError(nullErr);
  }
  return rv;
}
var NoopTransport = function() {
  function NoopTransport2() {
  }
  NoopTransport2.prototype.sendEvent = function(_2) {
    return resolvedSyncPromise({
      reason: "NoopTransport: Event has been skipped because no Dsn is configured.",
      status: "skipped"
    });
  };
  NoopTransport2.prototype.close = function(_2) {
    return resolvedSyncPromise(true);
  };
  return NoopTransport2;
}();
var BaseBackend = function() {
  function BaseBackend2(options) {
    this._options = options;
    if (!this._options.dsn) {
      logger.warn("No DSN provided, backend will not do anything.");
    }
    this._transport = this._setupTransport();
  }
  BaseBackend2.prototype.eventFromException = function(_exception, _hint) {
    throw new SentryError("Backend has to implement `eventFromException` method");
  };
  BaseBackend2.prototype.eventFromMessage = function(_message, _level, _hint) {
    throw new SentryError("Backend has to implement `eventFromMessage` method");
  };
  BaseBackend2.prototype.sendEvent = function(event) {
    void this._transport.sendEvent(event).then(null, function(reason) {
      if (isDebugBuild()) {
        logger.error("Error while sending event: " + reason);
      }
    });
  };
  BaseBackend2.prototype.sendSession = function(session) {
    if (!this._transport.sendSession) {
      if (isDebugBuild()) {
        logger.warn("Dropping session because custom transport doesn't implement sendSession");
      }
      return;
    }
    void this._transport.sendSession(session).then(null, function(reason) {
      if (isDebugBuild()) {
        logger.error("Error while sending session: " + reason);
      }
    });
  };
  BaseBackend2.prototype.getTransport = function() {
    return this._transport;
  };
  BaseBackend2.prototype._setupTransport = function() {
    return new NoopTransport();
  };
  return BaseBackend2;
}();
function getSdkMetadataForEnvelopeHeader(api) {
  if (!api.metadata || !api.metadata.sdk) {
    return;
  }
  var _a2 = api.metadata.sdk, name = _a2.name, version2 = _a2.version;
  return { name, version: version2 };
}
function enhanceEventWithSdkInfo(event, sdkInfo) {
  if (!sdkInfo) {
    return event;
  }
  event.sdk = event.sdk || {};
  event.sdk.name = event.sdk.name || sdkInfo.name;
  event.sdk.version = event.sdk.version || sdkInfo.version;
  event.sdk.integrations = __spread$2(event.sdk.integrations || [], sdkInfo.integrations || []);
  event.sdk.packages = __spread$2(event.sdk.packages || [], sdkInfo.packages || []);
  return event;
}
function sessionToSentryRequest(session, api) {
  var sdkInfo = getSdkMetadataForEnvelopeHeader(api);
  var envelopeHeaders = JSON.stringify(__assign$2(__assign$2({ sent_at: new Date().toISOString() }, sdkInfo && { sdk: sdkInfo }), !!api.tunnel && { dsn: dsnToString(api.dsn) }));
  var type = "aggregates" in session ? "sessions" : "session";
  var itemHeaders = JSON.stringify({
    type
  });
  return {
    body: envelopeHeaders + "\n" + itemHeaders + "\n" + JSON.stringify(session),
    type,
    url: getEnvelopeEndpointWithUrlEncodedAuth(api.dsn, api.tunnel)
  };
}
function eventToSentryRequest(event, api) {
  var sdkInfo = getSdkMetadataForEnvelopeHeader(api);
  var eventType = event.type || "event";
  var useEnvelope = eventType === "transaction" || !!api.tunnel;
  var transactionSampling = (event.sdkProcessingMetadata || {}).transactionSampling;
  var _a2 = transactionSampling || {}, samplingMethod = _a2.method, sampleRate = _a2.rate;
  enhanceEventWithSdkInfo(event, api.metadata.sdk);
  event.tags = event.tags || {};
  event.extra = event.extra || {};
  if (!(event.sdkProcessingMetadata && event.sdkProcessingMetadata.baseClientNormalized)) {
    event.tags.skippedNormalization = true;
    event.extra.normalizeDepth = event.sdkProcessingMetadata ? event.sdkProcessingMetadata.normalizeDepth : "unset";
  }
  delete event.sdkProcessingMetadata;
  var body;
  try {
    body = JSON.stringify(event);
  } catch (err) {
    event.tags.JSONStringifyError = true;
    event.extra.JSONStringifyError = err;
    try {
      body = JSON.stringify(normalize(event));
    } catch (newErr) {
      var innerErr = newErr;
      body = JSON.stringify({
        message: "JSON.stringify error after renormalization",
        extra: { message: innerErr.message, stack: innerErr.stack }
      });
    }
  }
  var req = {
    body,
    type: eventType,
    url: useEnvelope ? getEnvelopeEndpointWithUrlEncodedAuth(api.dsn, api.tunnel) : getStoreEndpointWithUrlEncodedAuth(api.dsn)
  };
  if (useEnvelope) {
    var envelopeHeaders = JSON.stringify(__assign$2(__assign$2({ event_id: event.event_id, sent_at: new Date().toISOString() }, sdkInfo && { sdk: sdkInfo }), !!api.tunnel && { dsn: dsnToString(api.dsn) }));
    var itemHeaders = JSON.stringify({
      type: eventType,
      sample_rates: [{ id: samplingMethod, rate: sampleRate }]
    });
    var envelope = envelopeHeaders + "\n" + itemHeaders + "\n" + req.body;
    req.body = envelope;
  }
  return req;
}
function initAndBind(clientClass, options) {
  if (options.debug === true) {
    logger.enable();
  }
  var hub = getCurrentHub();
  var scope = hub.getScope();
  if (scope) {
    scope.update(options.initialScope);
  }
  var client = new clientClass(options);
  hub.bindClient(client);
}
var SDK_VERSION = "6.17.9";
var originalFunctionToString;
var FunctionToString = function() {
  function FunctionToString2() {
    this.name = FunctionToString2.id;
  }
  FunctionToString2.prototype.setupOnce = function() {
    originalFunctionToString = Function.prototype.toString;
    Function.prototype.toString = function() {
      var args = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
      }
      var context = getOriginalFunction(this) || this;
      return originalFunctionToString.apply(context, args);
    };
  };
  FunctionToString2.id = "FunctionToString";
  return FunctionToString2;
}();
var DEFAULT_IGNORE_ERRORS = [/^Script error\.?$/, /^Javascript error: Script error\.? on line 0$/];
var InboundFilters = function() {
  function InboundFilters2(_options) {
    if (_options === void 0) {
      _options = {};
    }
    this._options = _options;
    this.name = InboundFilters2.id;
  }
  InboundFilters2.prototype.setupOnce = function() {
    addGlobalEventProcessor(function(event) {
      var hub = getCurrentHub();
      if (!hub) {
        return event;
      }
      var self2 = hub.getIntegration(InboundFilters2);
      if (self2) {
        var client = hub.getClient();
        var clientOptions = client ? client.getOptions() : {};
        var options = typeof self2._mergeOptions === "function" ? self2._mergeOptions(clientOptions) : {};
        if (typeof self2._shouldDropEvent !== "function") {
          return event;
        }
        return self2._shouldDropEvent(event, options) ? null : event;
      }
      return event;
    });
  };
  InboundFilters2.prototype._shouldDropEvent = function(event, options) {
    if (this._isSentryError(event, options)) {
      if (isDebugBuild()) {
        logger.warn("Event dropped due to being internal Sentry Error.\nEvent: " + getEventDescription(event));
      }
      return true;
    }
    if (this._isIgnoredError(event, options)) {
      if (isDebugBuild()) {
        logger.warn("Event dropped due to being matched by `ignoreErrors` option.\nEvent: " + getEventDescription(event));
      }
      return true;
    }
    if (this._isDeniedUrl(event, options)) {
      if (isDebugBuild()) {
        logger.warn("Event dropped due to being matched by `denyUrls` option.\nEvent: " + getEventDescription(event) + ".\nUrl: " + this._getEventFilterUrl(event));
      }
      return true;
    }
    if (!this._isAllowedUrl(event, options)) {
      if (isDebugBuild()) {
        logger.warn("Event dropped due to not being matched by `allowUrls` option.\nEvent: " + getEventDescription(event) + ".\nUrl: " + this._getEventFilterUrl(event));
      }
      return true;
    }
    return false;
  };
  InboundFilters2.prototype._isSentryError = function(event, options) {
    if (!options.ignoreInternal) {
      return false;
    }
    try {
      return event.exception.values[0].type === "SentryError";
    } catch (e2) {
    }
    return false;
  };
  InboundFilters2.prototype._isIgnoredError = function(event, options) {
    if (!options.ignoreErrors || !options.ignoreErrors.length) {
      return false;
    }
    return this._getPossibleEventMessages(event).some(function(message) {
      return options.ignoreErrors.some(function(pattern) {
        return isMatchingPattern(message, pattern);
      });
    });
  };
  InboundFilters2.prototype._isDeniedUrl = function(event, options) {
    if (!options.denyUrls || !options.denyUrls.length) {
      return false;
    }
    var url = this._getEventFilterUrl(event);
    return !url ? false : options.denyUrls.some(function(pattern) {
      return isMatchingPattern(url, pattern);
    });
  };
  InboundFilters2.prototype._isAllowedUrl = function(event, options) {
    if (!options.allowUrls || !options.allowUrls.length) {
      return true;
    }
    var url = this._getEventFilterUrl(event);
    return !url ? true : options.allowUrls.some(function(pattern) {
      return isMatchingPattern(url, pattern);
    });
  };
  InboundFilters2.prototype._mergeOptions = function(clientOptions) {
    if (clientOptions === void 0) {
      clientOptions = {};
    }
    return {
      allowUrls: __spread$2(this._options.whitelistUrls || [], this._options.allowUrls || [], clientOptions.whitelistUrls || [], clientOptions.allowUrls || []),
      denyUrls: __spread$2(this._options.blacklistUrls || [], this._options.denyUrls || [], clientOptions.blacklistUrls || [], clientOptions.denyUrls || []),
      ignoreErrors: __spread$2(this._options.ignoreErrors || [], clientOptions.ignoreErrors || [], DEFAULT_IGNORE_ERRORS),
      ignoreInternal: typeof this._options.ignoreInternal !== "undefined" ? this._options.ignoreInternal : true
    };
  };
  InboundFilters2.prototype._getPossibleEventMessages = function(event) {
    if (event.message) {
      return [event.message];
    }
    if (event.exception) {
      try {
        var _a2 = event.exception.values && event.exception.values[0] || {}, _b = _a2.type, type = _b === void 0 ? "" : _b, _c = _a2.value, value = _c === void 0 ? "" : _c;
        return ["" + value, type + ": " + value];
      } catch (oO) {
        if (isDebugBuild()) {
          logger.error("Cannot extract message for event " + getEventDescription(event));
        }
        return [];
      }
    }
    return [];
  };
  InboundFilters2.prototype._getLastValidUrl = function(frames) {
    if (frames === void 0) {
      frames = [];
    }
    for (var i2 = frames.length - 1; i2 >= 0; i2--) {
      var frame2 = frames[i2];
      if (frame2 && frame2.filename !== "<anonymous>" && frame2.filename !== "[native code]") {
        return frame2.filename || null;
      }
    }
    return null;
  };
  InboundFilters2.prototype._getEventFilterUrl = function(event) {
    try {
      if (event.stacktrace) {
        return this._getLastValidUrl(event.stacktrace.frames);
      }
      var frames_1;
      try {
        frames_1 = event.exception.values[0].stacktrace.frames;
      } catch (e2) {
      }
      return frames_1 ? this._getLastValidUrl(frames_1) : null;
    } catch (oO) {
      if (isDebugBuild()) {
        logger.error("Cannot extract url for event " + getEventDescription(event));
      }
      return null;
    }
  };
  InboundFilters2.id = "InboundFilters";
  return InboundFilters2;
}();
var UNKNOWN_FUNCTION = "?";
function createFrame(filename, func, lineno, colno) {
  var frame2 = {
    filename,
    function: func,
    in_app: true
  };
  if (lineno !== void 0) {
    frame2.lineno = lineno;
  }
  if (colno !== void 0) {
    frame2.colno = colno;
  }
  return frame2;
}
var chromeRegex = /^\s*at (?:(.*?) ?\((?:address at )?)?((?:file|https?|blob|chrome-extension|address|native|eval|webpack|<anonymous>|[-a-z]+:|.*bundle|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
var chromeEvalRegex = /\((\S*)(?::(\d+))(?::(\d+))\)/;
var chrome = function(line) {
  var parts = chromeRegex.exec(line);
  if (parts) {
    var isEval = parts[2] && parts[2].indexOf("eval") === 0;
    if (isEval) {
      var subMatch = chromeEvalRegex.exec(parts[2]);
      if (subMatch) {
        parts[2] = subMatch[1];
        parts[3] = subMatch[2];
        parts[4] = subMatch[3];
      }
    }
    var _a2 = __read$6(extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]), 2), func = _a2[0], filename = _a2[1];
    return createFrame(filename, func, parts[3] ? +parts[3] : void 0, parts[4] ? +parts[4] : void 0);
  }
  return;
};
var geckoREgex = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:file|https?|blob|chrome|webpack|resource|moz-extension|capacitor).*?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i;
var geckoEvalRegex = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
var gecko = function(line) {
  var _a2;
  var parts = geckoREgex.exec(line);
  if (parts) {
    var isEval = parts[3] && parts[3].indexOf(" > eval") > -1;
    if (isEval) {
      var subMatch = geckoEvalRegex.exec(parts[3]);
      if (subMatch) {
        parts[1] = parts[1] || "eval";
        parts[3] = subMatch[1];
        parts[4] = subMatch[2];
        parts[5] = "";
      }
    }
    var filename = parts[3];
    var func = parts[1] || UNKNOWN_FUNCTION;
    _a2 = __read$6(extractSafariExtensionDetails(func, filename), 2), func = _a2[0], filename = _a2[1];
    return createFrame(filename, func, parts[4] ? +parts[4] : void 0, parts[5] ? +parts[5] : void 0);
  }
  return;
};
var winjsRegex = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;
var winjs = function(line) {
  var parts = winjsRegex.exec(line);
  return parts ? createFrame(parts[2], parts[1] || UNKNOWN_FUNCTION, +parts[3], parts[4] ? +parts[4] : void 0) : void 0;
};
var opera10Regex = / line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i;
var opera10 = function(line) {
  var parts = opera10Regex.exec(line);
  return parts ? createFrame(parts[2], parts[3] || UNKNOWN_FUNCTION, +parts[1]) : void 0;
};
var opera11Regex = / line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i;
var opera11 = function(line) {
  var parts = opera11Regex.exec(line);
  return parts ? createFrame(parts[5], parts[3] || parts[4] || UNKNOWN_FUNCTION, +parts[1], +parts[2]) : void 0;
};
var extractSafariExtensionDetails = function(func, filename) {
  var isSafariExtension = func.indexOf("safari-extension") !== -1;
  var isSafariWebExtension = func.indexOf("safari-web-extension") !== -1;
  return isSafariExtension || isSafariWebExtension ? [
    func.indexOf("@") !== -1 ? func.split("@")[0] : UNKNOWN_FUNCTION,
    isSafariExtension ? "safari-extension:" + filename : "safari-web-extension:" + filename
  ] : [func, filename];
};
function exceptionFromError(ex) {
  var frames = parseStackFrames(ex);
  var exception = {
    type: ex && ex.name,
    value: extractMessage(ex)
  };
  if (frames && frames.length) {
    exception.stacktrace = { frames };
  }
  if (exception.type === void 0 && exception.value === "") {
    exception.value = "Unrecoverable error caught";
  }
  return exception;
}
function eventFromPlainObject(exception, syntheticException, rejection) {
  var event = {
    exception: {
      values: [
        {
          type: isEvent(exception) ? exception.constructor.name : rejection ? "UnhandledRejection" : "Error",
          value: "Non-Error " + (rejection ? "promise rejection" : "exception") + " captured with keys: " + extractExceptionKeysForMessage(exception)
        }
      ]
    },
    extra: {
      __serialized__: normalizeToSize(exception)
    }
  };
  if (syntheticException) {
    event.stacktrace = {
      frames: parseStackFrames(syntheticException)
    };
  }
  return event;
}
function eventFromError(ex) {
  return {
    exception: {
      values: [exceptionFromError(ex)]
    }
  };
}
function parseStackFrames(ex) {
  var stacktrace = ex.stacktrace || ex.stack || "";
  var popSize = getPopSize(ex);
  try {
    return createStackParser(opera10, opera11, chrome, winjs, gecko)(stacktrace, popSize);
  } catch (e2) {
  }
  return [];
}
var reactMinifiedRegexp = /Minified React error #\d+;/i;
function getPopSize(ex) {
  if (ex) {
    if (typeof ex.framesToPop === "number") {
      return ex.framesToPop;
    }
    if (reactMinifiedRegexp.test(ex.message)) {
      return 1;
    }
  }
  return 0;
}
function extractMessage(ex) {
  var message = ex && ex.message;
  if (!message) {
    return "No error message";
  }
  if (message.error && typeof message.error.message === "string") {
    return message.error.message;
  }
  return message;
}
function eventFromException(options, exception, hint) {
  var syntheticException = hint && hint.syntheticException || void 0;
  var event = eventFromUnknownInput(exception, syntheticException, {
    attachStacktrace: options.attachStacktrace
  });
  addExceptionMechanism(event);
  event.level = Severity.Error;
  if (hint && hint.event_id) {
    event.event_id = hint.event_id;
  }
  return resolvedSyncPromise(event);
}
function eventFromMessage(options, message, level, hint) {
  if (level === void 0) {
    level = Severity.Info;
  }
  var syntheticException = hint && hint.syntheticException || void 0;
  var event = eventFromString(message, syntheticException, {
    attachStacktrace: options.attachStacktrace
  });
  event.level = level;
  if (hint && hint.event_id) {
    event.event_id = hint.event_id;
  }
  return resolvedSyncPromise(event);
}
function eventFromUnknownInput(exception, syntheticException, options) {
  if (options === void 0) {
    options = {};
  }
  var event;
  if (isErrorEvent(exception) && exception.error) {
    var errorEvent = exception;
    return eventFromError(errorEvent.error);
  }
  if (isDOMError(exception) || isDOMException(exception)) {
    var domException = exception;
    if ("stack" in exception) {
      event = eventFromError(exception);
    } else {
      var name_1 = domException.name || (isDOMError(domException) ? "DOMError" : "DOMException");
      var message = domException.message ? name_1 + ": " + domException.message : name_1;
      event = eventFromString(message, syntheticException, options);
      addExceptionTypeValue(event, message);
    }
    if ("code" in domException) {
      event.tags = __assign$5(__assign$5({}, event.tags), { "DOMException.code": "" + domException.code });
    }
    return event;
  }
  if (isError(exception)) {
    return eventFromError(exception);
  }
  if (isPlainObject(exception) || isEvent(exception)) {
    var objectException = exception;
    event = eventFromPlainObject(objectException, syntheticException, options.isRejection);
    addExceptionMechanism(event, {
      synthetic: true
    });
    return event;
  }
  event = eventFromString(exception, syntheticException, options);
  addExceptionTypeValue(event, "" + exception, void 0);
  addExceptionMechanism(event, {
    synthetic: true
  });
  return event;
}
function eventFromString(input, syntheticException, options) {
  if (options === void 0) {
    options = {};
  }
  var event = {
    message: input
  };
  if (options.attachStacktrace && syntheticException) {
    event.stacktrace = {
      frames: parseStackFrames(syntheticException)
    };
  }
  return event;
}
var global$7 = getGlobalObject();
var cachedFetchImpl;
function getNativeFetchImplementation() {
  if (cachedFetchImpl) {
    return cachedFetchImpl;
  }
  if (isNativeFetch(global$7.fetch)) {
    return cachedFetchImpl = global$7.fetch.bind(global$7);
  }
  var document2 = global$7.document;
  var fetchImpl = global$7.fetch;
  if (document2 && typeof document2.createElement === "function") {
    try {
      var sandbox = document2.createElement("iframe");
      sandbox.hidden = true;
      document2.head.appendChild(sandbox);
      var contentWindow = sandbox.contentWindow;
      if (contentWindow && contentWindow.fetch) {
        fetchImpl = contentWindow.fetch;
      }
      document2.head.removeChild(sandbox);
    } catch (e2) {
      if (isDebugBuild()) {
        logger.warn("Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ", e2);
      }
    }
  }
  return cachedFetchImpl = fetchImpl.bind(global$7);
}
function sendReport(url, body) {
  var isRealNavigator = Object.prototype.toString.call(global$7 && global$7.navigator) === "[object Navigator]";
  var hasSendBeacon = isRealNavigator && typeof global$7.navigator.sendBeacon === "function";
  if (hasSendBeacon) {
    var sendBeacon = global$7.navigator.sendBeacon.bind(global$7.navigator);
    return sendBeacon(url, body);
  }
  if (supportsFetch()) {
    var fetch_1 = getNativeFetchImplementation();
    return forget(fetch_1(url, {
      body,
      method: "POST",
      credentials: "omit",
      keepalive: true
    }));
  }
}
function requestTypeToCategory(ty) {
  var tyStr = ty;
  return tyStr === "event" ? "error" : tyStr;
}
var global$6 = getGlobalObject();
var BaseTransport = function() {
  function BaseTransport2(options) {
    var _this = this;
    this.options = options;
    this._buffer = makePromiseBuffer(30);
    this._rateLimits = {};
    this._outcomes = {};
    this._api = initAPIDetails(options.dsn, options._metadata, options.tunnel);
    this.url = getStoreEndpointWithUrlEncodedAuth(this._api.dsn);
    if (this.options.sendClientReports && global$6.document) {
      global$6.document.addEventListener("visibilitychange", function() {
        if (global$6.document.visibilityState === "hidden") {
          _this._flushOutcomes();
        }
      });
    }
  }
  BaseTransport2.prototype.sendEvent = function(event) {
    return this._sendRequest(eventToSentryRequest(event, this._api), event);
  };
  BaseTransport2.prototype.sendSession = function(session) {
    return this._sendRequest(sessionToSentryRequest(session, this._api), session);
  };
  BaseTransport2.prototype.close = function(timeout) {
    return this._buffer.drain(timeout);
  };
  BaseTransport2.prototype.recordLostEvent = function(reason, category) {
    var _a2;
    if (!this.options.sendClientReports) {
      return;
    }
    var key = requestTypeToCategory(category) + ":" + reason;
    logger.log("Adding outcome: " + key);
    this._outcomes[key] = (_a2 = this._outcomes[key], _a2 !== null && _a2 !== void 0 ? _a2 : 0) + 1;
  };
  BaseTransport2.prototype._flushOutcomes = function() {
    if (!this.options.sendClientReports) {
      return;
    }
    var outcomes = this._outcomes;
    this._outcomes = {};
    if (!Object.keys(outcomes).length) {
      logger.log("No outcomes to flush");
      return;
    }
    logger.log("Flushing outcomes:\n" + JSON.stringify(outcomes, null, 2));
    var url = getEnvelopeEndpointWithUrlEncodedAuth(this._api.dsn, this._api.tunnel);
    var envelopeHeader = JSON.stringify(__assign$5({}, this._api.tunnel && { dsn: dsnToString(this._api.dsn) }));
    var itemHeaders = JSON.stringify({
      type: "client_report"
    });
    var item = JSON.stringify({
      timestamp: dateTimestampInSeconds(),
      discarded_events: Object.keys(outcomes).map(function(key) {
        var _a2 = __read$6(key.split(":"), 2), category = _a2[0], reason = _a2[1];
        return {
          reason,
          category,
          quantity: outcomes[key]
        };
      })
    });
    var envelope = envelopeHeader + "\n" + itemHeaders + "\n" + item;
    try {
      sendReport(url, envelope);
    } catch (e2) {
      logger.error(e2);
    }
  };
  BaseTransport2.prototype._handleResponse = function(_a2) {
    var requestType = _a2.requestType, response = _a2.response, headers = _a2.headers, resolve = _a2.resolve, reject = _a2.reject;
    var status = eventStatusFromHttpCode(response.status);
    var limited = this._handleRateLimit(headers);
    if (limited && isDebugBuild()) {
      logger.warn("Too many " + requestType + " requests, backing off until: " + this._disabledUntil(requestType));
    }
    if (status === "success") {
      resolve({ status });
      return;
    }
    reject(response);
  };
  BaseTransport2.prototype._disabledUntil = function(requestType) {
    var category = requestTypeToCategory(requestType);
    return this._rateLimits[category] || this._rateLimits.all;
  };
  BaseTransport2.prototype._isRateLimited = function(requestType) {
    return this._disabledUntil(requestType) > new Date(Date.now());
  };
  BaseTransport2.prototype._handleRateLimit = function(headers) {
    var e_1, _a2, e_2, _b;
    var now2 = Date.now();
    var rlHeader = headers["x-sentry-rate-limits"];
    var raHeader = headers["retry-after"];
    if (rlHeader) {
      try {
        for (var _c = __values$4(rlHeader.trim().split(",")), _d = _c.next(); !_d.done; _d = _c.next()) {
          var limit = _d.value;
          var parameters = limit.split(":", 2);
          var headerDelay = parseInt(parameters[0], 10);
          var delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1e3;
          try {
            for (var _e2 = (e_2 = void 0, __values$4(parameters[1].split(";"))), _f2 = _e2.next(); !_f2.done; _f2 = _e2.next()) {
              var category = _f2.value;
              this._rateLimits[category || "all"] = new Date(now2 + delay);
            }
          } catch (e_2_1) {
            e_2 = { error: e_2_1 };
          } finally {
            try {
              if (_f2 && !_f2.done && (_b = _e2.return))
                _b.call(_e2);
            } finally {
              if (e_2)
                throw e_2.error;
            }
          }
        }
      } catch (e_1_1) {
        e_1 = { error: e_1_1 };
      } finally {
        try {
          if (_d && !_d.done && (_a2 = _c.return))
            _a2.call(_c);
        } finally {
          if (e_1)
            throw e_1.error;
        }
      }
      return true;
    } else if (raHeader) {
      this._rateLimits.all = new Date(now2 + parseRetryAfterHeader(now2, raHeader));
      return true;
    }
    return false;
  };
  return BaseTransport2;
}();
var FetchTransport = function(_super) {
  __extends$3(FetchTransport2, _super);
  function FetchTransport2(options, fetchImpl) {
    if (fetchImpl === void 0) {
      fetchImpl = getNativeFetchImplementation();
    }
    var _this = _super.call(this, options) || this;
    _this._fetch = fetchImpl;
    return _this;
  }
  FetchTransport2.prototype._sendRequest = function(sentryRequest, originalPayload) {
    var _this = this;
    if (this._isRateLimited(sentryRequest.type)) {
      this.recordLostEvent("ratelimit_backoff", sentryRequest.type);
      return Promise.reject({
        event: originalPayload,
        type: sentryRequest.type,
        reason: "Transport for " + sentryRequest.type + " requests locked till " + this._disabledUntil(sentryRequest.type) + " due to too many requests.",
        status: 429
      });
    }
    var options = {
      body: sentryRequest.body,
      method: "POST",
      referrerPolicy: supportsReferrerPolicy() ? "origin" : ""
    };
    if (this.options.fetchParameters !== void 0) {
      Object.assign(options, this.options.fetchParameters);
    }
    if (this.options.headers !== void 0) {
      options.headers = this.options.headers;
    }
    return this._buffer.add(function() {
      return new SyncPromise(function(resolve, reject) {
        void _this._fetch(sentryRequest.url, options).then(function(response) {
          var headers = {
            "x-sentry-rate-limits": response.headers.get("X-Sentry-Rate-Limits"),
            "retry-after": response.headers.get("Retry-After")
          };
          _this._handleResponse({
            requestType: sentryRequest.type,
            response,
            headers,
            resolve,
            reject
          });
        }).catch(reject);
      });
    }).then(void 0, function(reason) {
      if (reason instanceof SentryError) {
        _this.recordLostEvent("queue_overflow", sentryRequest.type);
      } else {
        _this.recordLostEvent("network_error", sentryRequest.type);
      }
      throw reason;
    });
  };
  return FetchTransport2;
}(BaseTransport);
var XHRTransport = function(_super) {
  __extends$3(XHRTransport2, _super);
  function XHRTransport2() {
    return _super !== null && _super.apply(this, arguments) || this;
  }
  XHRTransport2.prototype._sendRequest = function(sentryRequest, originalPayload) {
    var _this = this;
    if (this._isRateLimited(sentryRequest.type)) {
      this.recordLostEvent("ratelimit_backoff", sentryRequest.type);
      return Promise.reject({
        event: originalPayload,
        type: sentryRequest.type,
        reason: "Transport for " + sentryRequest.type + " requests locked till " + this._disabledUntil(sentryRequest.type) + " due to too many requests.",
        status: 429
      });
    }
    return this._buffer.add(function() {
      return new SyncPromise(function(resolve, reject) {
        var request = new XMLHttpRequest();
        request.onreadystatechange = function() {
          if (request.readyState === 4) {
            var headers = {
              "x-sentry-rate-limits": request.getResponseHeader("X-Sentry-Rate-Limits"),
              "retry-after": request.getResponseHeader("Retry-After")
            };
            _this._handleResponse({ requestType: sentryRequest.type, response: request, headers, resolve, reject });
          }
        };
        request.open("POST", sentryRequest.url);
        for (var header in _this.options.headers) {
          if (Object.prototype.hasOwnProperty.call(_this.options.headers, header)) {
            request.setRequestHeader(header, _this.options.headers[header]);
          }
        }
        request.send(sentryRequest.body);
      });
    }).then(void 0, function(reason) {
      if (reason instanceof SentryError) {
        _this.recordLostEvent("queue_overflow", sentryRequest.type);
      } else {
        _this.recordLostEvent("network_error", sentryRequest.type);
      }
      throw reason;
    });
  };
  return XHRTransport2;
}(BaseTransport);
var BrowserBackend = function(_super) {
  __extends$3(BrowserBackend2, _super);
  function BrowserBackend2() {
    return _super !== null && _super.apply(this, arguments) || this;
  }
  BrowserBackend2.prototype.eventFromException = function(exception, hint) {
    return eventFromException(this._options, exception, hint);
  };
  BrowserBackend2.prototype.eventFromMessage = function(message, level, hint) {
    if (level === void 0) {
      level = Severity.Info;
    }
    return eventFromMessage(this._options, message, level, hint);
  };
  BrowserBackend2.prototype._setupTransport = function() {
    if (!this._options.dsn) {
      return _super.prototype._setupTransport.call(this);
    }
    var transportOptions = __assign$5(__assign$5({}, this._options.transportOptions), { dsn: this._options.dsn, tunnel: this._options.tunnel, sendClientReports: this._options.sendClientReports, _metadata: this._options._metadata });
    if (this._options.transport) {
      return new this._options.transport(transportOptions);
    }
    if (supportsFetch()) {
      return new FetchTransport(transportOptions);
    }
    return new XHRTransport(transportOptions);
  };
  return BrowserBackend2;
}(BaseBackend);
var global$5 = getGlobalObject();
var ignoreOnError = 0;
function shouldIgnoreOnError() {
  return ignoreOnError > 0;
}
function ignoreNextOnError() {
  ignoreOnError += 1;
  setTimeout(function() {
    ignoreOnError -= 1;
  });
}
function wrap(fn2, options, before) {
  if (options === void 0) {
    options = {};
  }
  if (typeof fn2 !== "function") {
    return fn2;
  }
  try {
    var wrapper = fn2.__sentry_wrapped__;
    if (wrapper) {
      return wrapper;
    }
    if (getOriginalFunction(fn2)) {
      return fn2;
    }
  } catch (e2) {
    return fn2;
  }
  var sentryWrapped = function() {
    var args = Array.prototype.slice.call(arguments);
    try {
      if (before && typeof before === "function") {
        before.apply(this, arguments);
      }
      var wrappedArguments = args.map(function(arg) {
        return wrap(arg, options);
      });
      return fn2.apply(this, wrappedArguments);
    } catch (ex) {
      ignoreNextOnError();
      withScope(function(scope) {
        scope.addEventProcessor(function(event) {
          if (options.mechanism) {
            addExceptionTypeValue(event, void 0, void 0);
            addExceptionMechanism(event, options.mechanism);
          }
          event.extra = __assign$5(__assign$5({}, event.extra), { arguments: args });
          return event;
        });
        captureException(ex);
      });
      throw ex;
    }
  };
  try {
    for (var property in fn2) {
      if (Object.prototype.hasOwnProperty.call(fn2, property)) {
        sentryWrapped[property] = fn2[property];
      }
    }
  } catch (_oO) {
  }
  markFunctionWrapped(sentryWrapped, fn2);
  addNonEnumerableProperty(fn2, "__sentry_wrapped__", sentryWrapped);
  try {
    var descriptor = Object.getOwnPropertyDescriptor(sentryWrapped, "name");
    if (descriptor.configurable) {
      Object.defineProperty(sentryWrapped, "name", {
        get: function() {
          return fn2.name;
        }
      });
    }
  } catch (_oO) {
  }
  return sentryWrapped;
}
function injectReportDialog(options) {
  if (options === void 0) {
    options = {};
  }
  if (!global$5.document) {
    return;
  }
  if (!options.eventId) {
    if (isDebugBuild()) {
      logger.error("Missing eventId option in showReportDialog call");
    }
    return;
  }
  if (!options.dsn) {
    if (isDebugBuild()) {
      logger.error("Missing dsn option in showReportDialog call");
    }
    return;
  }
  var script = global$5.document.createElement("script");
  script.async = true;
  script.src = getReportDialogEndpoint(options.dsn, options);
  if (options.onLoad) {
    script.onload = options.onLoad;
  }
  var injectionPoint = global$5.document.head || global$5.document.body;
  if (injectionPoint) {
    injectionPoint.appendChild(script);
  }
}
var GlobalHandlers = function() {
  function GlobalHandlers2(options) {
    this.name = GlobalHandlers2.id;
    this._installFunc = {
      onerror: _installGlobalOnErrorHandler,
      onunhandledrejection: _installGlobalOnUnhandledRejectionHandler
    };
    this._options = __assign$5({ onerror: true, onunhandledrejection: true }, options);
  }
  GlobalHandlers2.prototype.setupOnce = function() {
    Error.stackTraceLimit = 50;
    var options = this._options;
    for (var key in options) {
      var installFunc = this._installFunc[key];
      if (installFunc && options[key]) {
        globalHandlerLog(key);
        installFunc();
        this._installFunc[key] = void 0;
      }
    }
  };
  GlobalHandlers2.id = "GlobalHandlers";
  return GlobalHandlers2;
}();
function _installGlobalOnErrorHandler() {
  addInstrumentationHandler("error", function(data) {
    var _a2 = __read$6(getHubAndAttachStacktrace(), 2), hub = _a2[0], attachStacktrace = _a2[1];
    if (!hub.getIntegration(GlobalHandlers)) {
      return;
    }
    var msg = data.msg, url = data.url, line = data.line, column = data.column, error = data.error;
    if (shouldIgnoreOnError() || error && error.__sentry_own_request__) {
      return;
    }
    var event = error === void 0 && isString$1(msg) ? _eventFromIncompleteOnError(msg, url, line, column) : _enhanceEventWithInitialFrame(eventFromUnknownInput(error || msg, void 0, {
      attachStacktrace,
      isRejection: false
    }), url, line, column);
    event.level = Severity.Error;
    addMechanismAndCapture(hub, error, event, "onerror");
  });
}
function _installGlobalOnUnhandledRejectionHandler() {
  addInstrumentationHandler("unhandledrejection", function(e2) {
    var _a2 = __read$6(getHubAndAttachStacktrace(), 2), hub = _a2[0], attachStacktrace = _a2[1];
    if (!hub.getIntegration(GlobalHandlers)) {
      return;
    }
    var error = e2;
    try {
      if ("reason" in e2) {
        error = e2.reason;
      } else if ("detail" in e2 && "reason" in e2.detail) {
        error = e2.detail.reason;
      }
    } catch (_oO) {
    }
    if (shouldIgnoreOnError() || error && error.__sentry_own_request__) {
      return true;
    }
    var event = isPrimitive$1(error) ? _eventFromRejectionWithPrimitive(error) : eventFromUnknownInput(error, void 0, {
      attachStacktrace,
      isRejection: true
    });
    event.level = Severity.Error;
    addMechanismAndCapture(hub, error, event, "onunhandledrejection");
    return;
  });
}
function _eventFromRejectionWithPrimitive(reason) {
  return {
    exception: {
      values: [
        {
          type: "UnhandledRejection",
          value: "Non-Error promise rejection captured with value: " + String(reason)
        }
      ]
    }
  };
}
function _eventFromIncompleteOnError(msg, url, line, column) {
  var ERROR_TYPES_RE = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;
  var message = isErrorEvent(msg) ? msg.message : msg;
  var name = "Error";
  var groups = message.match(ERROR_TYPES_RE);
  if (groups) {
    name = groups[1];
    message = groups[2];
  }
  var event = {
    exception: {
      values: [
        {
          type: name,
          value: message
        }
      ]
    }
  };
  return _enhanceEventWithInitialFrame(event, url, line, column);
}
function _enhanceEventWithInitialFrame(event, url, line, column) {
  var e2 = event.exception = event.exception || {};
  var ev = e2.values = e2.values || [];
  var ev0 = ev[0] = ev[0] || {};
  var ev0s = ev0.stacktrace = ev0.stacktrace || {};
  var ev0sf = ev0s.frames = ev0s.frames || [];
  var colno = isNaN(parseInt(column, 10)) ? void 0 : column;
  var lineno = isNaN(parseInt(line, 10)) ? void 0 : line;
  var filename = isString$1(url) && url.length > 0 ? url : getLocationHref();
  if (ev0sf.length === 0) {
    ev0sf.push({
      colno,
      filename,
      function: "?",
      in_app: true,
      lineno
    });
  }
  return event;
}
function globalHandlerLog(type) {
  if (isDebugBuild()) {
    logger.log("Global Handler attached: " + type);
  }
}
function addMechanismAndCapture(hub, error, event, type) {
  addExceptionMechanism(event, {
    handled: false,
    type
  });
  hub.captureEvent(event, {
    originalException: error
  });
}
function getHubAndAttachStacktrace() {
  var hub = getCurrentHub();
  var client = hub.getClient();
  var attachStacktrace = client && client.getOptions().attachStacktrace;
  return [hub, attachStacktrace];
}
var DEFAULT_EVENT_TARGET = [
  "EventTarget",
  "Window",
  "Node",
  "ApplicationCache",
  "AudioTrackList",
  "ChannelMergerNode",
  "CryptoOperation",
  "EventSource",
  "FileReader",
  "HTMLUnknownElement",
  "IDBDatabase",
  "IDBRequest",
  "IDBTransaction",
  "KeyOperation",
  "MediaController",
  "MessagePort",
  "ModalWindow",
  "Notification",
  "SVGElementInstance",
  "Screen",
  "TextTrack",
  "TextTrackCue",
  "TextTrackList",
  "WebSocket",
  "WebSocketWorker",
  "Worker",
  "XMLHttpRequest",
  "XMLHttpRequestEventTarget",
  "XMLHttpRequestUpload"
];
var TryCatch = function() {
  function TryCatch2(options) {
    this.name = TryCatch2.id;
    this._options = __assign$5({ XMLHttpRequest: true, eventTarget: true, requestAnimationFrame: true, setInterval: true, setTimeout: true }, options);
  }
  TryCatch2.prototype.setupOnce = function() {
    var global2 = getGlobalObject();
    if (this._options.setTimeout) {
      fill(global2, "setTimeout", _wrapTimeFunction);
    }
    if (this._options.setInterval) {
      fill(global2, "setInterval", _wrapTimeFunction);
    }
    if (this._options.requestAnimationFrame) {
      fill(global2, "requestAnimationFrame", _wrapRAF);
    }
    if (this._options.XMLHttpRequest && "XMLHttpRequest" in global2) {
      fill(XMLHttpRequest.prototype, "send", _wrapXHR);
    }
    var eventTargetOption = this._options.eventTarget;
    if (eventTargetOption) {
      var eventTarget = Array.isArray(eventTargetOption) ? eventTargetOption : DEFAULT_EVENT_TARGET;
      eventTarget.forEach(_wrapEventTarget);
    }
  };
  TryCatch2.id = "TryCatch";
  return TryCatch2;
}();
function _wrapTimeFunction(original) {
  return function() {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
      args[_i] = arguments[_i];
    }
    var originalCallback = args[0];
    args[0] = wrap(originalCallback, {
      mechanism: {
        data: { function: getFunctionName(original) },
        handled: true,
        type: "instrument"
      }
    });
    return original.apply(this, args);
  };
}
function _wrapRAF(original) {
  return function(callback) {
    return original.call(this, wrap(callback, {
      mechanism: {
        data: {
          function: "requestAnimationFrame",
          handler: getFunctionName(original)
        },
        handled: true,
        type: "instrument"
      }
    }));
  };
}
function _wrapXHR(originalSend) {
  return function() {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
      args[_i] = arguments[_i];
    }
    var xhr = this;
    var xmlHttpRequestProps = ["onload", "onerror", "onprogress", "onreadystatechange"];
    xmlHttpRequestProps.forEach(function(prop) {
      if (prop in xhr && typeof xhr[prop] === "function") {
        fill(xhr, prop, function(original) {
          var wrapOptions = {
            mechanism: {
              data: {
                function: prop,
                handler: getFunctionName(original)
              },
              handled: true,
              type: "instrument"
            }
          };
          var originalFunction = getOriginalFunction(original);
          if (originalFunction) {
            wrapOptions.mechanism.data.handler = getFunctionName(originalFunction);
          }
          return wrap(original, wrapOptions);
        });
      }
    });
    return originalSend.apply(this, args);
  };
}
function _wrapEventTarget(target) {
  var global2 = getGlobalObject();
  var proto = global2[target] && global2[target].prototype;
  if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty("addEventListener")) {
    return;
  }
  fill(proto, "addEventListener", function(original) {
    return function(eventName, fn2, options) {
      try {
        if (typeof fn2.handleEvent === "function") {
          fn2.handleEvent = wrap(fn2.handleEvent.bind(fn2), {
            mechanism: {
              data: {
                function: "handleEvent",
                handler: getFunctionName(fn2),
                target
              },
              handled: true,
              type: "instrument"
            }
          });
        }
      } catch (err) {
      }
      return original.call(this, eventName, wrap(fn2, {
        mechanism: {
          data: {
            function: "addEventListener",
            handler: getFunctionName(fn2),
            target
          },
          handled: true,
          type: "instrument"
        }
      }), options);
    };
  });
  fill(proto, "removeEventListener", function(originalRemoveEventListener) {
    return function(eventName, fn2, options) {
      var wrappedEventHandler = fn2;
      try {
        var originalEventHandler = wrappedEventHandler && wrappedEventHandler.__sentry_wrapped__;
        if (originalEventHandler) {
          originalRemoveEventListener.call(this, eventName, originalEventHandler, options);
        }
      } catch (e2) {
      }
      return originalRemoveEventListener.call(this, eventName, wrappedEventHandler, options);
    };
  });
}
var Breadcrumbs = function() {
  function Breadcrumbs2(options) {
    this.name = Breadcrumbs2.id;
    this._options = __assign$5({ console: true, dom: true, fetch: true, history: true, sentry: true, xhr: true }, options);
  }
  Breadcrumbs2.prototype.addSentryBreadcrumb = function(event) {
    if (!this._options.sentry) {
      return;
    }
    getCurrentHub().addBreadcrumb({
      category: "sentry." + (event.type === "transaction" ? "transaction" : "event"),
      event_id: event.event_id,
      level: event.level,
      message: getEventDescription(event)
    }, {
      event
    });
  };
  Breadcrumbs2.prototype.setupOnce = function() {
    if (this._options.console) {
      addInstrumentationHandler("console", _consoleBreadcrumb);
    }
    if (this._options.dom) {
      addInstrumentationHandler("dom", _domBreadcrumb(this._options.dom));
    }
    if (this._options.xhr) {
      addInstrumentationHandler("xhr", _xhrBreadcrumb);
    }
    if (this._options.fetch) {
      addInstrumentationHandler("fetch", _fetchBreadcrumb);
    }
    if (this._options.history) {
      addInstrumentationHandler("history", _historyBreadcrumb);
    }
  };
  Breadcrumbs2.id = "Breadcrumbs";
  return Breadcrumbs2;
}();
function _domBreadcrumb(dom) {
  function _innerDomBreadcrumb(handlerData) {
    var target;
    var keyAttrs = typeof dom === "object" ? dom.serializeAttribute : void 0;
    if (typeof keyAttrs === "string") {
      keyAttrs = [keyAttrs];
    }
    try {
      target = handlerData.event.target ? htmlTreeAsString(handlerData.event.target, keyAttrs) : htmlTreeAsString(handlerData.event, keyAttrs);
    } catch (e2) {
      target = "<unknown>";
    }
    if (target.length === 0) {
      return;
    }
    getCurrentHub().addBreadcrumb({
      category: "ui." + handlerData.name,
      message: target
    }, {
      event: handlerData.event,
      name: handlerData.name,
      global: handlerData.global
    });
  }
  return _innerDomBreadcrumb;
}
function _consoleBreadcrumb(handlerData) {
  var breadcrumb = {
    category: "console",
    data: {
      arguments: handlerData.args,
      logger: "console"
    },
    level: severityFromString(handlerData.level),
    message: safeJoin(handlerData.args, " ")
  };
  if (handlerData.level === "assert") {
    if (handlerData.args[0] === false) {
      breadcrumb.message = "Assertion failed: " + (safeJoin(handlerData.args.slice(1), " ") || "console.assert");
      breadcrumb.data.arguments = handlerData.args.slice(1);
    } else {
      return;
    }
  }
  getCurrentHub().addBreadcrumb(breadcrumb, {
    input: handlerData.args,
    level: handlerData.level
  });
}
function _xhrBreadcrumb(handlerData) {
  if (handlerData.endTimestamp) {
    if (handlerData.xhr.__sentry_own_request__) {
      return;
    }
    var _a2 = handlerData.xhr.__sentry_xhr__ || {}, method = _a2.method, url = _a2.url, status_code = _a2.status_code, body = _a2.body;
    getCurrentHub().addBreadcrumb({
      category: "xhr",
      data: {
        method,
        url,
        status_code
      },
      type: "http"
    }, {
      xhr: handlerData.xhr,
      input: body
    });
    return;
  }
}
function _fetchBreadcrumb(handlerData) {
  if (!handlerData.endTimestamp) {
    return;
  }
  if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === "POST") {
    return;
  }
  if (handlerData.error) {
    getCurrentHub().addBreadcrumb({
      category: "fetch",
      data: handlerData.fetchData,
      level: Severity.Error,
      type: "http"
    }, {
      data: handlerData.error,
      input: handlerData.args
    });
  } else {
    getCurrentHub().addBreadcrumb({
      category: "fetch",
      data: __assign$5(__assign$5({}, handlerData.fetchData), { status_code: handlerData.response.status }),
      type: "http"
    }, {
      input: handlerData.args,
      response: handlerData.response
    });
  }
}
function _historyBreadcrumb(handlerData) {
  var global2 = getGlobalObject();
  var from = handlerData.from;
  var to = handlerData.to;
  var parsedLoc = parseUrl(global2.location.href);
  var parsedFrom = parseUrl(from);
  var parsedTo = parseUrl(to);
  if (!parsedFrom.path) {
    parsedFrom = parsedLoc;
  }
  if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) {
    to = parsedTo.relative;
  }
  if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) {
    from = parsedFrom.relative;
  }
  getCurrentHub().addBreadcrumb({
    category: "navigation",
    data: {
      from,
      to
    }
  });
}
var DEFAULT_KEY = "cause";
var DEFAULT_LIMIT = 5;
var LinkedErrors = function() {
  function LinkedErrors2(options) {
    if (options === void 0) {
      options = {};
    }
    this.name = LinkedErrors2.id;
    this._key = options.key || DEFAULT_KEY;
    this._limit = options.limit || DEFAULT_LIMIT;
  }
  LinkedErrors2.prototype.setupOnce = function() {
    addGlobalEventProcessor(function(event, hint) {
      var self2 = getCurrentHub().getIntegration(LinkedErrors2);
      return self2 ? _handler(self2._key, self2._limit, event, hint) : event;
    });
  };
  LinkedErrors2.id = "LinkedErrors";
  return LinkedErrors2;
}();
function _handler(key, limit, event, hint) {
  if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) {
    return event;
  }
  var linkedErrors = _walkErrorTree(limit, hint.originalException, key);
  event.exception.values = __spread$5(linkedErrors, event.exception.values);
  return event;
}
function _walkErrorTree(limit, error, key, stack) {
  if (stack === void 0) {
    stack = [];
  }
  if (!isInstanceOf(error[key], Error) || stack.length + 1 >= limit) {
    return stack;
  }
  var exception = exceptionFromError(error[key]);
  return _walkErrorTree(limit, error[key], key, __spread$5([exception], stack));
}
var global$4 = getGlobalObject();
var UserAgent = function() {
  function UserAgent2() {
    this.name = UserAgent2.id;
  }
  UserAgent2.prototype.setupOnce = function() {
    addGlobalEventProcessor(function(event) {
      if (getCurrentHub().getIntegration(UserAgent2)) {
        if (!global$4.navigator && !global$4.location && !global$4.document) {
          return event;
        }
        var url = event.request && event.request.url || global$4.location && global$4.location.href;
        var referrer = (global$4.document || {}).referrer;
        var userAgent = (global$4.navigator || {}).userAgent;
        var headers = __assign$5(__assign$5(__assign$5({}, event.request && event.request.headers), referrer && { Referer: referrer }), userAgent && { "User-Agent": userAgent });
        var request = __assign$5(__assign$5({}, url && { url }), { headers });
        return __assign$5(__assign$5({}, event), { request });
      }
      return event;
    });
  };
  UserAgent2.id = "UserAgent";
  return UserAgent2;
}();
var Dedupe = function() {
  function Dedupe2() {
    this.name = Dedupe2.id;
  }
  Dedupe2.prototype.setupOnce = function(addGlobalEventProcessor2, getCurrentHub2) {
    addGlobalEventProcessor2(function(currentEvent) {
      var self2 = getCurrentHub2().getIntegration(Dedupe2);
      if (self2) {
        try {
          if (_shouldDropEvent(currentEvent, self2._previousEvent)) {
            logger.warn("Event dropped due to being a duplicate of previously captured event.");
            return null;
          }
        } catch (_oO) {
          return self2._previousEvent = currentEvent;
        }
        return self2._previousEvent = currentEvent;
      }
      return currentEvent;
    });
  };
  Dedupe2.id = "Dedupe";
  return Dedupe2;
}();
function _shouldDropEvent(currentEvent, previousEvent) {
  if (!previousEvent) {
    return false;
  }
  if (_isSameMessageEvent(currentEvent, previousEvent)) {
    return true;
  }
  if (_isSameExceptionEvent(currentEvent, previousEvent)) {
    return true;
  }
  return false;
}
function _isSameMessageEvent(currentEvent, previousEvent) {
  var currentMessage = currentEvent.message;
  var previousMessage = previousEvent.message;
  if (!currentMessage && !previousMessage) {
    return false;
  }
  if (currentMessage && !previousMessage || !currentMessage && previousMessage) {
    return false;
  }
  if (currentMessage !== previousMessage) {
    return false;
  }
  if (!_isSameFingerprint(currentEvent, previousEvent)) {
    return false;
  }
  if (!_isSameStacktrace(currentEvent, previousEvent)) {
    return false;
  }
  return true;
}
function _isSameExceptionEvent(currentEvent, previousEvent) {
  var previousException = _getExceptionFromEvent(previousEvent);
  var currentException = _getExceptionFromEvent(currentEvent);
  if (!previousException || !currentException) {
    return false;
  }
  if (previousException.type !== currentException.type || previousException.value !== currentException.value) {
    return false;
  }
  if (!_isSameFingerprint(currentEvent, previousEvent)) {
    return false;
  }
  if (!_isSameStacktrace(currentEvent, previousEvent)) {
    return false;
  }
  return true;
}
function _isSameStacktrace(currentEvent, previousEvent) {
  var currentFrames = _getFramesFromEvent(currentEvent);
  var previousFrames = _getFramesFromEvent(previousEvent);
  if (!currentFrames && !previousFrames) {
    return true;
  }
  if (currentFrames && !previousFrames || !currentFrames && previousFrames) {
    return false;
  }
  currentFrames = currentFrames;
  previousFrames = previousFrames;
  if (previousFrames.length !== currentFrames.length) {
    return false;
  }
  for (var i2 = 0; i2 < previousFrames.length; i2++) {
    var frameA = previousFrames[i2];
    var frameB = currentFrames[i2];
    if (frameA.filename !== frameB.filename || frameA.lineno !== frameB.lineno || frameA.colno !== frameB.colno || frameA.function !== frameB.function) {
      return false;
    }
  }
  return true;
}
function _isSameFingerprint(currentEvent, previousEvent) {
  var currentFingerprint = currentEvent.fingerprint;
  var previousFingerprint = previousEvent.fingerprint;
  if (!currentFingerprint && !previousFingerprint) {
    return true;
  }
  if (currentFingerprint && !previousFingerprint || !currentFingerprint && previousFingerprint) {
    return false;
  }
  currentFingerprint = currentFingerprint;
  previousFingerprint = previousFingerprint;
  try {
    return !!(currentFingerprint.join("") === previousFingerprint.join(""));
  } catch (_oO) {
    return false;
  }
}
function _getExceptionFromEvent(event) {
  return event.exception && event.exception.values && event.exception.values[0];
}
function _getFramesFromEvent(event) {
  var exception = event.exception;
  if (exception) {
    try {
      return exception.values[0].stacktrace.frames;
    } catch (_oO) {
      return void 0;
    }
  } else if (event.stacktrace) {
    return event.stacktrace.frames;
  }
  return void 0;
}
var BrowserClient = function(_super) {
  __extends$3(BrowserClient2, _super);
  function BrowserClient2(options) {
    if (options === void 0) {
      options = {};
    }
    var _this = this;
    options._metadata = options._metadata || {};
    options._metadata.sdk = options._metadata.sdk || {
      name: "sentry.javascript.browser",
      packages: [
        {
          name: "npm:@sentry/browser",
          version: SDK_VERSION
        }
      ],
      version: SDK_VERSION
    };
    _this = _super.call(this, BrowserBackend, options) || this;
    return _this;
  }
  BrowserClient2.prototype.showReportDialog = function(options) {
    if (options === void 0) {
      options = {};
    }
    var document2 = getGlobalObject().document;
    if (!document2) {
      return;
    }
    if (!this._isEnabled()) {
      logger.error("Trying to call showReportDialog with Sentry Client disabled");
      return;
    }
    injectReportDialog(__assign$5(__assign$5({}, options), { dsn: options.dsn || this.getDsn() }));
  };
  BrowserClient2.prototype._prepareEvent = function(event, scope, hint) {
    event.platform = event.platform || "javascript";
    return _super.prototype._prepareEvent.call(this, event, scope, hint);
  };
  BrowserClient2.prototype._sendEvent = function(event) {
    var integration = this.getIntegration(Breadcrumbs);
    if (integration) {
      integration.addSentryBreadcrumb(event);
    }
    _super.prototype._sendEvent.call(this, event);
  };
  return BrowserClient2;
}(BaseClient);
var defaultIntegrations = [
  new InboundFilters(),
  new FunctionToString(),
  new TryCatch(),
  new Breadcrumbs(),
  new GlobalHandlers(),
  new LinkedErrors(),
  new Dedupe(),
  new UserAgent()
];
function init$1(options) {
  if (options === void 0) {
    options = {};
  }
  if (options.defaultIntegrations === void 0) {
    options.defaultIntegrations = defaultIntegrations;
  }
  if (options.release === void 0) {
    var window_1 = getGlobalObject();
    if (window_1.SENTRY_RELEASE && window_1.SENTRY_RELEASE.id) {
      options.release = window_1.SENTRY_RELEASE.id;
    }
  }
  if (options.autoSessionTracking === void 0) {
    options.autoSessionTracking = true;
  }
  if (options.sendClientReports === void 0) {
    options.sendClientReports = true;
  }
  initAndBind(BrowserClient, options);
  if (options.autoSessionTracking) {
    startSessionTracking();
  }
}
function startSessionOnHub(hub) {
  hub.startSession({ ignoreDuration: true });
  hub.captureSession();
}
function startSessionTracking() {
  var window2 = getGlobalObject();
  var document2 = window2.document;
  if (typeof document2 === "undefined") {
    if (isDebugBuild()) {
      logger.warn("Session tracking in non-browser environment with @sentry/browser is not supported.");
    }
    return;
  }
  var hub = getCurrentHub();
  if (!hub.captureSession) {
    return;
  }
  startSessionOnHub(hub);
  addInstrumentationHandler("history", function(_a2) {
    var from = _a2.from, to = _a2.to;
    if (!(from === void 0 || from === to)) {
      startSessionOnHub(getCurrentHub());
    }
  });
}
function init(options) {
  options._metadata = options._metadata || {};
  options._metadata.sdk = options._metadata.sdk || {
    name: "sentry.javascript.react",
    packages: [
      {
        name: "npm:@sentry/react",
        version: SDK_VERSION
      }
    ],
    version: SDK_VERSION
  };
  init$1(options);
}
var reactIs$1 = { exports: {} };
var reactIs_production_min = {};
/** @license React v16.13.1
 * react-is.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
var b$5 = typeof Symbol === "function" && Symbol.for, c$6 = b$5 ? Symbol.for("react.element") : 60103, d$4 = b$5 ? Symbol.for("react.portal") : 60106, e$2 = b$5 ? Symbol.for("react.fragment") : 60107, f$5 = b$5 ? Symbol.for("react.strict_mode") : 60108, g$5 = b$5 ? Symbol.for("react.profiler") : 60114, h$6 = b$5 ? Symbol.for("react.provider") : 60109, k$1 = b$5 ? Symbol.for("react.context") : 60110, l$4 = b$5 ? Symbol.for("react.async_mode") : 60111, m$4 = b$5 ? Symbol.for("react.concurrent_mode") : 60111, n$5 = b$5 ? Symbol.for("react.forward_ref") : 60112, p$5 = b$5 ? Symbol.for("react.suspense") : 60113, q$3 = b$5 ? Symbol.for("react.suspense_list") : 60120, r$3 = b$5 ? Symbol.for("react.memo") : 60115, t$3 = b$5 ? Symbol.for("react.lazy") : 60116, v$3 = b$5 ? Symbol.for("react.block") : 60121, w$3 = b$5 ? Symbol.for("react.fundamental") : 60117, x$4 = b$5 ? Symbol.for("react.responder") : 60118, y$3 = b$5 ? Symbol.for("react.scope") : 60119;
function z$2(a2) {
  if (typeof a2 === "object" && a2 !== null) {
    var u2 = a2.$$typeof;
    switch (u2) {
      case c$6:
        switch (a2 = a2.type, a2) {
          case l$4:
          case m$4:
          case e$2:
          case g$5:
          case f$5:
          case p$5:
            return a2;
          default:
            switch (a2 = a2 && a2.$$typeof, a2) {
              case k$1:
              case n$5:
              case t$3:
              case r$3:
              case h$6:
                return a2;
              default:
                return u2;
            }
        }
      case d$4:
        return u2;
    }
  }
}
function A$2(a2) {
  return z$2(a2) === m$4;
}
reactIs_production_min.AsyncMode = l$4;
reactIs_production_min.ConcurrentMode = m$4;
reactIs_production_min.ContextConsumer = k$1;
reactIs_production_min.ContextProvider = h$6;
reactIs_production_min.Element = c$6;
reactIs_production_min.ForwardRef = n$5;
reactIs_production_min.Fragment = e$2;
reactIs_production_min.Lazy = t$3;
reactIs_production_min.Memo = r$3;
reactIs_production_min.Portal = d$4;
reactIs_production_min.Profiler = g$5;
reactIs_production_min.StrictMode = f$5;
reactIs_production_min.Suspense = p$5;
reactIs_production_min.isAsyncMode = function(a2) {
  return A$2(a2) || z$2(a2) === l$4;
};
reactIs_production_min.isConcurrentMode = A$2;
reactIs_production_min.isContextConsumer = function(a2) {
  return z$2(a2) === k$1;
};
reactIs_production_min.isContextProvider = function(a2) {
  return z$2(a2) === h$6;
};
reactIs_production_min.isElement = function(a2) {
  return typeof a2 === "object" && a2 !== null && a2.$$typeof === c$6;
};
reactIs_production_min.isForwardRef = function(a2) {
  return z$2(a2) === n$5;
};
reactIs_production_min.isFragment = function(a2) {
  return z$2(a2) === e$2;
};
reactIs_production_min.isLazy = function(a2) {
  return z$2(a2) === t$3;
};
reactIs_production_min.isMemo = function(a2) {
  return z$2(a2) === r$3;
};
reactIs_production_min.isPortal = function(a2) {
  return z$2(a2) === d$4;
};
reactIs_production_min.isProfiler = function(a2) {
  return z$2(a2) === g$5;
};
reactIs_production_min.isStrictMode = function(a2) {
  return z$2(a2) === f$5;
};
reactIs_production_min.isSuspense = function(a2) {
  return z$2(a2) === p$5;
};
reactIs_production_min.isValidElementType = function(a2) {
  return typeof a2 === "string" || typeof a2 === "function" || a2 === e$2 || a2 === m$4 || a2 === g$5 || a2 === f$5 || a2 === p$5 || a2 === q$3 || typeof a2 === "object" && a2 !== null && (a2.$$typeof === t$3 || a2.$$typeof === r$3 || a2.$$typeof === h$6 || a2.$$typeof === k$1 || a2.$$typeof === n$5 || a2.$$typeof === w$3 || a2.$$typeof === x$4 || a2.$$typeof === y$3 || a2.$$typeof === v$3);
};
reactIs_production_min.typeOf = z$2;
{
  reactIs$1.exports = reactIs_production_min;
}
var reactIs = reactIs$1.exports;
var FORWARD_REF_STATICS = {
  "$$typeof": true,
  render: true,
  defaultProps: true,
  displayName: true,
  propTypes: true
};
var MEMO_STATICS = {
  "$$typeof": true,
  compare: true,
  defaultProps: true,
  displayName: true,
  propTypes: true,
  type: true
};
var TYPE_STATICS = {};
TYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS;
TYPE_STATICS[reactIs.Memo] = MEMO_STATICS;
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
var extendStatics$1 = function(d2, b2) {
  extendStatics$1 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d3, b3) {
    d3.__proto__ = b3;
  } || function(d3, b3) {
    for (var p2 in b3)
      if (b3.hasOwnProperty(p2))
        d3[p2] = b3[p2];
  };
  return extendStatics$1(d2, b2);
};
function __extends$1(d2, b2) {
  extendStatics$1(d2, b2);
  function __() {
    this.constructor = d2;
  }
  d2.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __());
}
var __assign$1 = function() {
  __assign$1 = Object.assign || function __assign2(t2) {
    for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
      s2 = arguments[i2];
      for (var p2 in s2)
        if (Object.prototype.hasOwnProperty.call(s2, p2))
          t2[p2] = s2[p2];
    }
    return t2;
  };
  return __assign$1.apply(this, arguments);
};
function __rest$1(s2, e2) {
  var t2 = {};
  for (var p2 in s2)
    if (Object.prototype.hasOwnProperty.call(s2, p2) && e2.indexOf(p2) < 0)
      t2[p2] = s2[p2];
  if (s2 != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i2 = 0, p2 = Object.getOwnPropertySymbols(s2); i2 < p2.length; i2++) {
      if (e2.indexOf(p2[i2]) < 0 && Object.prototype.propertyIsEnumerable.call(s2, p2[i2]))
        t2[p2[i2]] = s2[p2[i2]];
    }
  return t2;
}
function __values$1(o2) {
  var s2 = typeof Symbol === "function" && Symbol.iterator, m2 = s2 && o2[s2], i2 = 0;
  if (m2)
    return m2.call(o2);
  if (o2 && typeof o2.length === "number")
    return {
      next: function() {
        if (o2 && i2 >= o2.length)
          o2 = void 0;
        return { value: o2 && o2[i2++], done: !o2 };
      }
    };
  throw new TypeError(s2 ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read$1(o2, n2) {
  var m2 = typeof Symbol === "function" && o2[Symbol.iterator];
  if (!m2)
    return o2;
  var i2 = m2.call(o2), r2, ar = [], e2;
  try {
    while ((n2 === void 0 || n2-- > 0) && !(r2 = i2.next()).done)
      ar.push(r2.value);
  } catch (error) {
    e2 = { error };
  } finally {
    try {
      if (r2 && !r2.done && (m2 = i2["return"]))
        m2.call(i2);
    } finally {
      if (e2)
        throw e2.error;
    }
  }
  return ar;
}
function __spread$1() {
  for (var ar = [], i2 = 0; i2 < arguments.length; i2++)
    ar = ar.concat(__read$1(arguments[i2]));
  return ar;
}
var TRACEPARENT_REGEXP = new RegExp("^[ \\t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \\t]*$");
function hasTracingEnabled(maybeOptions) {
  var client = getCurrentHub().getClient();
  var options = maybeOptions || client && client.getOptions();
  return !!options && ("tracesSampleRate" in options || "tracesSampler" in options);
}
function extractTraceparentData(traceparent) {
  var matches = traceparent.match(TRACEPARENT_REGEXP);
  if (matches) {
    var parentSampled = void 0;
    if (matches[3] === "1") {
      parentSampled = true;
    } else if (matches[3] === "0") {
      parentSampled = false;
    }
    return {
      traceId: matches[1],
      parentSampled,
      parentSpanId: matches[2]
    };
  }
  return void 0;
}
function getActiveTransaction(maybeHub) {
  var hub = maybeHub || getCurrentHub();
  var scope = hub.getScope();
  return scope && scope.getTransaction();
}
function msToSec(time) {
  return time / 1e3;
}
function secToMs(time) {
  return time * 1e3;
}
function registerErrorInstrumentation() {
  addInstrumentationHandler("error", errorCallback);
  addInstrumentationHandler("unhandledrejection", errorCallback);
}
function errorCallback() {
  var activeTransaction = getActiveTransaction();
  if (activeTransaction) {
    var status_1 = "internal_error";
    logger.log("[Tracing] Transaction: " + status_1 + " -> Global error occured");
    activeTransaction.setStatus(status_1);
  }
}
var FINISH_REASON_TAG = "finishReason";
var IDLE_TRANSACTION_FINISH_REASONS = ["heartbeatFailed", "idleTimeout", "documentHidden"];
var SpanRecorder = function() {
  function SpanRecorder2(maxlen) {
    if (maxlen === void 0) {
      maxlen = 1e3;
    }
    this.spans = [];
    this._maxlen = maxlen;
  }
  SpanRecorder2.prototype.add = function(span) {
    if (this.spans.length > this._maxlen) {
      span.spanRecorder = void 0;
    } else {
      this.spans.push(span);
    }
  };
  return SpanRecorder2;
}();
var Span = function() {
  function Span2(spanContext) {
    this.traceId = uuid4();
    this.spanId = uuid4().substring(16);
    this.startTimestamp = timestampWithMs();
    this.tags = {};
    this.data = {};
    if (!spanContext) {
      return this;
    }
    if (spanContext.traceId) {
      this.traceId = spanContext.traceId;
    }
    if (spanContext.spanId) {
      this.spanId = spanContext.spanId;
    }
    if (spanContext.parentSpanId) {
      this.parentSpanId = spanContext.parentSpanId;
    }
    if ("sampled" in spanContext) {
      this.sampled = spanContext.sampled;
    }
    if (spanContext.op) {
      this.op = spanContext.op;
    }
    if (spanContext.description) {
      this.description = spanContext.description;
    }
    if (spanContext.data) {
      this.data = spanContext.data;
    }
    if (spanContext.tags) {
      this.tags = spanContext.tags;
    }
    if (spanContext.status) {
      this.status = spanContext.status;
    }
    if (spanContext.startTimestamp) {
      this.startTimestamp = spanContext.startTimestamp;
    }
    if (spanContext.endTimestamp) {
      this.endTimestamp = spanContext.endTimestamp;
    }
  }
  Span2.prototype.child = function(spanContext) {
    return this.startChild(spanContext);
  };
  Span2.prototype.startChild = function(spanContext) {
    var childSpan = new Span2(__assign$1(__assign$1({}, spanContext), { parentSpanId: this.spanId, sampled: this.sampled, traceId: this.traceId }));
    childSpan.spanRecorder = this.spanRecorder;
    if (childSpan.spanRecorder) {
      childSpan.spanRecorder.add(childSpan);
    }
    childSpan.transaction = this.transaction;
    return childSpan;
  };
  Span2.prototype.setTag = function(key, value) {
    var _a2;
    this.tags = __assign$1(__assign$1({}, this.tags), (_a2 = {}, _a2[key] = value, _a2));
    return this;
  };
  Span2.prototype.setData = function(key, value) {
    var _a2;
    this.data = __assign$1(__assign$1({}, this.data), (_a2 = {}, _a2[key] = value, _a2));
    return this;
  };
  Span2.prototype.setStatus = function(value) {
    this.status = value;
    return this;
  };
  Span2.prototype.setHttpStatus = function(httpStatus) {
    this.setTag("http.status_code", String(httpStatus));
    var spanStatus = spanStatusfromHttpCode(httpStatus);
    if (spanStatus !== "unknown_error") {
      this.setStatus(spanStatus);
    }
    return this;
  };
  Span2.prototype.isSuccess = function() {
    return this.status === "ok";
  };
  Span2.prototype.finish = function(endTimestamp) {
    this.endTimestamp = typeof endTimestamp === "number" ? endTimestamp : timestampWithMs();
  };
  Span2.prototype.toTraceparent = function() {
    var sampledString = "";
    if (this.sampled !== void 0) {
      sampledString = this.sampled ? "-1" : "-0";
    }
    return this.traceId + "-" + this.spanId + sampledString;
  };
  Span2.prototype.toContext = function() {
    return dropUndefinedKeys({
      data: this.data,
      description: this.description,
      endTimestamp: this.endTimestamp,
      op: this.op,
      parentSpanId: this.parentSpanId,
      sampled: this.sampled,
      spanId: this.spanId,
      startTimestamp: this.startTimestamp,
      status: this.status,
      tags: this.tags,
      traceId: this.traceId
    });
  };
  Span2.prototype.updateWithContext = function(spanContext) {
    var _a2, _b, _c, _d, _e2;
    this.data = (_a2 = spanContext.data, _a2 !== null && _a2 !== void 0 ? _a2 : {});
    this.description = spanContext.description;
    this.endTimestamp = spanContext.endTimestamp;
    this.op = spanContext.op;
    this.parentSpanId = spanContext.parentSpanId;
    this.sampled = spanContext.sampled;
    this.spanId = (_b = spanContext.spanId, _b !== null && _b !== void 0 ? _b : this.spanId);
    this.startTimestamp = (_c = spanContext.startTimestamp, _c !== null && _c !== void 0 ? _c : this.startTimestamp);
    this.status = spanContext.status;
    this.tags = (_d = spanContext.tags, _d !== null && _d !== void 0 ? _d : {});
    this.traceId = (_e2 = spanContext.traceId, _e2 !== null && _e2 !== void 0 ? _e2 : this.traceId);
    return this;
  };
  Span2.prototype.getTraceContext = function() {
    return dropUndefinedKeys({
      data: Object.keys(this.data).length > 0 ? this.data : void 0,
      description: this.description,
      op: this.op,
      parent_span_id: this.parentSpanId,
      span_id: this.spanId,
      status: this.status,
      tags: Object.keys(this.tags).length > 0 ? this.tags : void 0,
      trace_id: this.traceId
    });
  };
  Span2.prototype.toJSON = function() {
    return dropUndefinedKeys({
      data: Object.keys(this.data).length > 0 ? this.data : void 0,
      description: this.description,
      op: this.op,
      parent_span_id: this.parentSpanId,
      span_id: this.spanId,
      start_timestamp: this.startTimestamp,
      status: this.status,
      tags: Object.keys(this.tags).length > 0 ? this.tags : void 0,
      timestamp: this.endTimestamp,
      trace_id: this.traceId
    });
  };
  return Span2;
}();
function spanStatusfromHttpCode(httpStatus) {
  if (httpStatus < 400 && httpStatus >= 100) {
    return "ok";
  }
  if (httpStatus >= 400 && httpStatus < 500) {
    switch (httpStatus) {
      case 401:
        return "unauthenticated";
      case 403:
        return "permission_denied";
      case 404:
        return "not_found";
      case 409:
        return "already_exists";
      case 413:
        return "failed_precondition";
      case 429:
        return "resource_exhausted";
      default:
        return "invalid_argument";
    }
  }
  if (httpStatus >= 500 && httpStatus < 600) {
    switch (httpStatus) {
      case 501:
        return "unimplemented";
      case 503:
        return "unavailable";
      case 504:
        return "deadline_exceeded";
      default:
        return "internal_error";
    }
  }
  return "unknown_error";
}
var Transaction = function(_super) {
  __extends$1(Transaction2, _super);
  function Transaction2(transactionContext, hub) {
    var _this = _super.call(this, transactionContext) || this;
    _this._measurements = {};
    _this._hub = getCurrentHub();
    if (isInstanceOf(hub, Hub)) {
      _this._hub = hub;
    }
    _this.name = transactionContext.name || "";
    _this.metadata = transactionContext.metadata || {};
    _this._trimEnd = transactionContext.trimEnd;
    _this.transaction = _this;
    return _this;
  }
  Transaction2.prototype.setName = function(name) {
    this.name = name;
  };
  Transaction2.prototype.initSpanRecorder = function(maxlen) {
    if (maxlen === void 0) {
      maxlen = 1e3;
    }
    if (!this.spanRecorder) {
      this.spanRecorder = new SpanRecorder(maxlen);
    }
    this.spanRecorder.add(this);
  };
  Transaction2.prototype.setMeasurements = function(measurements) {
    this._measurements = __assign$1({}, measurements);
  };
  Transaction2.prototype.setMetadata = function(newMetadata) {
    this.metadata = __assign$1(__assign$1({}, this.metadata), newMetadata);
  };
  Transaction2.prototype.finish = function(endTimestamp) {
    var _this = this;
    if (this.endTimestamp !== void 0) {
      return void 0;
    }
    if (!this.name) {
      logger.warn("Transaction has no name, falling back to `<unlabeled transaction>`.");
      this.name = "<unlabeled transaction>";
    }
    _super.prototype.finish.call(this, endTimestamp);
    if (this.sampled !== true) {
      logger.log("[Tracing] Discarding transaction because its trace was not chosen to be sampled.");
      var client = this._hub.getClient();
      var transport = client && client.getTransport && client.getTransport();
      if (transport && transport.recordLostEvent) {
        transport.recordLostEvent("sample_rate", "transaction");
      }
      return void 0;
    }
    var finishedSpans = this.spanRecorder ? this.spanRecorder.spans.filter(function(s2) {
      return s2 !== _this && s2.endTimestamp;
    }) : [];
    if (this._trimEnd && finishedSpans.length > 0) {
      this.endTimestamp = finishedSpans.reduce(function(prev, current) {
        if (prev.endTimestamp && current.endTimestamp) {
          return prev.endTimestamp > current.endTimestamp ? prev : current;
        }
        return prev;
      }).endTimestamp;
    }
    var transaction = {
      contexts: {
        trace: this.getTraceContext()
      },
      spans: finishedSpans,
      start_timestamp: this.startTimestamp,
      tags: this.tags,
      timestamp: this.endTimestamp,
      transaction: this.name,
      type: "transaction",
      sdkProcessingMetadata: this.metadata
    };
    var hasMeasurements = Object.keys(this._measurements).length > 0;
    if (hasMeasurements) {
      logger.log("[Measurements] Adding measurements to transaction", JSON.stringify(this._measurements, void 0, 2));
      transaction.measurements = this._measurements;
    }
    logger.log("[Tracing] Finishing " + this.op + " transaction: " + this.name + ".");
    return this._hub.captureEvent(transaction);
  };
  Transaction2.prototype.toContext = function() {
    var spanContext = _super.prototype.toContext.call(this);
    return dropUndefinedKeys(__assign$1(__assign$1({}, spanContext), { name: this.name, trimEnd: this._trimEnd }));
  };
  Transaction2.prototype.updateWithContext = function(transactionContext) {
    var _a2;
    _super.prototype.updateWithContext.call(this, transactionContext);
    this.name = (_a2 = transactionContext.name, _a2 !== null && _a2 !== void 0 ? _a2 : "");
    this._trimEnd = transactionContext.trimEnd;
    return this;
  };
  return Transaction2;
}(Span);
var DEFAULT_IDLE_TIMEOUT = 1e3;
var HEARTBEAT_INTERVAL = 5e3;
var IdleTransactionSpanRecorder = function(_super) {
  __extends$1(IdleTransactionSpanRecorder2, _super);
  function IdleTransactionSpanRecorder2(_pushActivity, _popActivity, transactionSpanId, maxlen) {
    if (transactionSpanId === void 0) {
      transactionSpanId = "";
    }
    var _this = _super.call(this, maxlen) || this;
    _this._pushActivity = _pushActivity;
    _this._popActivity = _popActivity;
    _this.transactionSpanId = transactionSpanId;
    return _this;
  }
  IdleTransactionSpanRecorder2.prototype.add = function(span) {
    var _this = this;
    if (span.spanId !== this.transactionSpanId) {
      span.finish = function(endTimestamp) {
        span.endTimestamp = typeof endTimestamp === "number" ? endTimestamp : timestampWithMs();
        _this._popActivity(span.spanId);
      };
      if (span.endTimestamp === void 0) {
        this._pushActivity(span.spanId);
      }
    }
    _super.prototype.add.call(this, span);
  };
  return IdleTransactionSpanRecorder2;
}(SpanRecorder);
var IdleTransaction = function(_super) {
  __extends$1(IdleTransaction2, _super);
  function IdleTransaction2(transactionContext, _idleHub, _idleTimeout, _onScope) {
    if (_idleTimeout === void 0) {
      _idleTimeout = DEFAULT_IDLE_TIMEOUT;
    }
    if (_onScope === void 0) {
      _onScope = false;
    }
    var _this = _super.call(this, transactionContext, _idleHub) || this;
    _this._idleHub = _idleHub;
    _this._idleTimeout = _idleTimeout;
    _this._onScope = _onScope;
    _this.activities = {};
    _this._heartbeatCounter = 0;
    _this._finished = false;
    _this._beforeFinishCallbacks = [];
    if (_idleHub && _onScope) {
      clearActiveTransaction(_idleHub);
      logger.log("Setting idle transaction on scope. Span ID: " + _this.spanId);
      _idleHub.configureScope(function(scope) {
        return scope.setSpan(_this);
      });
    }
    _this._initTimeout = setTimeout(function() {
      if (!_this._finished) {
        _this.finish();
      }
    }, _this._idleTimeout);
    return _this;
  }
  IdleTransaction2.prototype.finish = function(endTimestamp) {
    var e_1, _a2;
    var _this = this;
    if (endTimestamp === void 0) {
      endTimestamp = timestampWithMs();
    }
    this._finished = true;
    this.activities = {};
    if (this.spanRecorder) {
      logger.log("[Tracing] finishing IdleTransaction", new Date(endTimestamp * 1e3).toISOString(), this.op);
      try {
        for (var _b = __values$1(this._beforeFinishCallbacks), _c = _b.next(); !_c.done; _c = _b.next()) {
          var callback = _c.value;
          callback(this, endTimestamp);
        }
      } catch (e_1_1) {
        e_1 = { error: e_1_1 };
      } finally {
        try {
          if (_c && !_c.done && (_a2 = _b.return))
            _a2.call(_b);
        } finally {
          if (e_1)
            throw e_1.error;
        }
      }
      this.spanRecorder.spans = this.spanRecorder.spans.filter(function(span) {
        if (span.spanId === _this.spanId) {
          return true;
        }
        if (!span.endTimestamp) {
          span.endTimestamp = endTimestamp;
          span.setStatus("cancelled");
          logger.log("[Tracing] cancelling span since transaction ended early", JSON.stringify(span, void 0, 2));
        }
        var keepSpan = span.startTimestamp < endTimestamp;
        if (!keepSpan) {
          logger.log("[Tracing] discarding Span since it happened after Transaction was finished", JSON.stringify(span, void 0, 2));
        }
        return keepSpan;
      });
      logger.log("[Tracing] flushing IdleTransaction");
    } else {
      logger.log("[Tracing] No active IdleTransaction");
    }
    if (this._onScope) {
      clearActiveTransaction(this._idleHub);
    }
    return _super.prototype.finish.call(this, endTimestamp);
  };
  IdleTransaction2.prototype.registerBeforeFinishCallback = function(callback) {
    this._beforeFinishCallbacks.push(callback);
  };
  IdleTransaction2.prototype.initSpanRecorder = function(maxlen) {
    var _this = this;
    if (!this.spanRecorder) {
      var pushActivity = function(id2) {
        if (_this._finished) {
          return;
        }
        _this._pushActivity(id2);
      };
      var popActivity = function(id2) {
        if (_this._finished) {
          return;
        }
        _this._popActivity(id2);
      };
      this.spanRecorder = new IdleTransactionSpanRecorder(pushActivity, popActivity, this.spanId, maxlen);
      logger.log("Starting heartbeat");
      this._pingHeartbeat();
    }
    this.spanRecorder.add(this);
  };
  IdleTransaction2.prototype._pushActivity = function(spanId) {
    if (this._initTimeout) {
      clearTimeout(this._initTimeout);
      this._initTimeout = void 0;
    }
    logger.log("[Tracing] pushActivity: " + spanId);
    this.activities[spanId] = true;
    logger.log("[Tracing] new activities count", Object.keys(this.activities).length);
  };
  IdleTransaction2.prototype._popActivity = function(spanId) {
    var _this = this;
    if (this.activities[spanId]) {
      logger.log("[Tracing] popActivity " + spanId);
      delete this.activities[spanId];
      logger.log("[Tracing] new activities count", Object.keys(this.activities).length);
    }
    if (Object.keys(this.activities).length === 0) {
      var timeout = this._idleTimeout;
      var end_1 = timestampWithMs() + timeout / 1e3;
      setTimeout(function() {
        if (!_this._finished) {
          _this.setTag(FINISH_REASON_TAG, IDLE_TRANSACTION_FINISH_REASONS[1]);
          _this.finish(end_1);
        }
      }, timeout);
    }
  };
  IdleTransaction2.prototype._beat = function() {
    if (this._finished) {
      return;
    }
    var heartbeatString = Object.keys(this.activities).join("");
    if (heartbeatString === this._prevHeartbeatString) {
      this._heartbeatCounter += 1;
    } else {
      this._heartbeatCounter = 1;
    }
    this._prevHeartbeatString = heartbeatString;
    if (this._heartbeatCounter >= 3) {
      logger.log("[Tracing] Transaction finished because of no change for 3 heart beats");
      this.setStatus("deadline_exceeded");
      this.setTag(FINISH_REASON_TAG, IDLE_TRANSACTION_FINISH_REASONS[0]);
      this.finish();
    } else {
      this._pingHeartbeat();
    }
  };
  IdleTransaction2.prototype._pingHeartbeat = function() {
    var _this = this;
    logger.log("pinging Heartbeat -> current counter: " + this._heartbeatCounter);
    setTimeout(function() {
      _this._beat();
    }, HEARTBEAT_INTERVAL);
  };
  return IdleTransaction2;
}(Transaction);
function clearActiveTransaction(hub) {
  if (hub) {
    var scope = hub.getScope();
    if (scope) {
      var transaction = scope.getTransaction();
      if (transaction) {
        scope.setSpan(void 0);
      }
    }
  }
}
function traceHeaders() {
  var scope = this.getScope();
  if (scope) {
    var span = scope.getSpan();
    if (span) {
      return {
        "sentry-trace": span.toTraceparent()
      };
    }
  }
  return {};
}
function sample(transaction, options, samplingContext) {
  if (!hasTracingEnabled(options)) {
    transaction.sampled = false;
    return transaction;
  }
  if (transaction.sampled !== void 0) {
    transaction.setMetadata({
      transactionSampling: { method: "explicitly_set" }
    });
    return transaction;
  }
  var sampleRate;
  if (typeof options.tracesSampler === "function") {
    sampleRate = options.tracesSampler(samplingContext);
    transaction.setMetadata({
      transactionSampling: {
        method: "client_sampler",
        rate: Number(sampleRate)
      }
    });
  } else if (samplingContext.parentSampled !== void 0) {
    sampleRate = samplingContext.parentSampled;
    transaction.setMetadata({
      transactionSampling: { method: "inheritance" }
    });
  } else {
    sampleRate = options.tracesSampleRate;
    transaction.setMetadata({
      transactionSampling: {
        method: "client_rate",
        rate: Number(sampleRate)
      }
    });
  }
  if (!isValidSampleRate(sampleRate)) {
    logger.warn("[Tracing] Discarding transaction because of invalid sample rate.");
    transaction.sampled = false;
    return transaction;
  }
  if (!sampleRate) {
    logger.log("[Tracing] Discarding transaction because " + (typeof options.tracesSampler === "function" ? "tracesSampler returned 0 or false" : "a negative sampling decision was inherited or tracesSampleRate is set to 0"));
    transaction.sampled = false;
    return transaction;
  }
  transaction.sampled = Math.random() < sampleRate;
  if (!transaction.sampled) {
    logger.log("[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = " + Number(sampleRate) + ")");
    return transaction;
  }
  logger.log("[Tracing] starting " + transaction.op + " transaction - " + transaction.name);
  return transaction;
}
function isValidSampleRate(rate) {
  if (isNaN(rate) || !(typeof rate === "number" || typeof rate === "boolean")) {
    logger.warn("[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got " + JSON.stringify(rate) + " of type " + JSON.stringify(typeof rate) + ".");
    return false;
  }
  if (rate < 0 || rate > 1) {
    logger.warn("[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got " + rate + ".");
    return false;
  }
  return true;
}
function _startTransaction(transactionContext, customSamplingContext) {
  var client = this.getClient();
  var options = client && client.getOptions() || {};
  var transaction = new Transaction(transactionContext, this);
  transaction = sample(transaction, options, __assign$1({ parentSampled: transactionContext.parentSampled, transactionContext }, customSamplingContext));
  if (transaction.sampled) {
    transaction.initSpanRecorder(options._experiments && options._experiments.maxSpans);
  }
  return transaction;
}
function startIdleTransaction(hub, transactionContext, idleTimeout, onScope, customSamplingContext) {
  var client = hub.getClient();
  var options = client && client.getOptions() || {};
  var transaction = new IdleTransaction(transactionContext, hub, idleTimeout, onScope);
  transaction = sample(transaction, options, __assign$1({ parentSampled: transactionContext.parentSampled, transactionContext }, customSamplingContext));
  if (transaction.sampled) {
    transaction.initSpanRecorder(options._experiments && options._experiments.maxSpans);
  }
  return transaction;
}
function _addTracingExtensions() {
  var carrier = getMainCarrier();
  if (!carrier.__SENTRY__) {
    return;
  }
  carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {};
  if (!carrier.__SENTRY__.extensions.startTransaction) {
    carrier.__SENTRY__.extensions.startTransaction = _startTransaction;
  }
  if (!carrier.__SENTRY__.extensions.traceHeaders) {
    carrier.__SENTRY__.extensions.traceHeaders = traceHeaders;
  }
}
function _autoloadDatabaseIntegrations() {
  var carrier = getMainCarrier();
  if (!carrier.__SENTRY__) {
    return;
  }
  var packageToIntegrationMapping = {
    mongodb: function() {
      var integration = dynamicRequire(module, "./integrations/node/mongo");
      return new integration.Mongo();
    },
    mongoose: function() {
      var integration = dynamicRequire(module, "./integrations/node/mongo");
      return new integration.Mongo({ mongoose: true });
    },
    mysql: function() {
      var integration = dynamicRequire(module, "./integrations/node/mysql");
      return new integration.Mysql();
    },
    pg: function() {
      var integration = dynamicRequire(module, "./integrations/node/postgres");
      return new integration.Postgres();
    }
  };
  var mappedPackages = Object.keys(packageToIntegrationMapping).filter(function(moduleName) {
    return !!loadModule(moduleName);
  }).map(function(pkg) {
    try {
      return packageToIntegrationMapping[pkg]();
    } catch (e2) {
      return void 0;
    }
  }).filter(function(p2) {
    return p2;
  });
  if (mappedPackages.length > 0) {
    carrier.__SENTRY__.integrations = __spread$1(carrier.__SENTRY__.integrations || [], mappedPackages);
  }
}
function addExtensionMethods() {
  _addTracingExtensions();
  if (isNodeEnv()) {
    _autoloadDatabaseIntegrations();
  }
  registerErrorInstrumentation();
}
var global$3 = getGlobalObject();
function registerBackgroundTabDetection() {
  if (global$3 && global$3.document) {
    global$3.document.addEventListener("visibilitychange", function() {
      var activeTransaction = getActiveTransaction();
      if (global$3.document.hidden && activeTransaction) {
        var statusType = "cancelled";
        logger.log("[Tracing] Transaction: " + statusType + " -> since tab moved to the background, op: " + activeTransaction.op);
        if (!activeTransaction.status) {
          activeTransaction.setStatus(statusType);
        }
        activeTransaction.setTag("visibilitychange", "document.hidden");
        activeTransaction.setTag(FINISH_REASON_TAG, IDLE_TRANSACTION_FINISH_REASONS[2]);
        activeTransaction.finish();
      }
    });
  } else {
    logger.warn("[Tracing] Could not set up background tab detection due to lack of global document");
  }
}
var bindReporter = function(callback, metric, reportAllChanges) {
  var prevValue;
  return function(forceReport) {
    if (metric.value >= 0) {
      if (forceReport || reportAllChanges) {
        metric.delta = metric.value - (prevValue || 0);
        if (metric.delta || prevValue === void 0) {
          prevValue = metric.value;
          callback(metric);
        }
      }
    }
  };
};
var generateUniqueID = function() {
  return "v2-" + Date.now() + "-" + (Math.floor(Math.random() * (9e12 - 1)) + 1e12);
};
var initMetric = function(name, value) {
  return {
    name,
    value: value !== null && value !== void 0 ? value : -1,
    delta: 0,
    entries: [],
    id: generateUniqueID()
  };
};
var observe = function(type, callback) {
  try {
    if (PerformanceObserver.supportedEntryTypes.includes(type)) {
      if (type === "first-input" && !("PerformanceEventTiming" in self)) {
        return;
      }
      var po = new PerformanceObserver(function(l2) {
        return l2.getEntries().map(callback);
      });
      po.observe({ type, buffered: true });
      return po;
    }
  } catch (e2) {
  }
  return;
};
var onHidden = function(cb2, once) {
  var onHiddenOrPageHide = function(event) {
    if (event.type === "pagehide" || getGlobalObject().document.visibilityState === "hidden") {
      cb2(event);
      if (once) {
        removeEventListener("visibilitychange", onHiddenOrPageHide, true);
        removeEventListener("pagehide", onHiddenOrPageHide, true);
      }
    }
  };
  addEventListener("visibilitychange", onHiddenOrPageHide, true);
  addEventListener("pagehide", onHiddenOrPageHide, true);
};
var getCLS = function(onReport, reportAllChanges) {
  var metric = initMetric("CLS", 0);
  var report;
  var sessionValue = 0;
  var sessionEntries = [];
  var entryHandler = function(entry) {
    if (entry && !entry.hadRecentInput) {
      var firstSessionEntry = sessionEntries[0];
      var lastSessionEntry = sessionEntries[sessionEntries.length - 1];
      if (sessionValue && sessionEntries.length !== 0 && entry.startTime - lastSessionEntry.startTime < 1e3 && entry.startTime - firstSessionEntry.startTime < 5e3) {
        sessionValue += entry.value;
        sessionEntries.push(entry);
      } else {
        sessionValue = entry.value;
        sessionEntries = [entry];
      }
      if (sessionValue > metric.value) {
        metric.value = sessionValue;
        metric.entries = sessionEntries;
        if (report) {
          report();
        }
      }
    }
  };
  var po = observe("layout-shift", entryHandler);
  if (po) {
    report = bindReporter(onReport, metric, reportAllChanges);
    onHidden(function() {
      po.takeRecords().map(entryHandler);
      report(true);
    });
  }
};
var firstHiddenTime = -1;
var initHiddenTime = function() {
  return getGlobalObject().document.visibilityState === "hidden" ? 0 : Infinity;
};
var trackChanges = function() {
  onHidden(function(_a2) {
    var timeStamp = _a2.timeStamp;
    firstHiddenTime = timeStamp;
  }, true);
};
var getVisibilityWatcher = function() {
  if (firstHiddenTime < 0) {
    firstHiddenTime = initHiddenTime();
    trackChanges();
  }
  return {
    get firstHiddenTime() {
      return firstHiddenTime;
    }
  };
};
var getFID = function(onReport, reportAllChanges) {
  var visibilityWatcher = getVisibilityWatcher();
  var metric = initMetric("FID");
  var report;
  var entryHandler = function(entry) {
    if (report && entry.startTime < visibilityWatcher.firstHiddenTime) {
      metric.value = entry.processingStart - entry.startTime;
      metric.entries.push(entry);
      report(true);
    }
  };
  var po = observe("first-input", entryHandler);
  if (po) {
    report = bindReporter(onReport, metric, reportAllChanges);
    onHidden(function() {
      po.takeRecords().map(entryHandler);
      po.disconnect();
    }, true);
  }
};
var reportedMetricIDs = {};
var getLCP = function(onReport, reportAllChanges) {
  var visibilityWatcher = getVisibilityWatcher();
  var metric = initMetric("LCP");
  var report;
  var entryHandler = function(entry) {
    var value = entry.startTime;
    if (value < visibilityWatcher.firstHiddenTime) {
      metric.value = value;
      metric.entries.push(entry);
    }
    if (report) {
      report();
    }
  };
  var po = observe("largest-contentful-paint", entryHandler);
  if (po) {
    report = bindReporter(onReport, metric, reportAllChanges);
    var stopListening_1 = function() {
      if (!reportedMetricIDs[metric.id]) {
        po.takeRecords().map(entryHandler);
        po.disconnect();
        reportedMetricIDs[metric.id] = true;
        report(true);
      }
    };
    ["keydown", "click"].forEach(function(type) {
      addEventListener(type, stopListening_1, { once: true, capture: true });
    });
    onHidden(stopListening_1, true);
  }
};
var global$2 = getGlobalObject();
var MetricsInstrumentation = function() {
  function MetricsInstrumentation2(_reportAllChanges) {
    if (_reportAllChanges === void 0) {
      _reportAllChanges = false;
    }
    this._reportAllChanges = _reportAllChanges;
    this._measurements = {};
    this._performanceCursor = 0;
    if (!isNodeEnv() && global$2 && global$2.performance && global$2.document) {
      if (global$2.performance.mark) {
        global$2.performance.mark("sentry-tracing-init");
      }
      this._trackCLS();
      this._trackLCP();
      this._trackFID();
    }
  }
  MetricsInstrumentation2.prototype.addPerformanceEntries = function(transaction) {
    var _this = this;
    if (!global$2 || !global$2.performance || !global$2.performance.getEntries || !browserPerformanceTimeOrigin) {
      return;
    }
    logger.log("[Tracing] Adding & adjusting spans using Performance API");
    var timeOrigin = msToSec(browserPerformanceTimeOrigin);
    var responseStartTimestamp;
    var requestStartTimestamp;
    global$2.performance.getEntries().slice(this._performanceCursor).forEach(function(entry) {
      var startTime = msToSec(entry.startTime);
      var duration = msToSec(entry.duration);
      if (transaction.op === "navigation" && timeOrigin + startTime < transaction.startTimestamp) {
        return;
      }
      switch (entry.entryType) {
        case "navigation": {
          addNavigationSpans(transaction, entry, timeOrigin);
          responseStartTimestamp = timeOrigin + msToSec(entry.responseStart);
          requestStartTimestamp = timeOrigin + msToSec(entry.requestStart);
          break;
        }
        case "mark":
        case "paint":
        case "measure": {
          var startTimestamp = addMeasureSpans(transaction, entry, startTime, duration, timeOrigin);
          var firstHidden = getVisibilityWatcher();
          var shouldRecord = entry.startTime < firstHidden.firstHiddenTime;
          if (entry.name === "first-paint" && shouldRecord) {
            logger.log("[Measurements] Adding FP");
            _this._measurements["fp"] = { value: entry.startTime };
            _this._measurements["mark.fp"] = { value: startTimestamp };
          }
          if (entry.name === "first-contentful-paint" && shouldRecord) {
            logger.log("[Measurements] Adding FCP");
            _this._measurements["fcp"] = { value: entry.startTime };
            _this._measurements["mark.fcp"] = { value: startTimestamp };
          }
          break;
        }
        case "resource": {
          var resourceName = entry.name.replace(global$2.location.origin, "");
          addResourceSpans(transaction, entry, resourceName, startTime, duration, timeOrigin);
          break;
        }
      }
    });
    this._performanceCursor = Math.max(performance.getEntries().length - 1, 0);
    this._trackNavigator(transaction);
    if (transaction.op === "pageload") {
      var timeOrigin_1 = msToSec(browserPerformanceTimeOrigin);
      if (typeof responseStartTimestamp === "number") {
        logger.log("[Measurements] Adding TTFB");
        this._measurements["ttfb"] = { value: (responseStartTimestamp - transaction.startTimestamp) * 1e3 };
        if (typeof requestStartTimestamp === "number" && requestStartTimestamp <= responseStartTimestamp) {
          this._measurements["ttfb.requestTime"] = { value: (responseStartTimestamp - requestStartTimestamp) * 1e3 };
        }
      }
      ["fcp", "fp", "lcp"].forEach(function(name) {
        if (!_this._measurements[name] || timeOrigin_1 >= transaction.startTimestamp) {
          return;
        }
        var oldValue = _this._measurements[name].value;
        var measurementTimestamp = timeOrigin_1 + msToSec(oldValue);
        var normalizedValue = Math.abs((measurementTimestamp - transaction.startTimestamp) * 1e3);
        var delta = normalizedValue - oldValue;
        logger.log("[Measurements] Normalized " + name + " from " + oldValue + " to " + normalizedValue + " (" + delta + ")");
        _this._measurements[name].value = normalizedValue;
      });
      if (this._measurements["mark.fid"] && this._measurements["fid"]) {
        _startChild(transaction, {
          description: "first input delay",
          endTimestamp: this._measurements["mark.fid"].value + msToSec(this._measurements["fid"].value),
          op: "web.vitals",
          startTimestamp: this._measurements["mark.fid"].value
        });
      }
      if (!("fcp" in this._measurements)) {
        delete this._measurements.cls;
      }
      transaction.setMeasurements(this._measurements);
      tagMetricInfo(transaction, this._lcpEntry, this._clsEntry);
      transaction.setTag("sentry_reportAllChanges", this._reportAllChanges);
    }
  };
  MetricsInstrumentation2.prototype._trackNavigator = function(transaction) {
    var navigator2 = global$2.navigator;
    if (!navigator2) {
      return;
    }
    var connection = navigator2.connection;
    if (connection) {
      if (connection.effectiveType) {
        transaction.setTag("effectiveConnectionType", connection.effectiveType);
      }
      if (connection.type) {
        transaction.setTag("connectionType", connection.type);
      }
      if (isMeasurementValue(connection.rtt)) {
        this._measurements["connection.rtt"] = { value: connection.rtt };
      }
      if (isMeasurementValue(connection.downlink)) {
        this._measurements["connection.downlink"] = { value: connection.downlink };
      }
    }
    if (isMeasurementValue(navigator2.deviceMemory)) {
      transaction.setTag("deviceMemory", String(navigator2.deviceMemory));
    }
    if (isMeasurementValue(navigator2.hardwareConcurrency)) {
      transaction.setTag("hardwareConcurrency", String(navigator2.hardwareConcurrency));
    }
  };
  MetricsInstrumentation2.prototype._trackCLS = function() {
    var _this = this;
    getCLS(function(metric) {
      var entry = metric.entries.pop();
      if (!entry) {
        return;
      }
      logger.log("[Measurements] Adding CLS");
      _this._measurements["cls"] = { value: metric.value };
      _this._clsEntry = entry;
    });
  };
  MetricsInstrumentation2.prototype._trackLCP = function() {
    var _this = this;
    getLCP(function(metric) {
      var entry = metric.entries.pop();
      if (!entry) {
        return;
      }
      var timeOrigin = msToSec(browserPerformanceTimeOrigin);
      var startTime = msToSec(entry.startTime);
      logger.log("[Measurements] Adding LCP");
      _this._measurements["lcp"] = { value: metric.value };
      _this._measurements["mark.lcp"] = { value: timeOrigin + startTime };
      _this._lcpEntry = entry;
    }, this._reportAllChanges);
  };
  MetricsInstrumentation2.prototype._trackFID = function() {
    var _this = this;
    getFID(function(metric) {
      var entry = metric.entries.pop();
      if (!entry) {
        return;
      }
      var timeOrigin = msToSec(browserPerformanceTimeOrigin);
      var startTime = msToSec(entry.startTime);
      logger.log("[Measurements] Adding FID");
      _this._measurements["fid"] = { value: metric.value };
      _this._measurements["mark.fid"] = { value: timeOrigin + startTime };
    });
  };
  return MetricsInstrumentation2;
}();
function addNavigationSpans(transaction, entry, timeOrigin) {
  ["unloadEvent", "redirect", "domContentLoadedEvent", "loadEvent", "connect"].forEach(function(event) {
    addPerformanceNavigationTiming(transaction, entry, event, timeOrigin);
  });
  addPerformanceNavigationTiming(transaction, entry, "secureConnection", timeOrigin, "TLS/SSL", "connectEnd");
  addPerformanceNavigationTiming(transaction, entry, "fetch", timeOrigin, "cache", "domainLookupStart");
  addPerformanceNavigationTiming(transaction, entry, "domainLookup", timeOrigin, "DNS");
  addRequest(transaction, entry, timeOrigin);
}
function addMeasureSpans(transaction, entry, startTime, duration, timeOrigin) {
  var measureStartTimestamp = timeOrigin + startTime;
  var measureEndTimestamp = measureStartTimestamp + duration;
  _startChild(transaction, {
    description: entry.name,
    endTimestamp: measureEndTimestamp,
    op: entry.entryType,
    startTimestamp: measureStartTimestamp
  });
  return measureStartTimestamp;
}
function addResourceSpans(transaction, entry, resourceName, startTime, duration, timeOrigin) {
  if (entry.initiatorType === "xmlhttprequest" || entry.initiatorType === "fetch") {
    return;
  }
  var data = {};
  if ("transferSize" in entry) {
    data["Transfer Size"] = entry.transferSize;
  }
  if ("encodedBodySize" in entry) {
    data["Encoded Body Size"] = entry.encodedBodySize;
  }
  if ("decodedBodySize" in entry) {
    data["Decoded Body Size"] = entry.decodedBodySize;
  }
  var startTimestamp = timeOrigin + startTime;
  var endTimestamp = startTimestamp + duration;
  _startChild(transaction, {
    description: resourceName,
    endTimestamp,
    op: entry.initiatorType ? "resource." + entry.initiatorType : "resource",
    startTimestamp,
    data
  });
}
function addPerformanceNavigationTiming(transaction, entry, event, timeOrigin, description, eventEnd) {
  var end = eventEnd ? entry[eventEnd] : entry[event + "End"];
  var start = entry[event + "Start"];
  if (!start || !end) {
    return;
  }
  _startChild(transaction, {
    op: "browser",
    description: description !== null && description !== void 0 ? description : event,
    startTimestamp: timeOrigin + msToSec(start),
    endTimestamp: timeOrigin + msToSec(end)
  });
}
function addRequest(transaction, entry, timeOrigin) {
  _startChild(transaction, {
    op: "browser",
    description: "request",
    startTimestamp: timeOrigin + msToSec(entry.requestStart),
    endTimestamp: timeOrigin + msToSec(entry.responseEnd)
  });
  _startChild(transaction, {
    op: "browser",
    description: "response",
    startTimestamp: timeOrigin + msToSec(entry.responseStart),
    endTimestamp: timeOrigin + msToSec(entry.responseEnd)
  });
}
function _startChild(transaction, _a2) {
  var startTimestamp = _a2.startTimestamp, ctx = __rest$1(_a2, ["startTimestamp"]);
  if (startTimestamp && transaction.startTimestamp > startTimestamp) {
    transaction.startTimestamp = startTimestamp;
  }
  return transaction.startChild(__assign$1({ startTimestamp }, ctx));
}
function isMeasurementValue(value) {
  return typeof value === "number" && isFinite(value);
}
function tagMetricInfo(transaction, lcpEntry, clsEntry) {
  if (lcpEntry) {
    logger.log("[Measurements] Adding LCP Data");
    if (lcpEntry.element) {
      transaction.setTag("lcp.element", htmlTreeAsString(lcpEntry.element));
    }
    if (lcpEntry.id) {
      transaction.setTag("lcp.id", lcpEntry.id);
    }
    if (lcpEntry.url) {
      transaction.setTag("lcp.url", lcpEntry.url.trim().slice(0, 200));
    }
    transaction.setTag("lcp.size", lcpEntry.size);
  }
  if (clsEntry && clsEntry.sources) {
    logger.log("[Measurements] Adding CLS Data");
    clsEntry.sources.forEach(function(source, index2) {
      return transaction.setTag("cls.source." + (index2 + 1), htmlTreeAsString(source.node));
    });
  }
}
var DEFAULT_TRACING_ORIGINS = ["localhost", /^\//];
var defaultRequestInstrumentationOptions = {
  traceFetch: true,
  traceXHR: true,
  tracingOrigins: DEFAULT_TRACING_ORIGINS
};
function instrumentOutgoingRequests(_options) {
  var _a2 = __assign$1(__assign$1({}, defaultRequestInstrumentationOptions), _options), traceFetch = _a2.traceFetch, traceXHR = _a2.traceXHR, tracingOrigins = _a2.tracingOrigins, shouldCreateSpanForRequest = _a2.shouldCreateSpanForRequest;
  var urlMap = {};
  var defaultShouldCreateSpan = function(url) {
    if (urlMap[url]) {
      return urlMap[url];
    }
    var origins = tracingOrigins;
    urlMap[url] = origins.some(function(origin) {
      return isMatchingPattern(url, origin);
    }) && !isMatchingPattern(url, "sentry_key");
    return urlMap[url];
  };
  var shouldCreateSpan = defaultShouldCreateSpan;
  if (typeof shouldCreateSpanForRequest === "function") {
    shouldCreateSpan = function(url) {
      return defaultShouldCreateSpan(url) && shouldCreateSpanForRequest(url);
    };
  }
  var spans = {};
  if (traceFetch) {
    addInstrumentationHandler("fetch", function(handlerData) {
      fetchCallback(handlerData, shouldCreateSpan, spans);
    });
  }
  if (traceXHR) {
    addInstrumentationHandler("xhr", function(handlerData) {
      xhrCallback(handlerData, shouldCreateSpan, spans);
    });
  }
}
function fetchCallback(handlerData, shouldCreateSpan, spans) {
  if (!hasTracingEnabled() || !(handlerData.fetchData && shouldCreateSpan(handlerData.fetchData.url))) {
    return;
  }
  if (handlerData.endTimestamp) {
    var spanId = handlerData.fetchData.__span;
    if (!spanId)
      return;
    var span = spans[spanId];
    if (span) {
      if (handlerData.response) {
        span.setHttpStatus(handlerData.response.status);
      } else if (handlerData.error) {
        span.setStatus("internal_error");
      }
      span.finish();
      delete spans[spanId];
    }
    return;
  }
  var activeTransaction = getActiveTransaction();
  if (activeTransaction) {
    var span = activeTransaction.startChild({
      data: __assign$1(__assign$1({}, handlerData.fetchData), { type: "fetch" }),
      description: handlerData.fetchData.method + " " + handlerData.fetchData.url,
      op: "http.client"
    });
    handlerData.fetchData.__span = span.spanId;
    spans[span.spanId] = span;
    var request = handlerData.args[0] = handlerData.args[0];
    var options = handlerData.args[1] = handlerData.args[1] || {};
    var headers = options.headers;
    if (isInstanceOf(request, Request)) {
      headers = request.headers;
    }
    if (headers) {
      if (typeof headers.append === "function") {
        headers.append("sentry-trace", span.toTraceparent());
      } else if (Array.isArray(headers)) {
        headers = __spread$1(headers, [["sentry-trace", span.toTraceparent()]]);
      } else {
        headers = __assign$1(__assign$1({}, headers), { "sentry-trace": span.toTraceparent() });
      }
    } else {
      headers = { "sentry-trace": span.toTraceparent() };
    }
    options.headers = headers;
  }
}
function xhrCallback(handlerData, shouldCreateSpan, spans) {
  if (!hasTracingEnabled() || handlerData.xhr && handlerData.xhr.__sentry_own_request__ || !(handlerData.xhr && handlerData.xhr.__sentry_xhr__ && shouldCreateSpan(handlerData.xhr.__sentry_xhr__.url))) {
    return;
  }
  var xhr = handlerData.xhr.__sentry_xhr__;
  if (handlerData.endTimestamp) {
    var spanId = handlerData.xhr.__sentry_xhr_span_id__;
    if (!spanId)
      return;
    var span = spans[spanId];
    if (span) {
      span.setHttpStatus(xhr.status_code);
      span.finish();
      delete spans[spanId];
    }
    return;
  }
  var activeTransaction = getActiveTransaction();
  if (activeTransaction) {
    var span = activeTransaction.startChild({
      data: __assign$1(__assign$1({}, xhr.data), { type: "xhr", method: xhr.method, url: xhr.url }),
      description: xhr.method + " " + xhr.url,
      op: "http.client"
    });
    handlerData.xhr.__sentry_xhr_span_id__ = span.spanId;
    spans[handlerData.xhr.__sentry_xhr_span_id__] = span;
    if (handlerData.xhr.setRequestHeader) {
      try {
        handlerData.xhr.setRequestHeader("sentry-trace", span.toTraceparent());
      } catch (_2) {
      }
    }
  }
}
var global$1 = getGlobalObject();
function instrumentRoutingWithDefaults(customStartTransaction, startTransactionOnPageLoad, startTransactionOnLocationChange) {
  if (startTransactionOnPageLoad === void 0) {
    startTransactionOnPageLoad = true;
  }
  if (startTransactionOnLocationChange === void 0) {
    startTransactionOnLocationChange = true;
  }
  if (!global$1 || !global$1.location) {
    logger.warn("Could not initialize routing instrumentation due to invalid location");
    return;
  }
  var startingUrl = global$1.location.href;
  var activeTransaction;
  if (startTransactionOnPageLoad) {
    activeTransaction = customStartTransaction({ name: global$1.location.pathname, op: "pageload" });
  }
  if (startTransactionOnLocationChange) {
    addInstrumentationHandler("history", function(_a2) {
      var to = _a2.to, from = _a2.from;
      if (from === void 0 && startingUrl && startingUrl.indexOf(to) !== -1) {
        startingUrl = void 0;
        return;
      }
      if (from !== to) {
        startingUrl = void 0;
        if (activeTransaction) {
          logger.log("[Tracing] Finishing current transaction with op: " + activeTransaction.op);
          activeTransaction.finish();
        }
        activeTransaction = customStartTransaction({ name: global$1.location.pathname, op: "navigation" });
      }
    });
  }
}
var DEFAULT_MAX_TRANSACTION_DURATION_SECONDS = 600;
var DEFAULT_BROWSER_TRACING_OPTIONS = __assign$1({ idleTimeout: DEFAULT_IDLE_TIMEOUT, markBackgroundTransactions: true, maxTransactionDuration: DEFAULT_MAX_TRANSACTION_DURATION_SECONDS, routingInstrumentation: instrumentRoutingWithDefaults, startTransactionOnLocationChange: true, startTransactionOnPageLoad: true }, defaultRequestInstrumentationOptions);
var BrowserTracing = function() {
  function BrowserTracing2(_options) {
    this.name = BrowserTracing2.id;
    this._emitOptionsWarning = false;
    this._configuredIdleTimeout = void 0;
    var tracingOrigins = defaultRequestInstrumentationOptions.tracingOrigins;
    if (_options) {
      this._configuredIdleTimeout = _options.idleTimeout;
      if (_options.tracingOrigins && Array.isArray(_options.tracingOrigins) && _options.tracingOrigins.length !== 0) {
        tracingOrigins = _options.tracingOrigins;
      } else {
        this._emitOptionsWarning = true;
      }
    }
    this.options = __assign$1(__assign$1(__assign$1({}, DEFAULT_BROWSER_TRACING_OPTIONS), _options), { tracingOrigins });
    var _metricOptions = this.options._metricOptions;
    this._metrics = new MetricsInstrumentation(_metricOptions && _metricOptions._reportAllChanges);
  }
  BrowserTracing2.prototype.setupOnce = function(_2, getCurrentHub2) {
    var _this = this;
    this._getCurrentHub = getCurrentHub2;
    if (this._emitOptionsWarning) {
      logger.warn("[Tracing] You need to define `tracingOrigins` in the options. Set an array of urls or patterns to trace.");
      logger.warn("[Tracing] We added a reasonable default for you: " + defaultRequestInstrumentationOptions.tracingOrigins);
    }
    var _a2 = this.options, instrumentRouting = _a2.routingInstrumentation, startTransactionOnLocationChange = _a2.startTransactionOnLocationChange, startTransactionOnPageLoad = _a2.startTransactionOnPageLoad, markBackgroundTransactions = _a2.markBackgroundTransactions, traceFetch = _a2.traceFetch, traceXHR = _a2.traceXHR, tracingOrigins = _a2.tracingOrigins, shouldCreateSpanForRequest = _a2.shouldCreateSpanForRequest;
    instrumentRouting(function(context) {
      return _this._createRouteTransaction(context);
    }, startTransactionOnPageLoad, startTransactionOnLocationChange);
    if (markBackgroundTransactions) {
      registerBackgroundTabDetection();
    }
    instrumentOutgoingRequests({ traceFetch, traceXHR, tracingOrigins, shouldCreateSpanForRequest });
  };
  BrowserTracing2.prototype._createRouteTransaction = function(context) {
    var _this = this;
    if (!this._getCurrentHub) {
      logger.warn("[Tracing] Did not create " + context.op + " transaction because _getCurrentHub is invalid.");
      return void 0;
    }
    var _a2 = this.options, beforeNavigate = _a2.beforeNavigate, idleTimeout = _a2.idleTimeout, maxTransactionDuration = _a2.maxTransactionDuration;
    var parentContextFromHeader = context.op === "pageload" ? getHeaderContext() : void 0;
    var expandedContext = __assign$1(__assign$1(__assign$1({}, context), parentContextFromHeader), { trimEnd: true });
    var modifiedContext = typeof beforeNavigate === "function" ? beforeNavigate(expandedContext) : expandedContext;
    var finalContext = modifiedContext === void 0 ? __assign$1(__assign$1({}, expandedContext), { sampled: false }) : modifiedContext;
    if (finalContext.sampled === false) {
      logger.log("[Tracing] Will not send " + finalContext.op + " transaction because of beforeNavigate.");
    }
    logger.log("[Tracing] Starting " + finalContext.op + " transaction on scope");
    var hub = this._getCurrentHub();
    var location2 = getGlobalObject().location;
    var idleTransaction = startIdleTransaction(hub, finalContext, idleTimeout, true, { location: location2 });
    idleTransaction.registerBeforeFinishCallback(function(transaction, endTimestamp) {
      _this._metrics.addPerformanceEntries(transaction);
      adjustTransactionDuration(secToMs(maxTransactionDuration), transaction, endTimestamp);
    });
    idleTransaction.setTag("idleTimeout", this._configuredIdleTimeout);
    return idleTransaction;
  };
  BrowserTracing2.id = "BrowserTracing";
  return BrowserTracing2;
}();
function getHeaderContext() {
  var header = getMetaContent("sentry-trace");
  if (header) {
    return extractTraceparentData(header);
  }
  return void 0;
}
function getMetaContent(metaName) {
  var el = getGlobalObject().document.querySelector("meta[name=" + metaName + "]");
  return el ? el.getAttribute("content") : null;
}
function adjustTransactionDuration(maxDuration2, transaction, endTimestamp) {
  var diff = endTimestamp - transaction.startTimestamp;
  var isOutdatedTransaction = endTimestamp && (diff > maxDuration2 || diff < 0);
  if (isOutdatedTransaction) {
    transaction.setStatus("deadline_exceeded");
    transaction.setTag("maxTransactionDurationExceeded", "true");
  }
}
addExtensionMethods();
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
var extendStatics = function(d2, b2) {
  extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d3, b3) {
    d3.__proto__ = b3;
  } || function(d3, b3) {
    for (var p2 in b3)
      if (Object.prototype.hasOwnProperty.call(b3, p2))
        d3[p2] = b3[p2];
  };
  return extendStatics(d2, b2);
};
function __extends(d2, b2) {
  if (typeof b2 !== "function" && b2 !== null)
    throw new TypeError("Class extends value " + String(b2) + " is not a constructor or null");
  extendStatics(d2, b2);
  function __() {
    this.constructor = d2;
  }
  d2.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __());
}
var __assign = function() {
  __assign = Object.assign || function __assign2(t2) {
    for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
      s2 = arguments[i2];
      for (var p2 in s2)
        if (Object.prototype.hasOwnProperty.call(s2, p2))
          t2[p2] = s2[p2];
    }
    return t2;
  };
  return __assign.apply(this, arguments);
};
function __rest(s2, e2) {
  var t2 = {};
  for (var p2 in s2)
    if (Object.prototype.hasOwnProperty.call(s2, p2) && e2.indexOf(p2) < 0)
      t2[p2] = s2[p2];
  if (s2 != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i2 = 0, p2 = Object.getOwnPropertySymbols(s2); i2 < p2.length; i2++) {
      if (e2.indexOf(p2[i2]) < 0 && Object.prototype.propertyIsEnumerable.call(s2, p2[i2]))
        t2[p2[i2]] = s2[p2[i2]];
    }
  return t2;
}
function __awaiter(thisArg, _arguments, P2, generator) {
  function adopt(value) {
    return value instanceof P2 ? value : new P2(function(resolve) {
      resolve(value);
    });
  }
  return new (P2 || (P2 = Promise))(function(resolve, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e2) {
        reject(e2);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e2) {
        reject(e2);
      }
    }
    function step(result) {
      result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}
function __generator(thisArg, body) {
  var _2 = { label: 0, sent: function() {
    if (t2[0] & 1)
      throw t2[1];
    return t2[1];
  }, trys: [], ops: [] }, f2, y2, t2, g2;
  return g2 = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g2[Symbol.iterator] = function() {
    return this;
  }), g2;
  function verb(n2) {
    return function(v2) {
      return step([n2, v2]);
    };
  }
  function step(op) {
    if (f2)
      throw new TypeError("Generator is already executing.");
    while (_2)
      try {
        if (f2 = 1, y2 && (t2 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t2 = y2["return"]) && t2.call(y2), 0) : y2.next) && !(t2 = t2.call(y2, op[1])).done)
          return t2;
        if (y2 = 0, t2)
          op = [op[0] & 2, t2.value];
        switch (op[0]) {
          case 0:
          case 1:
            t2 = op;
            break;
          case 4:
            _2.label++;
            return { value: op[1], done: false };
          case 5:
            _2.label++;
            y2 = op[1];
            op = [0];
            continue;
          case 7:
            op = _2.ops.pop();
            _2.trys.pop();
            continue;
          default:
            if (!(t2 = _2.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) {
              _2 = 0;
              continue;
            }
            if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) {
              _2.label = op[1];
              break;
            }
            if (op[0] === 6 && _2.label < t2[1]) {
              _2.label = t2[1];
              t2 = op;
              break;
            }
            if (t2 && _2.label < t2[2]) {
              _2.label = t2[2];
              _2.ops.push(op);
              break;
            }
            if (t2[2])
              _2.ops.pop();
            _2.trys.pop();
            continue;
        }
        op = body.call(thisArg, _2);
      } catch (e2) {
        op = [6, e2];
        y2 = 0;
      } finally {
        f2 = t2 = 0;
      }
    if (op[0] & 5)
      throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
}
function __values(o2) {
  var s2 = typeof Symbol === "function" && Symbol.iterator, m2 = s2 && o2[s2], i2 = 0;
  if (m2)
    return m2.call(o2);
  if (o2 && typeof o2.length === "number")
    return {
      next: function() {
        if (o2 && i2 >= o2.length)
          o2 = void 0;
        return { value: o2 && o2[i2++], done: !o2 };
      }
    };
  throw new TypeError(s2 ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o2, n2) {
  var m2 = typeof Symbol === "function" && o2[Symbol.iterator];
  if (!m2)
    return o2;
  var i2 = m2.call(o2), r2, ar = [], e2;
  try {
    while ((n2 === void 0 || n2-- > 0) && !(r2 = i2.next()).done)
      ar.push(r2.value);
  } catch (error) {
    e2 = { error };
  } finally {
    try {
      if (r2 && !r2.done && (m2 = i2["return"]))
        m2.call(i2);
    } finally {
      if (e2)
        throw e2.error;
    }
  }
  return ar;
}
function __spread() {
  for (var ar = [], i2 = 0; i2 < arguments.length; i2++)
    ar = ar.concat(__read(arguments[i2]));
  return ar;
}
function __spreadArray(to, from, pack) {
  if (pack || arguments.length === 2)
    for (var i2 = 0, l2 = from.length, ar; i2 < l2; i2++) {
      if (ar || !(i2 in from)) {
        if (!ar)
          ar = Array.prototype.slice.call(from, 0, i2);
        ar[i2] = from[i2];
      }
    }
  return to.concat(ar || Array.prototype.slice.call(from));
}
function invariant$1(condition, message, Err) {
  if (Err === void 0) {
    Err = Error;
  }
  if (!condition) {
    throw new Err(message);
  }
}
var ErrorKind;
(function(ErrorKind2) {
  ErrorKind2[ErrorKind2["EXPECT_ARGUMENT_CLOSING_BRACE"] = 1] = "EXPECT_ARGUMENT_CLOSING_BRACE";
  ErrorKind2[ErrorKind2["EMPTY_ARGUMENT"] = 2] = "EMPTY_ARGUMENT";
  ErrorKind2[ErrorKind2["MALFORMED_ARGUMENT"] = 3] = "MALFORMED_ARGUMENT";
  ErrorKind2[ErrorKind2["EXPECT_ARGUMENT_TYPE"] = 4] = "EXPECT_ARGUMENT_TYPE";
  ErrorKind2[ErrorKind2["INVALID_ARGUMENT_TYPE"] = 5] = "INVALID_ARGUMENT_TYPE";
  ErrorKind2[ErrorKind2["EXPECT_ARGUMENT_STYLE"] = 6] = "EXPECT_ARGUMENT_STYLE";
  ErrorKind2[ErrorKind2["INVALID_NUMBER_SKELETON"] = 7] = "INVALID_NUMBER_SKELETON";
  ErrorKind2[ErrorKind2["INVALID_DATE_TIME_SKELETON"] = 8] = "INVALID_DATE_TIME_SKELETON";
  ErrorKind2[ErrorKind2["EXPECT_NUMBER_SKELETON"] = 9] = "EXPECT_NUMBER_SKELETON";
  ErrorKind2[ErrorKind2["EXPECT_DATE_TIME_SKELETON"] = 10] = "EXPECT_DATE_TIME_SKELETON";
  ErrorKind2[ErrorKind2["UNCLOSED_QUOTE_IN_ARGUMENT_STYLE"] = 11] = "UNCLOSED_QUOTE_IN_ARGUMENT_STYLE";
  ErrorKind2[ErrorKind2["EXPECT_SELECT_ARGUMENT_OPTIONS"] = 12] = "EXPECT_SELECT_ARGUMENT_OPTIONS";
  ErrorKind2[ErrorKind2["EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE"] = 13] = "EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE";
  ErrorKind2[ErrorKind2["INVALID_PLURAL_ARGUMENT_OFFSET_VALUE"] = 14] = "INVALID_PLURAL_ARGUMENT_OFFSET_VALUE";
  ErrorKind2[ErrorKind2["EXPECT_SELECT_ARGUMENT_SELECTOR"] = 15] = "EXPECT_SELECT_ARGUMENT_SELECTOR";
  ErrorKind2[ErrorKind2["EXPECT_PLURAL_ARGUMENT_SELECTOR"] = 16] = "EXPECT_PLURAL_ARGUMENT_SELECTOR";
  ErrorKind2[ErrorKind2["EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT"] = 17] = "EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT";
  ErrorKind2[ErrorKind2["EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT"] = 18] = "EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT";
  ErrorKind2[ErrorKind2["INVALID_PLURAL_ARGUMENT_SELECTOR"] = 19] = "INVALID_PLURAL_ARGUMENT_SELECTOR";
  ErrorKind2[ErrorKind2["DUPLICATE_PLURAL_ARGUMENT_SELECTOR"] = 20] = "DUPLICATE_PLURAL_ARGUMENT_SELECTOR";
  ErrorKind2[ErrorKind2["DUPLICATE_SELECT_ARGUMENT_SELECTOR"] = 21] = "DUPLICATE_SELECT_ARGUMENT_SELECTOR";
  ErrorKind2[ErrorKind2["MISSING_OTHER_CLAUSE"] = 22] = "MISSING_OTHER_CLAUSE";
  ErrorKind2[ErrorKind2["INVALID_TAG"] = 23] = "INVALID_TAG";
  ErrorKind2[ErrorKind2["INVALID_TAG_NAME"] = 25] = "INVALID_TAG_NAME";
  ErrorKind2[ErrorKind2["UNMATCHED_CLOSING_TAG"] = 26] = "UNMATCHED_CLOSING_TAG";
  ErrorKind2[ErrorKind2["UNCLOSED_TAG"] = 27] = "UNCLOSED_TAG";
})(ErrorKind || (ErrorKind = {}));
var TYPE;
(function(TYPE2) {
  TYPE2[TYPE2["literal"] = 0] = "literal";
  TYPE2[TYPE2["argument"] = 1] = "argument";
  TYPE2[TYPE2["number"] = 2] = "number";
  TYPE2[TYPE2["date"] = 3] = "date";
  TYPE2[TYPE2["time"] = 4] = "time";
  TYPE2[TYPE2["select"] = 5] = "select";
  TYPE2[TYPE2["plural"] = 6] = "plural";
  TYPE2[TYPE2["pound"] = 7] = "pound";
  TYPE2[TYPE2["tag"] = 8] = "tag";
})(TYPE || (TYPE = {}));
var SKELETON_TYPE;
(function(SKELETON_TYPE2) {
  SKELETON_TYPE2[SKELETON_TYPE2["number"] = 0] = "number";
  SKELETON_TYPE2[SKELETON_TYPE2["dateTime"] = 1] = "dateTime";
})(SKELETON_TYPE || (SKELETON_TYPE = {}));
function isLiteralElement(el) {
  return el.type === TYPE.literal;
}
function isArgumentElement(el) {
  return el.type === TYPE.argument;
}
function isNumberElement(el) {
  return el.type === TYPE.number;
}
function isDateElement(el) {
  return el.type === TYPE.date;
}
function isTimeElement(el) {
  return el.type === TYPE.time;
}
function isSelectElement(el) {
  return el.type === TYPE.select;
}
function isPluralElement(el) {
  return el.type === TYPE.plural;
}
function isPoundElement(el) {
  return el.type === TYPE.pound;
}
function isTagElement(el) {
  return el.type === TYPE.tag;
}
function isNumberSkeleton(el) {
  return !!(el && typeof el === "object" && el.type === SKELETON_TYPE.number);
}
function isDateTimeSkeleton(el) {
  return !!(el && typeof el === "object" && el.type === SKELETON_TYPE.dateTime);
}
var SPACE_SEPARATOR_REGEX = /[ \xA0\u1680\u2000-\u200A\u202F\u205F\u3000]/;
var DATE_TIME_REGEX = /(?:[Eec]{1,6}|G{1,5}|[Qq]{1,5}|(?:[yYur]+|U{1,5})|[ML]{1,5}|d{1,2}|D{1,3}|F{1}|[abB]{1,5}|[hkHK]{1,2}|w{1,2}|W{1}|m{1,2}|s{1,2}|[zZOvVxX]{1,4})(?=([^']*'[^']*')*[^']*$)/g;
function parseDateTimeSkeleton(skeleton) {
  var result = {};
  skeleton.replace(DATE_TIME_REGEX, function(match) {
    var len = match.length;
    switch (match[0]) {
      case "G":
        result.era = len === 4 ? "long" : len === 5 ? "narrow" : "short";
        break;
      case "y":
        result.year = len === 2 ? "2-digit" : "numeric";
        break;
      case "Y":
      case "u":
      case "U":
      case "r":
        throw new RangeError("`Y/u/U/r` (year) patterns are not supported, use `y` instead");
      case "q":
      case "Q":
        throw new RangeError("`q/Q` (quarter) patterns are not supported");
      case "M":
      case "L":
        result.month = ["numeric", "2-digit", "short", "long", "narrow"][len - 1];
        break;
      case "w":
      case "W":
        throw new RangeError("`w/W` (week) patterns are not supported");
      case "d":
        result.day = ["numeric", "2-digit"][len - 1];
        break;
      case "D":
      case "F":
      case "g":
        throw new RangeError("`D/F/g` (day) patterns are not supported, use `d` instead");
      case "E":
        result.weekday = len === 4 ? "short" : len === 5 ? "narrow" : "short";
        break;
      case "e":
        if (len < 4) {
          throw new RangeError("`e..eee` (weekday) patterns are not supported");
        }
        result.weekday = ["short", "long", "narrow", "short"][len - 4];
        break;
      case "c":
        if (len < 4) {
          throw new RangeError("`c..ccc` (weekday) patterns are not supported");
        }
        result.weekday = ["short", "long", "narrow", "short"][len - 4];
        break;
      case "a":
        result.hour12 = true;
        break;
      case "b":
      case "B":
        throw new RangeError("`b/B` (period) patterns are not supported, use `a` instead");
      case "h":
        result.hourCycle = "h12";
        result.hour = ["numeric", "2-digit"][len - 1];
        break;
      case "H":
        result.hourCycle = "h23";
        result.hour = ["numeric", "2-digit"][len - 1];
        break;
      case "K":
        result.hourCycle = "h11";
        result.hour = ["numeric", "2-digit"][len - 1];
        break;
      case "k":
        result.hourCycle = "h24";
        result.hour = ["numeric", "2-digit"][len - 1];
        break;
      case "j":
      case "J":
      case "C":
        throw new RangeError("`j/J/C` (hour) patterns are not supported, use `h/H/K/k` instead");
      case "m":
        result.minute = ["numeric", "2-digit"][len - 1];
        break;
      case "s":
        result.second = ["numeric", "2-digit"][len - 1];
        break;
      case "S":
      case "A":
        throw new RangeError("`S/A` (second) patterns are not supported, use `s` instead");
      case "z":
        result.timeZoneName = len < 4 ? "short" : "long";
        break;
      case "Z":
      case "O":
      case "v":
      case "V":
      case "X":
      case "x":
        throw new RangeError("`Z/O/v/V/X/x` (timeZone) patterns are not supported, use `z` instead");
    }
    return "";
  });
  return result;
}
var WHITE_SPACE_REGEX = /[\t-\r \x85\u200E\u200F\u2028\u2029]/i;
function parseNumberSkeletonFromString(skeleton) {
  if (skeleton.length === 0) {
    throw new Error("Number skeleton cannot be empty");
  }
  var stringTokens = skeleton.split(WHITE_SPACE_REGEX).filter(function(x2) {
    return x2.length > 0;
  });
  var tokens = [];
  for (var _i = 0, stringTokens_1 = stringTokens; _i < stringTokens_1.length; _i++) {
    var stringToken = stringTokens_1[_i];
    var stemAndOptions = stringToken.split("/");
    if (stemAndOptions.length === 0) {
      throw new Error("Invalid number skeleton");
    }
    var stem = stemAndOptions[0], options = stemAndOptions.slice(1);
    for (var _a2 = 0, options_1 = options; _a2 < options_1.length; _a2++) {
      var option = options_1[_a2];
      if (option.length === 0) {
        throw new Error("Invalid number skeleton");
      }
    }
    tokens.push({ stem, options });
  }
  return tokens;
}
function icuUnitToEcma(unit) {
  return unit.replace(/^(.*?)-/, "");
}
var FRACTION_PRECISION_REGEX = /^\.(?:(0+)(\*)?|(#+)|(0+)(#+))$/g;
var SIGNIFICANT_PRECISION_REGEX = /^(@+)?(\+|#+)?[rs]?$/g;
var INTEGER_WIDTH_REGEX = /(\*)(0+)|(#+)(0+)|(0+)/g;
var CONCISE_INTEGER_WIDTH_REGEX = /^(0+)$/;
function parseSignificantPrecision(str) {
  var result = {};
  if (str[str.length - 1] === "r") {
    result.roundingPriority = "morePrecision";
  } else if (str[str.length - 1] === "s") {
    result.roundingPriority = "lessPrecision";
  }
  str.replace(SIGNIFICANT_PRECISION_REGEX, function(_2, g1, g2) {
    if (typeof g2 !== "string") {
      result.minimumSignificantDigits = g1.length;
      result.maximumSignificantDigits = g1.length;
    } else if (g2 === "+") {
      result.minimumSignificantDigits = g1.length;
    } else if (g1[0] === "#") {
      result.maximumSignificantDigits = g1.length;
    } else {
      result.minimumSignificantDigits = g1.length;
      result.maximumSignificantDigits = g1.length + (typeof g2 === "string" ? g2.length : 0);
    }
    return "";
  });
  return result;
}
function parseSign(str) {
  switch (str) {
    case "sign-auto":
      return {
        signDisplay: "auto"
      };
    case "sign-accounting":
    case "()":
      return {
        currencySign: "accounting"
      };
    case "sign-always":
    case "+!":
      return {
        signDisplay: "always"
      };
    case "sign-accounting-always":
    case "()!":
      return {
        signDisplay: "always",
        currencySign: "accounting"
      };
    case "sign-except-zero":
    case "+?":
      return {
        signDisplay: "exceptZero"
      };
    case "sign-accounting-except-zero":
    case "()?":
      return {
        signDisplay: "exceptZero",
        currencySign: "accounting"
      };
    case "sign-never":
    case "+_":
      return {
        signDisplay: "never"
      };
  }
}
function parseConciseScientificAndEngineeringStem(stem) {
  var result;
  if (stem[0] === "E" && stem[1] === "E") {
    result = {
      notation: "engineering"
    };
    stem = stem.slice(2);
  } else if (stem[0] === "E") {
    result = {
      notation: "scientific"
    };
    stem = stem.slice(1);
  }
  if (result) {
    var signDisplay = stem.slice(0, 2);
    if (signDisplay === "+!") {
      result.signDisplay = "always";
      stem = stem.slice(2);
    } else if (signDisplay === "+?") {
      result.signDisplay = "exceptZero";
      stem = stem.slice(2);
    }
    if (!CONCISE_INTEGER_WIDTH_REGEX.test(stem)) {
      throw new Error("Malformed concise eng/scientific notation");
    }
    result.minimumIntegerDigits = stem.length;
  }
  return result;
}
function parseNotationOptions(opt) {
  var result = {};
  var signOpts = parseSign(opt);
  if (signOpts) {
    return signOpts;
  }
  return result;
}
function parseNumberSkeleton(tokens) {
  var result = {};
  for (var _i = 0, tokens_1 = tokens; _i < tokens_1.length; _i++) {
    var token = tokens_1[_i];
    switch (token.stem) {
      case "percent":
      case "%":
        result.style = "percent";
        continue;
      case "%x100":
        result.style = "percent";
        result.scale = 100;
        continue;
      case "currency":
        result.style = "currency";
        result.currency = token.options[0];
        continue;
      case "group-off":
      case ",_":
        result.useGrouping = false;
        continue;
      case "precision-integer":
      case ".":
        result.maximumFractionDigits = 0;
        continue;
      case "measure-unit":
      case "unit":
        result.style = "unit";
        result.unit = icuUnitToEcma(token.options[0]);
        continue;
      case "compact-short":
      case "K":
        result.notation = "compact";
        result.compactDisplay = "short";
        continue;
      case "compact-long":
      case "KK":
        result.notation = "compact";
        result.compactDisplay = "long";
        continue;
      case "scientific":
        result = __assign(__assign(__assign({}, result), { notation: "scientific" }), token.options.reduce(function(all, opt2) {
          return __assign(__assign({}, all), parseNotationOptions(opt2));
        }, {}));
        continue;
      case "engineering":
        result = __assign(__assign(__assign({}, result), { notation: "engineering" }), token.options.reduce(function(all, opt2) {
          return __assign(__assign({}, all), parseNotationOptions(opt2));
        }, {}));
        continue;
      case "notation-simple":
        result.notation = "standard";
        continue;
      case "unit-width-narrow":
        result.currencyDisplay = "narrowSymbol";
        result.unitDisplay = "narrow";
        continue;
      case "unit-width-short":
        result.currencyDisplay = "code";
        result.unitDisplay = "short";
        continue;
      case "unit-width-full-name":
        result.currencyDisplay = "name";
        result.unitDisplay = "long";
        continue;
      case "unit-width-iso-code":
        result.currencyDisplay = "symbol";
        continue;
      case "scale":
        result.scale = parseFloat(token.options[0]);
        continue;
      case "integer-width":
        if (token.options.length > 1) {
          throw new RangeError("integer-width stems only accept a single optional option");
        }
        token.options[0].replace(INTEGER_WIDTH_REGEX, function(_2, g1, g2, g3, g4, g5) {
          if (g1) {
            result.minimumIntegerDigits = g2.length;
          } else if (g3 && g4) {
            throw new Error("We currently do not support maximum integer digits");
          } else if (g5) {
            throw new Error("We currently do not support exact integer digits");
          }
          return "";
        });
        continue;
    }
    if (CONCISE_INTEGER_WIDTH_REGEX.test(token.stem)) {
      result.minimumIntegerDigits = token.stem.length;
      continue;
    }
    if (FRACTION_PRECISION_REGEX.test(token.stem)) {
      if (token.options.length > 1) {
        throw new RangeError("Fraction-precision stems only accept a single optional option");
      }
      token.stem.replace(FRACTION_PRECISION_REGEX, function(_2, g1, g2, g3, g4, g5) {
        if (g2 === "*") {
          result.minimumFractionDigits = g1.length;
        } else if (g3 && g3[0] === "#") {
          result.maximumFractionDigits = g3.length;
        } else if (g4 && g5) {
          result.minimumFractionDigits = g4.length;
          result.maximumFractionDigits = g4.length + g5.length;
        } else {
          result.minimumFractionDigits = g1.length;
          result.maximumFractionDigits = g1.length;
        }
        return "";
      });
      var opt = token.options[0];
      if (opt === "w") {
        result = __assign(__assign({}, result), { trailingZeroDisplay: "stripIfInteger" });
      } else if (opt) {
        result = __assign(__assign({}, result), parseSignificantPrecision(opt));
      }
      continue;
    }
    if (SIGNIFICANT_PRECISION_REGEX.test(token.stem)) {
      result = __assign(__assign({}, result), parseSignificantPrecision(token.stem));
      continue;
    }
    var signOpts = parseSign(token.stem);
    if (signOpts) {
      result = __assign(__assign({}, result), signOpts);
    }
    var conciseScientificAndEngineeringOpts = parseConciseScientificAndEngineeringStem(token.stem);
    if (conciseScientificAndEngineeringOpts) {
      result = __assign(__assign({}, result), conciseScientificAndEngineeringOpts);
    }
  }
  return result;
}
var _a;
var SPACE_SEPARATOR_START_REGEX = new RegExp("^".concat(SPACE_SEPARATOR_REGEX.source, "*"));
var SPACE_SEPARATOR_END_REGEX = new RegExp("".concat(SPACE_SEPARATOR_REGEX.source, "*$"));
function createLocation(start, end) {
  return { start, end };
}
var hasNativeStartsWith = !!String.prototype.startsWith;
var hasNativeFromCodePoint = !!String.fromCodePoint;
var hasNativeFromEntries = !!Object.fromEntries;
var hasNativeCodePointAt = !!String.prototype.codePointAt;
var hasTrimStart = !!String.prototype.trimStart;
var hasTrimEnd = !!String.prototype.trimEnd;
var hasNativeIsSafeInteger = !!Number.isSafeInteger;
var isSafeInteger = hasNativeIsSafeInteger ? Number.isSafeInteger : function(n2) {
  return typeof n2 === "number" && isFinite(n2) && Math.floor(n2) === n2 && Math.abs(n2) <= 9007199254740991;
};
var REGEX_SUPPORTS_U_AND_Y = true;
try {
  var re = RE("([^\\p{White_Space}\\p{Pattern_Syntax}]*)", "yu");
  REGEX_SUPPORTS_U_AND_Y = ((_a = re.exec("a")) === null || _a === void 0 ? void 0 : _a[0]) === "a";
} catch (_2) {
  REGEX_SUPPORTS_U_AND_Y = false;
}
var startsWith = hasNativeStartsWith ? function startsWith2(s2, search, position2) {
  return s2.startsWith(search, position2);
} : function startsWith3(s2, search, position2) {
  return s2.slice(position2, position2 + search.length) === search;
};
var fromCodePoint = hasNativeFromCodePoint ? String.fromCodePoint : function fromCodePoint2() {
  var codePoints = [];
  for (var _i = 0; _i < arguments.length; _i++) {
    codePoints[_i] = arguments[_i];
  }
  var elements = "";
  var length = codePoints.length;
  var i2 = 0;
  var code;
  while (length > i2) {
    code = codePoints[i2++];
    if (code > 1114111)
      throw RangeError(code + " is not a valid code point");
    elements += code < 65536 ? String.fromCharCode(code) : String.fromCharCode(((code -= 65536) >> 10) + 55296, code % 1024 + 56320);
  }
  return elements;
};
var fromEntries = hasNativeFromEntries ? Object.fromEntries : function fromEntries2(entries) {
  var obj = {};
  for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
    var _a2 = entries_1[_i], k2 = _a2[0], v2 = _a2[1];
    obj[k2] = v2;
  }
  return obj;
};
var codePointAt = hasNativeCodePointAt ? function codePointAt2(s2, index2) {
  return s2.codePointAt(index2);
} : function codePointAt3(s2, index2) {
  var size = s2.length;
  if (index2 < 0 || index2 >= size) {
    return void 0;
  }
  var first = s2.charCodeAt(index2);
  var second;
  return first < 55296 || first > 56319 || index2 + 1 === size || (second = s2.charCodeAt(index2 + 1)) < 56320 || second > 57343 ? first : (first - 55296 << 10) + (second - 56320) + 65536;
};
var trimStart = hasTrimStart ? function trimStart2(s2) {
  return s2.trimStart();
} : function trimStart3(s2) {
  return s2.replace(SPACE_SEPARATOR_START_REGEX, "");
};
var trimEnd = hasTrimEnd ? function trimEnd2(s2) {
  return s2.trimEnd();
} : function trimEnd3(s2) {
  return s2.replace(SPACE_SEPARATOR_END_REGEX, "");
};
function RE(s2, flag) {
  return new RegExp(s2, flag);
}
var matchIdentifierAtIndex;
if (REGEX_SUPPORTS_U_AND_Y) {
  var IDENTIFIER_PREFIX_RE_1 = RE("([^\\p{White_Space}\\p{Pattern_Syntax}]*)", "yu");
  matchIdentifierAtIndex = function matchIdentifierAtIndex2(s2, index2) {
    var _a2;
    IDENTIFIER_PREFIX_RE_1.lastIndex = index2;
    var match = IDENTIFIER_PREFIX_RE_1.exec(s2);
    return (_a2 = match[1]) !== null && _a2 !== void 0 ? _a2 : "";
  };
} else {
  matchIdentifierAtIndex = function matchIdentifierAtIndex2(s2, index2) {
    var match = [];
    while (true) {
      var c2 = codePointAt(s2, index2);
      if (c2 === void 0 || _isWhiteSpace(c2) || _isPatternSyntax(c2)) {
        break;
      }
      match.push(c2);
      index2 += c2 >= 65536 ? 2 : 1;
    }
    return fromCodePoint.apply(void 0, match);
  };
}
var Parser = function() {
  function Parser2(message, options) {
    if (options === void 0) {
      options = {};
    }
    this.message = message;
    this.position = { offset: 0, line: 1, column: 1 };
    this.ignoreTag = !!options.ignoreTag;
    this.requiresOtherClause = !!options.requiresOtherClause;
    this.shouldParseSkeletons = !!options.shouldParseSkeletons;
  }
  Parser2.prototype.parse = function() {
    if (this.offset() !== 0) {
      throw Error("parser can only be used once");
    }
    return this.parseMessage(0, "", false);
  };
  Parser2.prototype.parseMessage = function(nestingLevel, parentArgType, expectingCloseTag) {
    var elements = [];
    while (!this.isEOF()) {
      var char = this.char();
      if (char === 123) {
        var result = this.parseArgument(nestingLevel, expectingCloseTag);
        if (result.err) {
          return result;
        }
        elements.push(result.val);
      } else if (char === 125 && nestingLevel > 0) {
        break;
      } else if (char === 35 && (parentArgType === "plural" || parentArgType === "selectordinal")) {
        var position2 = this.clonePosition();
        this.bump();
        elements.push({
          type: TYPE.pound,
          location: createLocation(position2, this.clonePosition())
        });
      } else if (char === 60 && !this.ignoreTag && this.peek() === 47) {
        if (expectingCloseTag) {
          break;
        } else {
          return this.error(ErrorKind.UNMATCHED_CLOSING_TAG, createLocation(this.clonePosition(), this.clonePosition()));
        }
      } else if (char === 60 && !this.ignoreTag && _isAlpha(this.peek() || 0)) {
        var result = this.parseTag(nestingLevel, parentArgType);
        if (result.err) {
          return result;
        }
        elements.push(result.val);
      } else {
        var result = this.parseLiteral(nestingLevel, parentArgType);
        if (result.err) {
          return result;
        }
        elements.push(result.val);
      }
    }
    return { val: elements, err: null };
  };
  Parser2.prototype.parseTag = function(nestingLevel, parentArgType) {
    var startPosition = this.clonePosition();
    this.bump();
    var tagName = this.parseTagName();
    this.bumpSpace();
    if (this.bumpIf("/>")) {
      return {
        val: {
          type: TYPE.literal,
          value: "<".concat(tagName, "/>"),
          location: createLocation(startPosition, this.clonePosition())
        },
        err: null
      };
    } else if (this.bumpIf(">")) {
      var childrenResult = this.parseMessage(nestingLevel + 1, parentArgType, true);
      if (childrenResult.err) {
        return childrenResult;
      }
      var children = childrenResult.val;
      var endTagStartPosition = this.clonePosition();
      if (this.bumpIf("</")) {
        if (this.isEOF() || !_isAlpha(this.char())) {
          return this.error(ErrorKind.INVALID_TAG, createLocation(endTagStartPosition, this.clonePosition()));
        }
        var closingTagNameStartPosition = this.clonePosition();
        var closingTagName = this.parseTagName();
        if (tagName !== closingTagName) {
          return this.error(ErrorKind.UNMATCHED_CLOSING_TAG, createLocation(closingTagNameStartPosition, this.clonePosition()));
        }
        this.bumpSpace();
        if (!this.bumpIf(">")) {
          return this.error(ErrorKind.INVALID_TAG, createLocation(endTagStartPosition, this.clonePosition()));
        }
        return {
          val: {
            type: TYPE.tag,
            value: tagName,
            children,
            location: createLocation(startPosition, this.clonePosition())
          },
          err: null
        };
      } else {
        return this.error(ErrorKind.UNCLOSED_TAG, createLocation(startPosition, this.clonePosition()));
      }
    } else {
      return this.error(ErrorKind.INVALID_TAG, createLocation(startPosition, this.clonePosition()));
    }
  };
  Parser2.prototype.parseTagName = function() {
    var startOffset = this.offset();
    this.bump();
    while (!this.isEOF() && _isPotentialElementNameChar(this.char())) {
      this.bump();
    }
    return this.message.slice(startOffset, this.offset());
  };
  Parser2.prototype.parseLiteral = function(nestingLevel, parentArgType) {
    var start = this.clonePosition();
    var value = "";
    while (true) {
      var parseQuoteResult = this.tryParseQuote(parentArgType);
      if (parseQuoteResult) {
        value += parseQuoteResult;
        continue;
      }
      var parseUnquotedResult = this.tryParseUnquoted(nestingLevel, parentArgType);
      if (parseUnquotedResult) {
        value += parseUnquotedResult;
        continue;
      }
      var parseLeftAngleResult = this.tryParseLeftAngleBracket();
      if (parseLeftAngleResult) {
        value += parseLeftAngleResult;
        continue;
      }
      break;
    }
    var location2 = createLocation(start, this.clonePosition());
    return {
      val: { type: TYPE.literal, value, location: location2 },
      err: null
    };
  };
  Parser2.prototype.tryParseLeftAngleBracket = function() {
    if (!this.isEOF() && this.char() === 60 && (this.ignoreTag || !_isAlphaOrSlash(this.peek() || 0))) {
      this.bump();
      return "<";
    }
    return null;
  };
  Parser2.prototype.tryParseQuote = function(parentArgType) {
    if (this.isEOF() || this.char() !== 39) {
      return null;
    }
    switch (this.peek()) {
      case 39:
        this.bump();
        this.bump();
        return "'";
      case 123:
      case 60:
      case 62:
      case 125:
        break;
      case 35:
        if (parentArgType === "plural" || parentArgType === "selectordinal") {
          break;
        }
        return null;
      default:
        return null;
    }
    this.bump();
    var codePoints = [this.char()];
    this.bump();
    while (!this.isEOF()) {
      var ch = this.char();
      if (ch === 39) {
        if (this.peek() === 39) {
          codePoints.push(39);
          this.bump();
        } else {
          this.bump();
          break;
        }
      } else {
        codePoints.push(ch);
      }
      this.bump();
    }
    return fromCodePoint.apply(void 0, codePoints);
  };
  Parser2.prototype.tryParseUnquoted = function(nestingLevel, parentArgType) {
    if (this.isEOF()) {
      return null;
    }
    var ch = this.char();
    if (ch === 60 || ch === 123 || ch === 35 && (parentArgType === "plural" || parentArgType === "selectordinal") || ch === 125 && nestingLevel > 0) {
      return null;
    } else {
      this.bump();
      return fromCodePoint(ch);
    }
  };
  Parser2.prototype.parseArgument = function(nestingLevel, expectingCloseTag) {
    var openingBracePosition = this.clonePosition();
    this.bump();
    this.bumpSpace();
    if (this.isEOF()) {
      return this.error(ErrorKind.EXPECT_ARGUMENT_CLOSING_BRACE, createLocation(openingBracePosition, this.clonePosition()));
    }
    if (this.char() === 125) {
      this.bump();
      return this.error(ErrorKind.EMPTY_ARGUMENT, createLocation(openingBracePosition, this.clonePosition()));
    }
    var value = this.parseIdentifierIfPossible().value;
    if (!value) {
      return this.error(ErrorKind.MALFORMED_ARGUMENT, createLocation(openingBracePosition, this.clonePosition()));
    }
    this.bumpSpace();
    if (this.isEOF()) {
      return this.error(ErrorKind.EXPECT_ARGUMENT_CLOSING_BRACE, createLocation(openingBracePosition, this.clonePosition()));
    }
    switch (this.char()) {
      case 125: {
        this.bump();
        return {
          val: {
            type: TYPE.argument,
            value,
            location: createLocation(openingBracePosition, this.clonePosition())
          },
          err: null
        };
      }
      case 44: {
        this.bump();
        this.bumpSpace();
        if (this.isEOF()) {
          return this.error(ErrorKind.EXPECT_ARGUMENT_CLOSING_BRACE, createLocation(openingBracePosition, this.clonePosition()));
        }
        return this.parseArgumentOptions(nestingLevel, expectingCloseTag, value, openingBracePosition);
      }
      default:
        return this.error(ErrorKind.MALFORMED_ARGUMENT, createLocation(openingBracePosition, this.clonePosition()));
    }
  };
  Parser2.prototype.parseIdentifierIfPossible = function() {
    var startingPosition = this.clonePosition();
    var startOffset = this.offset();
    var value = matchIdentifierAtIndex(this.message, startOffset);
    var endOffset = startOffset + value.length;
    this.bumpTo(endOffset);
    var endPosition = this.clonePosition();
    var location2 = createLocation(startingPosition, endPosition);
    return { value, location: location2 };
  };
  Parser2.prototype.parseArgumentOptions = function(nestingLevel, expectingCloseTag, value, openingBracePosition) {
    var _a2;
    var typeStartPosition = this.clonePosition();
    var argType = this.parseIdentifierIfPossible().value;
    var typeEndPosition = this.clonePosition();
    switch (argType) {
      case "":
        return this.error(ErrorKind.EXPECT_ARGUMENT_TYPE, createLocation(typeStartPosition, typeEndPosition));
      case "number":
      case "date":
      case "time": {
        this.bumpSpace();
        var styleAndLocation = null;
        if (this.bumpIf(",")) {
          this.bumpSpace();
          var styleStartPosition = this.clonePosition();
          var result = this.parseSimpleArgStyleIfPossible();
          if (result.err) {
            return result;
          }
          var style2 = trimEnd(result.val);
          if (style2.length === 0) {
            return this.error(ErrorKind.EXPECT_ARGUMENT_STYLE, createLocation(this.clonePosition(), this.clonePosition()));
          }
          var styleLocation = createLocation(styleStartPosition, this.clonePosition());
          styleAndLocation = { style: style2, styleLocation };
        }
        var argCloseResult = this.tryParseArgumentClose(openingBracePosition);
        if (argCloseResult.err) {
          return argCloseResult;
        }
        var location_1 = createLocation(openingBracePosition, this.clonePosition());
        if (styleAndLocation && startsWith(styleAndLocation === null || styleAndLocation === void 0 ? void 0 : styleAndLocation.style, "::", 0)) {
          var skeleton = trimStart(styleAndLocation.style.slice(2));
          if (argType === "number") {
            var result = this.parseNumberSkeletonFromString(skeleton, styleAndLocation.styleLocation);
            if (result.err) {
              return result;
            }
            return {
              val: { type: TYPE.number, value, location: location_1, style: result.val },
              err: null
            };
          } else {
            if (skeleton.length === 0) {
              return this.error(ErrorKind.EXPECT_DATE_TIME_SKELETON, location_1);
            }
            var style2 = {
              type: SKELETON_TYPE.dateTime,
              pattern: skeleton,
              location: styleAndLocation.styleLocation,
              parsedOptions: this.shouldParseSkeletons ? parseDateTimeSkeleton(skeleton) : {}
            };
            var type = argType === "date" ? TYPE.date : TYPE.time;
            return {
              val: { type, value, location: location_1, style: style2 },
              err: null
            };
          }
        }
        return {
          val: {
            type: argType === "number" ? TYPE.number : argType === "date" ? TYPE.date : TYPE.time,
            value,
            location: location_1,
            style: (_a2 = styleAndLocation === null || styleAndLocation === void 0 ? void 0 : styleAndLocation.style) !== null && _a2 !== void 0 ? _a2 : null
          },
          err: null
        };
      }
      case "plural":
      case "selectordinal":
      case "select": {
        var typeEndPosition_1 = this.clonePosition();
        this.bumpSpace();
        if (!this.bumpIf(",")) {
          return this.error(ErrorKind.EXPECT_SELECT_ARGUMENT_OPTIONS, createLocation(typeEndPosition_1, __assign({}, typeEndPosition_1)));
        }
        this.bumpSpace();
        var identifierAndLocation = this.parseIdentifierIfPossible();
        var pluralOffset = 0;
        if (argType !== "select" && identifierAndLocation.value === "offset") {
          if (!this.bumpIf(":")) {
            return this.error(ErrorKind.EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE, createLocation(this.clonePosition(), this.clonePosition()));
          }
          this.bumpSpace();
          var result = this.tryParseDecimalInteger(ErrorKind.EXPECT_PLURAL_ARGUMENT_OFFSET_VALUE, ErrorKind.INVALID_PLURAL_ARGUMENT_OFFSET_VALUE);
          if (result.err) {
            return result;
          }
          this.bumpSpace();
          identifierAndLocation = this.parseIdentifierIfPossible();
          pluralOffset = result.val;
        }
        var optionsResult = this.tryParsePluralOrSelectOptions(nestingLevel, argType, expectingCloseTag, identifierAndLocation);
        if (optionsResult.err) {
          return optionsResult;
        }
        var argCloseResult = this.tryParseArgumentClose(openingBracePosition);
        if (argCloseResult.err) {
          return argCloseResult;
        }
        var location_2 = createLocation(openingBracePosition, this.clonePosition());
        if (argType === "select") {
          return {
            val: {
              type: TYPE.select,
              value,
              options: fromEntries(optionsResult.val),
              location: location_2
            },
            err: null
          };
        } else {
          return {
            val: {
              type: TYPE.plural,
              value,
              options: fromEntries(optionsResult.val),
              offset: pluralOffset,
              pluralType: argType === "plural" ? "cardinal" : "ordinal",
              location: location_2
            },
            err: null
          };
        }
      }
      default:
        return this.error(ErrorKind.INVALID_ARGUMENT_TYPE, createLocation(typeStartPosition, typeEndPosition));
    }
  };
  Parser2.prototype.tryParseArgumentClose = function(openingBracePosition) {
    if (this.isEOF() || this.char() !== 125) {
      return this.error(ErrorKind.EXPECT_ARGUMENT_CLOSING_BRACE, createLocation(openingBracePosition, this.clonePosition()));
    }
    this.bump();
    return { val: true, err: null };
  };
  Parser2.prototype.parseSimpleArgStyleIfPossible = function() {
    var nestedBraces = 0;
    var startPosition = this.clonePosition();
    while (!this.isEOF()) {
      var ch = this.char();
      switch (ch) {
        case 39: {
          this.bump();
          var apostrophePosition = this.clonePosition();
          if (!this.bumpUntil("'")) {
            return this.error(ErrorKind.UNCLOSED_QUOTE_IN_ARGUMENT_STYLE, createLocation(apostrophePosition, this.clonePosition()));
          }
          this.bump();
          break;
        }
        case 123: {
          nestedBraces += 1;
          this.bump();
          break;
        }
        case 125: {
          if (nestedBraces > 0) {
            nestedBraces -= 1;
          } else {
            return {
              val: this.message.slice(startPosition.offset, this.offset()),
              err: null
            };
          }
          break;
        }
        default:
          this.bump();
          break;
      }
    }
    return {
      val: this.message.slice(startPosition.offset, this.offset()),
      err: null
    };
  };
  Parser2.prototype.parseNumberSkeletonFromString = function(skeleton, location2) {
    var tokens = [];
    try {
      tokens = parseNumberSkeletonFromString(skeleton);
    } catch (e2) {
      return this.error(ErrorKind.INVALID_NUMBER_SKELETON, location2);
    }
    return {
      val: {
        type: SKELETON_TYPE.number,
        tokens,
        location: location2,
        parsedOptions: this.shouldParseSkeletons ? parseNumberSkeleton(tokens) : {}
      },
      err: null
    };
  };
  Parser2.prototype.tryParsePluralOrSelectOptions = function(nestingLevel, parentArgType, expectCloseTag, parsedFirstIdentifier) {
    var _a2;
    var hasOtherClause = false;
    var options = [];
    var parsedSelectors = /* @__PURE__ */ new Set();
    var selector = parsedFirstIdentifier.value, selectorLocation = parsedFirstIdentifier.location;
    while (true) {
      if (selector.length === 0) {
        var startPosition = this.clonePosition();
        if (parentArgType !== "select" && this.bumpIf("=")) {
          var result = this.tryParseDecimalInteger(ErrorKind.EXPECT_PLURAL_ARGUMENT_SELECTOR, ErrorKind.INVALID_PLURAL_ARGUMENT_SELECTOR);
          if (result.err) {
            return result;
          }
          selectorLocation = createLocation(startPosition, this.clonePosition());
          selector = this.message.slice(startPosition.offset, this.offset());
        } else {
          break;
        }
      }
      if (parsedSelectors.has(selector)) {
        return this.error(parentArgType === "select" ? ErrorKind.DUPLICATE_SELECT_ARGUMENT_SELECTOR : ErrorKind.DUPLICATE_PLURAL_ARGUMENT_SELECTOR, selectorLocation);
      }
      if (selector === "other") {
        hasOtherClause = true;
      }
      this.bumpSpace();
      var openingBracePosition = this.clonePosition();
      if (!this.bumpIf("{")) {
        return this.error(parentArgType === "select" ? ErrorKind.EXPECT_SELECT_ARGUMENT_SELECTOR_FRAGMENT : ErrorKind.EXPECT_PLURAL_ARGUMENT_SELECTOR_FRAGMENT, createLocation(this.clonePosition(), this.clonePosition()));
      }
      var fragmentResult = this.parseMessage(nestingLevel + 1, parentArgType, expectCloseTag);
      if (fragmentResult.err) {
        return fragmentResult;
      }
      var argCloseResult = this.tryParseArgumentClose(openingBracePosition);
      if (argCloseResult.err) {
        return argCloseResult;
      }
      options.push([
        selector,
        {
          value: fragmentResult.val,
          location: createLocation(openingBracePosition, this.clonePosition())
        }
      ]);
      parsedSelectors.add(selector);
      this.bumpSpace();
      _a2 = this.parseIdentifierIfPossible(), selector = _a2.value, selectorLocation = _a2.location;
    }
    if (options.length === 0) {
      return this.error(parentArgType === "select" ? ErrorKind.EXPECT_SELECT_ARGUMENT_SELECTOR : ErrorKind.EXPECT_PLURAL_ARGUMENT_SELECTOR, createLocation(this.clonePosition(), this.clonePosition()));
    }
    if (this.requiresOtherClause && !hasOtherClause) {
      return this.error(ErrorKind.MISSING_OTHER_CLAUSE, createLocation(this.clonePosition(), this.clonePosition()));
    }
    return { val: options, err: null };
  };
  Parser2.prototype.tryParseDecimalInteger = function(expectNumberError, invalidNumberError) {
    var sign = 1;
    var startingPosition = this.clonePosition();
    if (this.bumpIf("+"))
      ;
    else if (this.bumpIf("-")) {
      sign = -1;
    }
    var hasDigits = false;
    var decimal = 0;
    while (!this.isEOF()) {
      var ch = this.char();
      if (ch >= 48 && ch <= 57) {
        hasDigits = true;
        decimal = decimal * 10 + (ch - 48);
        this.bump();
      } else {
        break;
      }
    }
    var location2 = createLocation(startingPosition, this.clonePosition());
    if (!hasDigits) {
      return this.error(expectNumberError, location2);
    }
    decimal *= sign;
    if (!isSafeInteger(decimal)) {
      return this.error(invalidNumberError, location2);
    }
    return { val: decimal, err: null };
  };
  Parser2.prototype.offset = function() {
    return this.position.offset;
  };
  Parser2.prototype.isEOF = function() {
    return this.offset() === this.message.length;
  };
  Parser2.prototype.clonePosition = function() {
    return {
      offset: this.position.offset,
      line: this.position.line,
      column: this.position.column
    };
  };
  Parser2.prototype.char = function() {
    var offset2 = this.position.offset;
    if (offset2 >= this.message.length) {
      throw Error("out of bound");
    }
    var code = codePointAt(this.message, offset2);
    if (code === void 0) {
      throw Error("Offset ".concat(offset2, " is at invalid UTF-16 code unit boundary"));
    }
    return code;
  };
  Parser2.prototype.error = function(kind, location2) {
    return {
      val: null,
      err: {
        kind,
        message: this.message,
        location: location2
      }
    };
  };
  Parser2.prototype.bump = function() {
    if (this.isEOF()) {
      return;
    }
    var code = this.char();
    if (code === 10) {
      this.position.line += 1;
      this.position.column = 1;
      this.position.offset += 1;
    } else {
      this.position.column += 1;
      this.position.offset += code < 65536 ? 1 : 2;
    }
  };
  Parser2.prototype.bumpIf = function(prefix2) {
    if (startsWith(this.message, prefix2, this.offset())) {
      for (var i2 = 0; i2 < prefix2.length; i2++) {
        this.bump();
      }
      return true;
    }
    return false;
  };
  Parser2.prototype.bumpUntil = function(pattern) {
    var currentOffset = this.offset();
    var index2 = this.message.indexOf(pattern, currentOffset);
    if (index2 >= 0) {
      this.bumpTo(index2);
      return true;
    } else {
      this.bumpTo(this.message.length);
      return false;
    }
  };
  Parser2.prototype.bumpTo = function(targetOffset) {
    if (this.offset() > targetOffset) {
      throw Error("targetOffset ".concat(targetOffset, " must be greater than or equal to the current offset ").concat(this.offset()));
    }
    targetOffset = Math.min(targetOffset, this.message.length);
    while (true) {
      var offset2 = this.offset();
      if (offset2 === targetOffset) {
        break;
      }
      if (offset2 > targetOffset) {
        throw Error("targetOffset ".concat(targetOffset, " is at invalid UTF-16 code unit boundary"));
      }
      this.bump();
      if (this.isEOF()) {
        break;
      }
    }
  };
  Parser2.prototype.bumpSpace = function() {
    while (!this.isEOF() && _isWhiteSpace(this.char())) {
      this.bump();
    }
  };
  Parser2.prototype.peek = function() {
    if (this.isEOF()) {
      return null;
    }
    var code = this.char();
    var offset2 = this.offset();
    var nextCode = this.message.charCodeAt(offset2 + (code >= 65536 ? 2 : 1));
    return nextCode !== null && nextCode !== void 0 ? nextCode : null;
  };
  return Parser2;
}();
function _isAlpha(codepoint) {
  return codepoint >= 97 && codepoint <= 122 || codepoint >= 65 && codepoint <= 90;
}
function _isAlphaOrSlash(codepoint) {
  return _isAlpha(codepoint) || codepoint === 47;
}
function _isPotentialElementNameChar(c2) {
  return c2 === 45 || c2 === 46 || c2 >= 48 && c2 <= 57 || c2 === 95 || c2 >= 97 && c2 <= 122 || c2 >= 65 && c2 <= 90 || c2 == 183 || c2 >= 192 && c2 <= 214 || c2 >= 216 && c2 <= 246 || c2 >= 248 && c2 <= 893 || c2 >= 895 && c2 <= 8191 || c2 >= 8204 && c2 <= 8205 || c2 >= 8255 && c2 <= 8256 || c2 >= 8304 && c2 <= 8591 || c2 >= 11264 && c2 <= 12271 || c2 >= 12289 && c2 <= 55295 || c2 >= 63744 && c2 <= 64975 || c2 >= 65008 && c2 <= 65533 || c2 >= 65536 && c2 <= 983039;
}
function _isWhiteSpace(c2) {
  return c2 >= 9 && c2 <= 13 || c2 === 32 || c2 === 133 || c2 >= 8206 && c2 <= 8207 || c2 === 8232 || c2 === 8233;
}
function _isPatternSyntax(c2) {
  return c2 >= 33 && c2 <= 35 || c2 === 36 || c2 >= 37 && c2 <= 39 || c2 === 40 || c2 === 41 || c2 === 42 || c2 === 43 || c2 === 44 || c2 === 45 || c2 >= 46 && c2 <= 47 || c2 >= 58 && c2 <= 59 || c2 >= 60 && c2 <= 62 || c2 >= 63 && c2 <= 64 || c2 === 91 || c2 === 92 || c2 === 93 || c2 === 94 || c2 === 96 || c2 === 123 || c2 === 124 || c2 === 125 || c2 === 126 || c2 === 161 || c2 >= 162 && c2 <= 165 || c2 === 166 || c2 === 167 || c2 === 169 || c2 === 171 || c2 === 172 || c2 === 174 || c2 === 176 || c2 === 177 || c2 === 182 || c2 === 187 || c2 === 191 || c2 === 215 || c2 === 247 || c2 >= 8208 && c2 <= 8213 || c2 >= 8214 && c2 <= 8215 || c2 === 8216 || c2 === 8217 || c2 === 8218 || c2 >= 8219 && c2 <= 8220 || c2 === 8221 || c2 === 8222 || c2 === 8223 || c2 >= 8224 && c2 <= 8231 || c2 >= 8240 && c2 <= 8248 || c2 === 8249 || c2 === 8250 || c2 >= 8251 && c2 <= 8254 || c2 >= 8257 && c2 <= 8259 || c2 === 8260 || c2 === 8261 || c2 === 8262 || c2 >= 8263 && c2 <= 8273 || c2 === 8274 || c2 === 8275 || c2 >= 8277 && c2 <= 8286 || c2 >= 8592 && c2 <= 8596 || c2 >= 8597 && c2 <= 8601 || c2 >= 8602 && c2 <= 8603 || c2 >= 8604 && c2 <= 8607 || c2 === 8608 || c2 >= 8609 && c2 <= 8610 || c2 === 8611 || c2 >= 8612 && c2 <= 8613 || c2 === 8614 || c2 >= 8615 && c2 <= 8621 || c2 === 8622 || c2 >= 8623 && c2 <= 8653 || c2 >= 8654 && c2 <= 8655 || c2 >= 8656 && c2 <= 8657 || c2 === 8658 || c2 === 8659 || c2 === 8660 || c2 >= 8661 && c2 <= 8691 || c2 >= 8692 && c2 <= 8959 || c2 >= 8960 && c2 <= 8967 || c2 === 8968 || c2 === 8969 || c2 === 8970 || c2 === 8971 || c2 >= 8972 && c2 <= 8991 || c2 >= 8992 && c2 <= 8993 || c2 >= 8994 && c2 <= 9e3 || c2 === 9001 || c2 === 9002 || c2 >= 9003 && c2 <= 9083 || c2 === 9084 || c2 >= 9085 && c2 <= 9114 || c2 >= 9115 && c2 <= 9139 || c2 >= 9140 && c2 <= 9179 || c2 >= 9180 && c2 <= 9185 || c2 >= 9186 && c2 <= 9254 || c2 >= 9255 && c2 <= 9279 || c2 >= 9280 && c2 <= 9290 || c2 >= 9291 && c2 <= 9311 || c2 >= 9472 && c2 <= 9654 || c2 === 9655 || c2 >= 9656 && c2 <= 9664 || c2 === 9665 || c2 >= 9666 && c2 <= 9719 || c2 >= 9720 && c2 <= 9727 || c2 >= 9728 && c2 <= 9838 || c2 === 9839 || c2 >= 9840 && c2 <= 10087 || c2 === 10088 || c2 === 10089 || c2 === 10090 || c2 === 10091 || c2 === 10092 || c2 === 10093 || c2 === 10094 || c2 === 10095 || c2 === 10096 || c2 === 10097 || c2 === 10098 || c2 === 10099 || c2 === 10100 || c2 === 10101 || c2 >= 10132 && c2 <= 10175 || c2 >= 10176 && c2 <= 10180 || c2 === 10181 || c2 === 10182 || c2 >= 10183 && c2 <= 10213 || c2 === 10214 || c2 === 10215 || c2 === 10216 || c2 === 10217 || c2 === 10218 || c2 === 10219 || c2 === 10220 || c2 === 10221 || c2 === 10222 || c2 === 10223 || c2 >= 10224 && c2 <= 10239 || c2 >= 10240 && c2 <= 10495 || c2 >= 10496 && c2 <= 10626 || c2 === 10627 || c2 === 10628 || c2 === 10629 || c2 === 10630 || c2 === 10631 || c2 === 10632 || c2 === 10633 || c2 === 10634 || c2 === 10635 || c2 === 10636 || c2 === 10637 || c2 === 10638 || c2 === 10639 || c2 === 10640 || c2 === 10641 || c2 === 10642 || c2 === 10643 || c2 === 10644 || c2 === 10645 || c2 === 10646 || c2 === 10647 || c2 === 10648 || c2 >= 10649 && c2 <= 10711 || c2 === 10712 || c2 === 10713 || c2 === 10714 || c2 === 10715 || c2 >= 10716 && c2 <= 10747 || c2 === 10748 || c2 === 10749 || c2 >= 10750 && c2 <= 11007 || c2 >= 11008 && c2 <= 11055 || c2 >= 11056 && c2 <= 11076 || c2 >= 11077 && c2 <= 11078 || c2 >= 11079 && c2 <= 11084 || c2 >= 11085 && c2 <= 11123 || c2 >= 11124 && c2 <= 11125 || c2 >= 11126 && c2 <= 11157 || c2 === 11158 || c2 >= 11159 && c2 <= 11263 || c2 >= 11776 && c2 <= 11777 || c2 === 11778 || c2 === 11779 || c2 === 11780 || c2 === 11781 || c2 >= 11782 && c2 <= 11784 || c2 === 11785 || c2 === 11786 || c2 === 11787 || c2 === 11788 || c2 === 11789 || c2 >= 11790 && c2 <= 11798 || c2 === 11799 || c2 >= 11800 && c2 <= 11801 || c2 === 11802 || c2 === 11803 || c2 === 11804 || c2 === 11805 || c2 >= 11806 && c2 <= 11807 || c2 === 11808 || c2 === 11809 || c2 === 11810 || c2 === 11811 || c2 === 11812 || c2 === 11813 || c2 === 11814 || c2 === 11815 || c2 === 11816 || c2 === 11817 || c2 >= 11818 && c2 <= 11822 || c2 === 11823 || c2 >= 11824 && c2 <= 11833 || c2 >= 11834 && c2 <= 11835 || c2 >= 11836 && c2 <= 11839 || c2 === 11840 || c2 === 11841 || c2 === 11842 || c2 >= 11843 && c2 <= 11855 || c2 >= 11856 && c2 <= 11857 || c2 === 11858 || c2 >= 11859 && c2 <= 11903 || c2 >= 12289 && c2 <= 12291 || c2 === 12296 || c2 === 12297 || c2 === 12298 || c2 === 12299 || c2 === 12300 || c2 === 12301 || c2 === 12302 || c2 === 12303 || c2 === 12304 || c2 === 12305 || c2 >= 12306 && c2 <= 12307 || c2 === 12308 || c2 === 12309 || c2 === 12310 || c2 === 12311 || c2 === 12312 || c2 === 12313 || c2 === 12314 || c2 === 12315 || c2 === 12316 || c2 === 12317 || c2 >= 12318 && c2 <= 12319 || c2 === 12320 || c2 === 12336 || c2 === 64830 || c2 === 64831 || c2 >= 65093 && c2 <= 65094;
}
function pruneLocation(els) {
  els.forEach(function(el) {
    delete el.location;
    if (isSelectElement(el) || isPluralElement(el)) {
      for (var k2 in el.options) {
        delete el.options[k2].location;
        pruneLocation(el.options[k2].value);
      }
    } else if (isNumberElement(el) && isNumberSkeleton(el.style)) {
      delete el.style.location;
    } else if ((isDateElement(el) || isTimeElement(el)) && isDateTimeSkeleton(el.style)) {
      delete el.style.location;
    } else if (isTagElement(el)) {
      pruneLocation(el.children);
    }
  });
}
function parse$2(message, opts) {
  if (opts === void 0) {
    opts = {};
  }
  opts = __assign({ shouldParseSkeletons: true, requiresOtherClause: true }, opts);
  var result = new Parser(message, opts).parse();
  if (result.err) {
    var error = SyntaxError(ErrorKind[result.err.kind]);
    error.location = result.err.location;
    error.originalMessage = result.err.message;
    throw error;
  }
  if (!(opts === null || opts === void 0 ? void 0 : opts.captureLocation)) {
    pruneLocation(result.val);
  }
  return result.val;
}
function memoize(fn2, options) {
  var cache = options && options.cache ? options.cache : cacheDefault;
  var serializer = options && options.serializer ? options.serializer : serializerDefault;
  var strategy = options && options.strategy ? options.strategy : strategyDefault;
  return strategy(fn2, {
    cache,
    serializer
  });
}
function isPrimitive(value) {
  return value == null || typeof value === "number" || typeof value === "boolean";
}
function monadic(fn2, cache, serializer, arg) {
  var cacheKey = isPrimitive(arg) ? arg : serializer(arg);
  var computedValue = cache.get(cacheKey);
  if (typeof computedValue === "undefined") {
    computedValue = fn2.call(this, arg);
    cache.set(cacheKey, computedValue);
  }
  return computedValue;
}
function variadic(fn2, cache, serializer) {
  var args = Array.prototype.slice.call(arguments, 3);
  var cacheKey = serializer(args);
  var computedValue = cache.get(cacheKey);
  if (typeof computedValue === "undefined") {
    computedValue = fn2.apply(this, args);
    cache.set(cacheKey, computedValue);
  }
  return computedValue;
}
function assemble(fn2, context, strategy, cache, serialize) {
  return strategy.bind(context, fn2, cache, serialize);
}
function strategyDefault(fn2, options) {
  var strategy = fn2.length === 1 ? monadic : variadic;
  return assemble(fn2, this, strategy, options.cache.create(), options.serializer);
}
function strategyVariadic(fn2, options) {
  return assemble(fn2, this, variadic, options.cache.create(), options.serializer);
}
function strategyMonadic(fn2, options) {
  return assemble(fn2, this, monadic, options.cache.create(), options.serializer);
}
var serializerDefault = function() {
  return JSON.stringify(arguments);
};
function ObjectWithoutPrototypeCache() {
  this.cache = /* @__PURE__ */ Object.create(null);
}
ObjectWithoutPrototypeCache.prototype.get = function(key) {
  return this.cache[key];
};
ObjectWithoutPrototypeCache.prototype.set = function(key, value) {
  this.cache[key] = value;
};
var cacheDefault = {
  create: function create() {
    return new ObjectWithoutPrototypeCache();
  }
};
var strategies = {
  variadic: strategyVariadic,
  monadic: strategyMonadic
};
var ErrorCode;
(function(ErrorCode2) {
  ErrorCode2["MISSING_VALUE"] = "MISSING_VALUE";
  ErrorCode2["INVALID_VALUE"] = "INVALID_VALUE";
  ErrorCode2["MISSING_INTL_API"] = "MISSING_INTL_API";
})(ErrorCode || (ErrorCode = {}));
var FormatError = function(_super) {
  __extends(FormatError2, _super);
  function FormatError2(msg, code, originalMessage) {
    var _this = _super.call(this, msg) || this;
    _this.code = code;
    _this.originalMessage = originalMessage;
    return _this;
  }
  FormatError2.prototype.toString = function() {
    return "[formatjs Error: ".concat(this.code, "] ").concat(this.message);
  };
  return FormatError2;
}(Error);
var InvalidValueError = function(_super) {
  __extends(InvalidValueError2, _super);
  function InvalidValueError2(variableId, value, options, originalMessage) {
    return _super.call(this, 'Invalid values for "'.concat(variableId, '": "').concat(value, '". Options are "').concat(Object.keys(options).join('", "'), '"'), ErrorCode.INVALID_VALUE, originalMessage) || this;
  }
  return InvalidValueError2;
}(FormatError);
var InvalidValueTypeError = function(_super) {
  __extends(InvalidValueTypeError2, _super);
  function InvalidValueTypeError2(value, type, originalMessage) {
    return _super.call(this, 'Value for "'.concat(value, '" must be of type ').concat(type), ErrorCode.INVALID_VALUE, originalMessage) || this;
  }
  return InvalidValueTypeError2;
}(FormatError);
var MissingValueError = function(_super) {
  __extends(MissingValueError2, _super);
  function MissingValueError2(variableId, originalMessage) {
    return _super.call(this, 'The intl string context variable "'.concat(variableId, '" was not provided to the string "').concat(originalMessage, '"'), ErrorCode.MISSING_VALUE, originalMessage) || this;
  }
  return MissingValueError2;
}(FormatError);
var PART_TYPE;
(function(PART_TYPE2) {
  PART_TYPE2[PART_TYPE2["literal"] = 0] = "literal";
  PART_TYPE2[PART_TYPE2["object"] = 1] = "object";
})(PART_TYPE || (PART_TYPE = {}));
function mergeLiteral(parts) {
  if (parts.length < 2) {
    return parts;
  }
  return parts.reduce(function(all, part) {
    var lastPart = all[all.length - 1];
    if (!lastPart || lastPart.type !== PART_TYPE.literal || part.type !== PART_TYPE.literal) {
      all.push(part);
    } else {
      lastPart.value += part.value;
    }
    return all;
  }, []);
}
function isFormatXMLElementFn(el) {
  return typeof el === "function";
}
function formatToParts(els, locales, formatters, formats, values, currentPluralValue, originalMessage) {
  if (els.length === 1 && isLiteralElement(els[0])) {
    return [
      {
        type: PART_TYPE.literal,
        value: els[0].value
      }
    ];
  }
  var result = [];
  for (var _i = 0, els_1 = els; _i < els_1.length; _i++) {
    var el = els_1[_i];
    if (isLiteralElement(el)) {
      result.push({
        type: PART_TYPE.literal,
        value: el.value
      });
      continue;
    }
    if (isPoundElement(el)) {
      if (typeof currentPluralValue === "number") {
        result.push({
          type: PART_TYPE.literal,
          value: formatters.getNumberFormat(locales).format(currentPluralValue)
        });
      }
      continue;
    }
    var varName = el.value;
    if (!(values && varName in values)) {
      throw new MissingValueError(varName, originalMessage);
    }
    var value = values[varName];
    if (isArgumentElement(el)) {
      if (!value || typeof value === "string" || typeof value === "number") {
        value = typeof value === "string" || typeof value === "number" ? String(value) : "";
      }
      result.push({
        type: typeof value === "string" ? PART_TYPE.literal : PART_TYPE.object,
        value
      });
      continue;
    }
    if (isDateElement(el)) {
      var style2 = typeof el.style === "string" ? formats.date[el.style] : isDateTimeSkeleton(el.style) ? el.style.parsedOptions : void 0;
      result.push({
        type: PART_TYPE.literal,
        value: formatters.getDateTimeFormat(locales, style2).format(value)
      });
      continue;
    }
    if (isTimeElement(el)) {
      var style2 = typeof el.style === "string" ? formats.time[el.style] : isDateTimeSkeleton(el.style) ? el.style.parsedOptions : void 0;
      result.push({
        type: PART_TYPE.literal,
        value: formatters.getDateTimeFormat(locales, style2).format(value)
      });
      continue;
    }
    if (isNumberElement(el)) {
      var style2 = typeof el.style === "string" ? formats.number[el.style] : isNumberSkeleton(el.style) ? el.style.parsedOptions : void 0;
      if (style2 && style2.scale) {
        value = value * (style2.scale || 1);
      }
      result.push({
        type: PART_TYPE.literal,
        value: formatters.getNumberFormat(locales, style2).format(value)
      });
      continue;
    }
    if (isTagElement(el)) {
      var children = el.children, value_1 = el.value;
      var formatFn = values[value_1];
      if (!isFormatXMLElementFn(formatFn)) {
        throw new InvalidValueTypeError(value_1, "function", originalMessage);
      }
      var parts = formatToParts(children, locales, formatters, formats, values, currentPluralValue);
      var chunks = formatFn(parts.map(function(p2) {
        return p2.value;
      }));
      if (!Array.isArray(chunks)) {
        chunks = [chunks];
      }
      result.push.apply(result, chunks.map(function(c2) {
        return {
          type: typeof c2 === "string" ? PART_TYPE.literal : PART_TYPE.object,
          value: c2
        };
      }));
    }
    if (isSelectElement(el)) {
      var opt = el.options[value] || el.options.other;
      if (!opt) {
        throw new InvalidValueError(el.value, value, Object.keys(el.options), originalMessage);
      }
      result.push.apply(result, formatToParts(opt.value, locales, formatters, formats, values));
      continue;
    }
    if (isPluralElement(el)) {
      var opt = el.options["=".concat(value)];
      if (!opt) {
        if (!Intl.PluralRules) {
          throw new FormatError('Intl.PluralRules is not available in this environment.\nTry polyfilling it using "@formatjs/intl-pluralrules"\n', ErrorCode.MISSING_INTL_API, originalMessage);
        }
        var rule = formatters.getPluralRules(locales, { type: el.pluralType }).select(value - (el.offset || 0));
        opt = el.options[rule] || el.options.other;
      }
      if (!opt) {
        throw new InvalidValueError(el.value, value, Object.keys(el.options), originalMessage);
      }
      result.push.apply(result, formatToParts(opt.value, locales, formatters, formats, values, value - (el.offset || 0)));
      continue;
    }
  }
  return mergeLiteral(result);
}
function mergeConfig$1(c1, c2) {
  if (!c2) {
    return c1;
  }
  return __assign(__assign(__assign({}, c1 || {}), c2 || {}), Object.keys(c1).reduce(function(all, k2) {
    all[k2] = __assign(__assign({}, c1[k2]), c2[k2] || {});
    return all;
  }, {}));
}
function mergeConfigs(defaultConfig, configs) {
  if (!configs) {
    return defaultConfig;
  }
  return Object.keys(defaultConfig).reduce(function(all, k2) {
    all[k2] = mergeConfig$1(defaultConfig[k2], configs[k2]);
    return all;
  }, __assign({}, defaultConfig));
}
function createFastMemoizeCache$1(store) {
  return {
    create: function() {
      return {
        get: function(key) {
          return store[key];
        },
        set: function(key, value) {
          store[key] = value;
        }
      };
    }
  };
}
function createDefaultFormatters(cache) {
  if (cache === void 0) {
    cache = {
      number: {},
      dateTime: {},
      pluralRules: {}
    };
  }
  return {
    getNumberFormat: memoize(function() {
      var _a2;
      var args = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
      }
      return new ((_a2 = Intl.NumberFormat).bind.apply(_a2, __spreadArray([void 0], args, false)))();
    }, {
      cache: createFastMemoizeCache$1(cache.number),
      strategy: strategies.variadic
    }),
    getDateTimeFormat: memoize(function() {
      var _a2;
      var args = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
      }
      return new ((_a2 = Intl.DateTimeFormat).bind.apply(_a2, __spreadArray([void 0], args, false)))();
    }, {
      cache: createFastMemoizeCache$1(cache.dateTime),
      strategy: strategies.variadic
    }),
    getPluralRules: memoize(function() {
      var _a2;
      var args = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
      }
      return new ((_a2 = Intl.PluralRules).bind.apply(_a2, __spreadArray([void 0], args, false)))();
    }, {
      cache: createFastMemoizeCache$1(cache.pluralRules),
      strategy: strategies.variadic
    })
  };
}
var IntlMessageFormat = function() {
  function IntlMessageFormat2(message, locales, overrideFormats, opts) {
    var _this = this;
    if (locales === void 0) {
      locales = IntlMessageFormat2.defaultLocale;
    }
    this.formatterCache = {
      number: {},
      dateTime: {},
      pluralRules: {}
    };
    this.format = function(values) {
      var parts = _this.formatToParts(values);
      if (parts.length === 1) {
        return parts[0].value;
      }
      var result = parts.reduce(function(all, part) {
        if (!all.length || part.type !== PART_TYPE.literal || typeof all[all.length - 1] !== "string") {
          all.push(part.value);
        } else {
          all[all.length - 1] += part.value;
        }
        return all;
      }, []);
      if (result.length <= 1) {
        return result[0] || "";
      }
      return result;
    };
    this.formatToParts = function(values) {
      return formatToParts(_this.ast, _this.locales, _this.formatters, _this.formats, values, void 0, _this.message);
    };
    this.resolvedOptions = function() {
      return {
        locale: Intl.NumberFormat.supportedLocalesOf(_this.locales)[0]
      };
    };
    this.getAst = function() {
      return _this.ast;
    };
    if (typeof message === "string") {
      this.message = message;
      if (!IntlMessageFormat2.__parse) {
        throw new TypeError("IntlMessageFormat.__parse must be set to process `message` of type `string`");
      }
      this.ast = IntlMessageFormat2.__parse(message, {
        ignoreTag: opts === null || opts === void 0 ? void 0 : opts.ignoreTag
      });
    } else {
      this.ast = message;
    }
    if (!Array.isArray(this.ast)) {
      throw new TypeError("A message must be provided as a String or AST.");
    }
    this.formats = mergeConfigs(IntlMessageFormat2.formats, overrideFormats);
    this.locales = locales;
    this.formatters = opts && opts.formatters || createDefaultFormatters(this.formatterCache);
  }
  Object.defineProperty(IntlMessageFormat2, "defaultLocale", {
    get: function() {
      if (!IntlMessageFormat2.memoizedDefaultLocale) {
        IntlMessageFormat2.memoizedDefaultLocale = new Intl.NumberFormat().resolvedOptions().locale;
      }
      return IntlMessageFormat2.memoizedDefaultLocale;
    },
    enumerable: false,
    configurable: true
  });
  IntlMessageFormat2.memoizedDefaultLocale = null;
  IntlMessageFormat2.__parse = parse$2;
  IntlMessageFormat2.formats = {
    number: {
      integer: {
        maximumFractionDigits: 0
      },
      currency: {
        style: "currency"
      },
      percent: {
        style: "percent"
      }
    },
    date: {
      short: {
        month: "numeric",
        day: "numeric",
        year: "2-digit"
      },
      medium: {
        month: "short",
        day: "numeric",
        year: "numeric"
      },
      long: {
        month: "long",
        day: "numeric",
        year: "numeric"
      },
      full: {
        weekday: "long",
        month: "long",
        day: "numeric",
        year: "numeric"
      }
    },
    time: {
      short: {
        hour: "numeric",
        minute: "numeric"
      },
      medium: {
        hour: "numeric",
        minute: "numeric",
        second: "numeric"
      },
      long: {
        hour: "numeric",
        minute: "numeric",
        second: "numeric",
        timeZoneName: "short"
      },
      full: {
        hour: "numeric",
        minute: "numeric",
        second: "numeric",
        timeZoneName: "short"
      }
    }
  };
  return IntlMessageFormat2;
}();
var $1Ofoe$intlmessageformat = IntlMessageFormat;
var IntlErrorCode;
(function(IntlErrorCode2) {
  IntlErrorCode2["FORMAT_ERROR"] = "FORMAT_ERROR";
  IntlErrorCode2["UNSUPPORTED_FORMATTER"] = "UNSUPPORTED_FORMATTER";
  IntlErrorCode2["INVALID_CONFIG"] = "INVALID_CONFIG";
  IntlErrorCode2["MISSING_DATA"] = "MISSING_DATA";
  IntlErrorCode2["MISSING_TRANSLATION"] = "MISSING_TRANSLATION";
})(IntlErrorCode || (IntlErrorCode = {}));
var IntlError = function(_super) {
  __extends(IntlError2, _super);
  function IntlError2(code, message, exception) {
    var _this = this;
    var err = exception ? exception instanceof Error ? exception : new Error(String(exception)) : void 0;
    _this = _super.call(this, "[@formatjs/intl Error ".concat(code, "] ").concat(message, " \n").concat(err ? "\n".concat(err.message, "\n").concat(err.stack) : "")) || this;
    _this.code = code;
    if (typeof Error.captureStackTrace === "function") {
      Error.captureStackTrace(_this, IntlError2);
    }
    return _this;
  }
  return IntlError2;
}(Error);
var UnsupportedFormatterError = function(_super) {
  __extends(UnsupportedFormatterError2, _super);
  function UnsupportedFormatterError2(message, exception) {
    return _super.call(this, IntlErrorCode.UNSUPPORTED_FORMATTER, message, exception) || this;
  }
  return UnsupportedFormatterError2;
}(IntlError);
var InvalidConfigError = function(_super) {
  __extends(InvalidConfigError2, _super);
  function InvalidConfigError2(message, exception) {
    return _super.call(this, IntlErrorCode.INVALID_CONFIG, message, exception) || this;
  }
  return InvalidConfigError2;
}(IntlError);
var MissingDataError = function(_super) {
  __extends(MissingDataError2, _super);
  function MissingDataError2(message, exception) {
    return _super.call(this, IntlErrorCode.MISSING_DATA, message, exception) || this;
  }
  return MissingDataError2;
}(IntlError);
var IntlFormatError = function(_super) {
  __extends(IntlFormatError2, _super);
  function IntlFormatError2(message, locale, exception) {
    return _super.call(this, IntlErrorCode.FORMAT_ERROR, "".concat(message, " \nLocale: ").concat(locale, "\n"), exception) || this;
  }
  return IntlFormatError2;
}(IntlError);
var MessageFormatError = function(_super) {
  __extends(MessageFormatError2, _super);
  function MessageFormatError2(message, locale, descriptor, exception) {
    var _this = _super.call(this, "".concat(message, " \nMessageID: ").concat(descriptor === null || descriptor === void 0 ? void 0 : descriptor.id, "\nDefault Message: ").concat(descriptor === null || descriptor === void 0 ? void 0 : descriptor.defaultMessage, "\nDescription: ").concat(descriptor === null || descriptor === void 0 ? void 0 : descriptor.description, " \n"), locale, exception) || this;
    _this.descriptor = descriptor;
    return _this;
  }
  return MessageFormatError2;
}(IntlFormatError);
var MissingTranslationError = function(_super) {
  __extends(MissingTranslationError2, _super);
  function MissingTranslationError2(descriptor, locale) {
    var _this = _super.call(this, IntlErrorCode.MISSING_TRANSLATION, 'Missing message: "'.concat(descriptor.id, '" for locale "').concat(locale, '", using ').concat(descriptor.defaultMessage ? "default message" : "id", " as fallback.")) || this;
    _this.descriptor = descriptor;
    return _this;
  }
  return MissingTranslationError2;
}(IntlError);
function filterProps$1(props2, allowlist, defaults) {
  if (defaults === void 0) {
    defaults = {};
  }
  return allowlist.reduce(function(filtered, name) {
    if (name in props2) {
      filtered[name] = props2[name];
    } else if (name in defaults) {
      filtered[name] = defaults[name];
    }
    return filtered;
  }, {});
}
var defaultErrorHandler = function(error) {
};
var DEFAULT_INTL_CONFIG$1 = {
  formats: {},
  messages: {},
  timeZone: void 0,
  defaultLocale: "en",
  defaultFormats: {},
  fallbackOnEmptyString: true,
  onError: defaultErrorHandler
};
function createIntlCache() {
  return {
    dateTime: {},
    number: {},
    message: {},
    relativeTime: {},
    pluralRules: {},
    list: {},
    displayNames: {}
  };
}
function createFastMemoizeCache(store) {
  return {
    create: function() {
      return {
        get: function(key) {
          return store[key];
        },
        set: function(key, value) {
          store[key] = value;
        }
      };
    }
  };
}
function createFormatters(cache) {
  if (cache === void 0) {
    cache = createIntlCache();
  }
  var RelativeTimeFormat = Intl.RelativeTimeFormat;
  var ListFormat = Intl.ListFormat;
  var DisplayNames = Intl.DisplayNames;
  var getDateTimeFormat = memoize(function() {
    var _a2;
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
      args[_i] = arguments[_i];
    }
    return new ((_a2 = Intl.DateTimeFormat).bind.apply(_a2, __spreadArray([void 0], args, false)))();
  }, {
    cache: createFastMemoizeCache(cache.dateTime),
    strategy: strategies.variadic
  });
  var getNumberFormat = memoize(function() {
    var _a2;
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
      args[_i] = arguments[_i];
    }
    return new ((_a2 = Intl.NumberFormat).bind.apply(_a2, __spreadArray([void 0], args, false)))();
  }, {
    cache: createFastMemoizeCache(cache.number),
    strategy: strategies.variadic
  });
  var getPluralRules = memoize(function() {
    var _a2;
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
      args[_i] = arguments[_i];
    }
    return new ((_a2 = Intl.PluralRules).bind.apply(_a2, __spreadArray([void 0], args, false)))();
  }, {
    cache: createFastMemoizeCache(cache.pluralRules),
    strategy: strategies.variadic
  });
  return {
    getDateTimeFormat,
    getNumberFormat,
    getMessageFormat: memoize(function(message, locales, overrideFormats, opts) {
      return new IntlMessageFormat(message, locales, overrideFormats, __assign({ formatters: {
        getNumberFormat,
        getDateTimeFormat,
        getPluralRules
      } }, opts || {}));
    }, {
      cache: createFastMemoizeCache(cache.message),
      strategy: strategies.variadic
    }),
    getRelativeTimeFormat: memoize(function() {
      var args = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
      }
      return new (RelativeTimeFormat.bind.apply(RelativeTimeFormat, __spreadArray([void 0], args, false)))();
    }, {
      cache: createFastMemoizeCache(cache.relativeTime),
      strategy: strategies.variadic
    }),
    getPluralRules,
    getListFormat: memoize(function() {
      var args = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
      }
      return new (ListFormat.bind.apply(ListFormat, __spreadArray([void 0], args, false)))();
    }, {
      cache: createFastMemoizeCache(cache.list),
      strategy: strategies.variadic
    }),
    getDisplayNames: memoize(function() {
      var args = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
      }
      return new (DisplayNames.bind.apply(DisplayNames, __spreadArray([void 0], args, false)))();
    }, {
      cache: createFastMemoizeCache(cache.displayNames),
      strategy: strategies.variadic
    })
  };
}
function getNamedFormat(formats, type, name, onError) {
  var formatType = formats && formats[type];
  var format;
  if (formatType) {
    format = formatType[name];
  }
  if (format) {
    return format;
  }
  onError(new UnsupportedFormatterError("No ".concat(type, " format named: ").concat(name)));
}
function setTimeZoneInOptions(opts, timeZone) {
  return Object.keys(opts).reduce(function(all, k2) {
    all[k2] = __assign({ timeZone }, opts[k2]);
    return all;
  }, {});
}
function deepMergeOptions(opts1, opts2) {
  var keys = Object.keys(__assign(__assign({}, opts1), opts2));
  return keys.reduce(function(all, k2) {
    all[k2] = __assign(__assign({}, opts1[k2] || {}), opts2[k2] || {});
    return all;
  }, {});
}
function deepMergeFormatsAndSetTimeZone(f1, timeZone) {
  if (!timeZone) {
    return f1;
  }
  var mfFormats = IntlMessageFormat.formats;
  return __assign(__assign(__assign({}, mfFormats), f1), { date: deepMergeOptions(setTimeZoneInOptions(mfFormats.date, timeZone), setTimeZoneInOptions(f1.date || {}, timeZone)), time: deepMergeOptions(setTimeZoneInOptions(mfFormats.time, timeZone), setTimeZoneInOptions(f1.time || {}, timeZone)) });
}
function formatMessage$1(_a2, state2, messageDescriptor, values, opts) {
  var locale = _a2.locale, formats = _a2.formats, messages2 = _a2.messages, defaultLocale = _a2.defaultLocale, defaultFormats = _a2.defaultFormats, fallbackOnEmptyString = _a2.fallbackOnEmptyString, onError = _a2.onError, timeZone = _a2.timeZone, defaultRichTextElements = _a2.defaultRichTextElements;
  if (messageDescriptor === void 0) {
    messageDescriptor = { id: "" };
  }
  var msgId = messageDescriptor.id, defaultMessage = messageDescriptor.defaultMessage;
  invariant$1(!!msgId, "[@formatjs/intl] An `id` must be provided to format a message. You can either:\n1. Configure your build toolchain with [babel-plugin-formatjs](https://formatjs.io/docs/tooling/babel-plugin)\nor [@formatjs/ts-transformer](https://formatjs.io/docs/tooling/ts-transformer) OR\n2. Configure your `eslint` config to include [eslint-plugin-formatjs](https://formatjs.io/docs/tooling/linter#enforce-id)\nto autofix this issue");
  var id2 = String(msgId);
  var message = messages2 && Object.prototype.hasOwnProperty.call(messages2, id2) && messages2[id2];
  if (Array.isArray(message) && message.length === 1 && message[0].type === TYPE.literal) {
    return message[0].value;
  }
  if (!values && message && typeof message === "string" && !defaultRichTextElements) {
    return message.replace(/'\{(.*?)\}'/gi, "{$1}");
  }
  values = __assign(__assign({}, defaultRichTextElements), values || {});
  formats = deepMergeFormatsAndSetTimeZone(formats, timeZone);
  defaultFormats = deepMergeFormatsAndSetTimeZone(defaultFormats, timeZone);
  if (!message) {
    if (fallbackOnEmptyString === false && message === "") {
      return message;
    }
    if (!defaultMessage || locale && locale.toLowerCase() !== defaultLocale.toLowerCase()) {
      onError(new MissingTranslationError(messageDescriptor, locale));
    }
    if (defaultMessage) {
      try {
        var formatter = state2.getMessageFormat(defaultMessage, defaultLocale, defaultFormats, opts);
        return formatter.format(values);
      } catch (e2) {
        onError(new MessageFormatError('Error formatting default message for: "'.concat(id2, '", rendering default message verbatim'), locale, messageDescriptor, e2));
        return typeof defaultMessage === "string" ? defaultMessage : id2;
      }
    }
    return id2;
  }
  try {
    var formatter = state2.getMessageFormat(message, locale, formats, __assign({ formatters: state2 }, opts || {}));
    return formatter.format(values);
  } catch (e2) {
    onError(new MessageFormatError('Error formatting message: "'.concat(id2, '", using ').concat(defaultMessage ? "default message" : "id", " as fallback."), locale, messageDescriptor, e2));
  }
  if (defaultMessage) {
    try {
      var formatter = state2.getMessageFormat(defaultMessage, defaultLocale, defaultFormats, opts);
      return formatter.format(values);
    } catch (e2) {
      onError(new MessageFormatError('Error formatting the default message for: "'.concat(id2, '", rendering message verbatim'), locale, messageDescriptor, e2));
    }
  }
  if (typeof message === "string") {
    return message;
  }
  if (typeof defaultMessage === "string") {
    return defaultMessage;
  }
  return id2;
}
var DATE_TIME_FORMAT_OPTIONS = [
  "localeMatcher",
  "formatMatcher",
  "timeZone",
  "hour12",
  "weekday",
  "era",
  "year",
  "month",
  "day",
  "hour",
  "minute",
  "second",
  "timeZoneName",
  "hourCycle",
  "dateStyle",
  "timeStyle",
  "calendar",
  "numberingSystem"
];
function getFormatter$2(_a2, type, getDateTimeFormat, options) {
  var locale = _a2.locale, formats = _a2.formats, onError = _a2.onError, timeZone = _a2.timeZone;
  if (options === void 0) {
    options = {};
  }
  var format = options.format;
  var defaults = __assign(__assign({}, timeZone && { timeZone }), format && getNamedFormat(formats, type, format, onError));
  var filteredOptions = filterProps$1(options, DATE_TIME_FORMAT_OPTIONS, defaults);
  if (type === "time" && !filteredOptions.hour && !filteredOptions.minute && !filteredOptions.second && !filteredOptions.timeStyle && !filteredOptions.dateStyle) {
    filteredOptions = __assign(__assign({}, filteredOptions), { hour: "numeric", minute: "numeric" });
  }
  return getDateTimeFormat(locale, filteredOptions);
}
function formatDate(config, getDateTimeFormat) {
  var _a2 = [];
  for (var _i = 2; _i < arguments.length; _i++) {
    _a2[_i - 2] = arguments[_i];
  }
  var value = _a2[0], _b = _a2[1], options = _b === void 0 ? {} : _b;
  var date = typeof value === "string" ? new Date(value || 0) : value;
  try {
    return getFormatter$2(config, "date", getDateTimeFormat, options).format(date);
  } catch (e2) {
    config.onError(new IntlError(IntlErrorCode.FORMAT_ERROR, "Error formatting date.", e2));
  }
  return String(date);
}
function formatTime(config, getDateTimeFormat) {
  var _a2 = [];
  for (var _i = 2; _i < arguments.length; _i++) {
    _a2[_i - 2] = arguments[_i];
  }
  var value = _a2[0], _b = _a2[1], options = _b === void 0 ? {} : _b;
  var date = typeof value === "string" ? new Date(value || 0) : value;
  try {
    return getFormatter$2(config, "time", getDateTimeFormat, options).format(date);
  } catch (e2) {
    config.onError(new IntlError(IntlErrorCode.FORMAT_ERROR, "Error formatting time.", e2));
  }
  return String(date);
}
function formatDateTimeRange(config, getDateTimeFormat) {
  var _a2 = [];
  for (var _i = 2; _i < arguments.length; _i++) {
    _a2[_i - 2] = arguments[_i];
  }
  var from = _a2[0], to = _a2[1], _b = _a2[2], options = _b === void 0 ? {} : _b;
  var timeZone = config.timeZone, locale = config.locale, onError = config.onError;
  var filteredOptions = filterProps$1(options, DATE_TIME_FORMAT_OPTIONS, timeZone ? { timeZone } : {});
  try {
    return getDateTimeFormat(locale, filteredOptions).formatRange(from, to);
  } catch (e2) {
    onError(new IntlError(IntlErrorCode.FORMAT_ERROR, "Error formatting date time range.", e2));
  }
  return String(from);
}
function formatDateToParts(config, getDateTimeFormat) {
  var _a2 = [];
  for (var _i = 2; _i < arguments.length; _i++) {
    _a2[_i - 2] = arguments[_i];
  }
  var value = _a2[0], _b = _a2[1], options = _b === void 0 ? {} : _b;
  var date = typeof value === "string" ? new Date(value || 0) : value;
  try {
    return getFormatter$2(config, "date", getDateTimeFormat, options).formatToParts(date);
  } catch (e2) {
    config.onError(new IntlError(IntlErrorCode.FORMAT_ERROR, "Error formatting date.", e2));
  }
  return [];
}
function formatTimeToParts(config, getDateTimeFormat) {
  var _a2 = [];
  for (var _i = 2; _i < arguments.length; _i++) {
    _a2[_i - 2] = arguments[_i];
  }
  var value = _a2[0], _b = _a2[1], options = _b === void 0 ? {} : _b;
  var date = typeof value === "string" ? new Date(value || 0) : value;
  try {
    return getFormatter$2(config, "time", getDateTimeFormat, options).formatToParts(date);
  } catch (e2) {
    config.onError(new IntlError(IntlErrorCode.FORMAT_ERROR, "Error formatting time.", e2));
  }
  return [];
}
var DISPLAY_NAMES_OPTONS = [
  "localeMatcher",
  "style",
  "type",
  "fallback"
];
function formatDisplayName(_a2, getDisplayNames, value, options) {
  var locale = _a2.locale, onError = _a2.onError;
  var DisplayNames = Intl.DisplayNames;
  if (!DisplayNames) {
    onError(new FormatError('Intl.DisplayNames is not available in this environment.\nTry polyfilling it using "@formatjs/intl-displaynames"\n', ErrorCode.MISSING_INTL_API));
  }
  var filteredOptions = filterProps$1(options, DISPLAY_NAMES_OPTONS);
  try {
    return getDisplayNames(locale, filteredOptions).of(value);
  } catch (e2) {
    onError(new IntlError(IntlErrorCode.FORMAT_ERROR, "Error formatting display name.", e2));
  }
}
var LIST_FORMAT_OPTIONS = [
  "localeMatcher",
  "type",
  "style"
];
var now = Date.now();
function generateToken(i2) {
  return "".concat(now, "_").concat(i2, "_").concat(now);
}
function formatList(opts, getListFormat, values, options) {
  if (options === void 0) {
    options = {};
  }
  var results = formatListToParts(opts, getListFormat, values, options).reduce(function(all, el) {
    var val = el.value;
    if (typeof val !== "string") {
      all.push(val);
    } else if (typeof all[all.length - 1] === "string") {
      all[all.length - 1] += val;
    } else {
      all.push(val);
    }
    return all;
  }, []);
  return results.length === 1 ? results[0] : results;
}
function formatListToParts(_a2, getListFormat, values, options) {
  var locale = _a2.locale, onError = _a2.onError;
  if (options === void 0) {
    options = {};
  }
  var ListFormat = Intl.ListFormat;
  if (!ListFormat) {
    onError(new FormatError('Intl.ListFormat is not available in this environment.\nTry polyfilling it using "@formatjs/intl-listformat"\n', ErrorCode.MISSING_INTL_API));
  }
  var filteredOptions = filterProps$1(options, LIST_FORMAT_OPTIONS);
  try {
    var richValues_1 = {};
    var serializedValues = values.map(function(v2, i2) {
      if (typeof v2 === "object") {
        var id2 = generateToken(i2);
        richValues_1[id2] = v2;
        return id2;
      }
      return String(v2);
    });
    return getListFormat(locale, filteredOptions).formatToParts(serializedValues).map(function(part) {
      return part.type === "literal" ? part : __assign(__assign({}, part), { value: richValues_1[part.value] || part.value });
    });
  } catch (e2) {
    onError(new IntlError(IntlErrorCode.FORMAT_ERROR, "Error formatting list.", e2));
  }
  return values;
}
var PLURAL_FORMAT_OPTIONS = [
  "localeMatcher",
  "type"
];
function formatPlural(_a2, getPluralRules, value, options) {
  var locale = _a2.locale, onError = _a2.onError;
  if (options === void 0) {
    options = {};
  }
  if (!Intl.PluralRules) {
    onError(new FormatError('Intl.PluralRules is not available in this environment.\nTry polyfilling it using "@formatjs/intl-pluralrules"\n', ErrorCode.MISSING_INTL_API));
  }
  var filteredOptions = filterProps$1(options, PLURAL_FORMAT_OPTIONS);
  try {
    return getPluralRules(locale, filteredOptions).select(value);
  } catch (e2) {
    onError(new IntlFormatError("Error formatting plural.", locale, e2));
  }
  return "other";
}
var RELATIVE_TIME_FORMAT_OPTIONS = ["numeric", "style"];
function getFormatter$1(_a2, getRelativeTimeFormat, options) {
  var locale = _a2.locale, formats = _a2.formats, onError = _a2.onError;
  if (options === void 0) {
    options = {};
  }
  var format = options.format;
  var defaults = !!format && getNamedFormat(formats, "relative", format, onError) || {};
  var filteredOptions = filterProps$1(options, RELATIVE_TIME_FORMAT_OPTIONS, defaults);
  return getRelativeTimeFormat(locale, filteredOptions);
}
function formatRelativeTime(config, getRelativeTimeFormat, value, unit, options) {
  if (options === void 0) {
    options = {};
  }
  if (!unit) {
    unit = "second";
  }
  var RelativeTimeFormat = Intl.RelativeTimeFormat;
  if (!RelativeTimeFormat) {
    config.onError(new FormatError('Intl.RelativeTimeFormat is not available in this environment.\nTry polyfilling it using "@formatjs/intl-relativetimeformat"\n', ErrorCode.MISSING_INTL_API));
  }
  try {
    return getFormatter$1(config, getRelativeTimeFormat, options).format(value, unit);
  } catch (e2) {
    config.onError(new IntlFormatError("Error formatting relative time.", config.locale, e2));
  }
  return String(value);
}
var NUMBER_FORMAT_OPTIONS = [
  "localeMatcher",
  "style",
  "currency",
  "currencyDisplay",
  "unit",
  "unitDisplay",
  "useGrouping",
  "minimumIntegerDigits",
  "minimumFractionDigits",
  "maximumFractionDigits",
  "minimumSignificantDigits",
  "maximumSignificantDigits",
  "compactDisplay",
  "currencyDisplay",
  "currencySign",
  "notation",
  "signDisplay",
  "unit",
  "unitDisplay",
  "numberingSystem"
];
function getFormatter(_a2, getNumberFormat, options) {
  var locale = _a2.locale, formats = _a2.formats, onError = _a2.onError;
  if (options === void 0) {
    options = {};
  }
  var format = options.format;
  var defaults = format && getNamedFormat(formats, "number", format, onError) || {};
  var filteredOptions = filterProps$1(options, NUMBER_FORMAT_OPTIONS, defaults);
  return getNumberFormat(locale, filteredOptions);
}
function formatNumber(config, getNumberFormat, value, options) {
  if (options === void 0) {
    options = {};
  }
  try {
    return getFormatter(config, getNumberFormat, options).format(value);
  } catch (e2) {
    config.onError(new IntlError(IntlErrorCode.FORMAT_ERROR, "Error formatting number.", e2));
  }
  return String(value);
}
function formatNumberToParts(config, getNumberFormat, value, options) {
  if (options === void 0) {
    options = {};
  }
  try {
    return getFormatter(config, getNumberFormat, options).formatToParts(value);
  } catch (e2) {
    config.onError(new IntlError(IntlErrorCode.FORMAT_ERROR, "Error formatting number.", e2));
  }
  return [];
}
function messagesContainString(messages2) {
  var firstMessage = messages2 ? messages2[Object.keys(messages2)[0]] : void 0;
  return typeof firstMessage === "string";
}
function verifyConfigMessages(config) {
  if (config.defaultRichTextElements && messagesContainString(config.messages || {})) {
    console.warn('[@formatjs/intl] "defaultRichTextElements" was specified but "message" was not pre-compiled. \nPlease consider using "@formatjs/cli" to pre-compile your messages for performance.\nFor more details see https://formatjs.io/docs/getting-started/message-distribution');
  }
}
function createIntl$1(config, cache) {
  var formatters = createFormatters(cache);
  var resolvedConfig = __assign(__assign({}, DEFAULT_INTL_CONFIG$1), config);
  var locale = resolvedConfig.locale, defaultLocale = resolvedConfig.defaultLocale, onError = resolvedConfig.onError;
  if (!locale) {
    if (onError) {
      onError(new InvalidConfigError('"locale" was not configured, using "'.concat(defaultLocale, '" as fallback. See https://formatjs.io/docs/react-intl/api#intlshape for more details')));
    }
    resolvedConfig.locale = resolvedConfig.defaultLocale || "en";
  } else if (!Intl.NumberFormat.supportedLocalesOf(locale).length && onError) {
    onError(new MissingDataError('Missing locale data for locale: "'.concat(locale, '" in Intl.NumberFormat. Using default locale: "').concat(defaultLocale, '" as fallback. See https://formatjs.io/docs/react-intl#runtime-requirements for more details')));
  } else if (!Intl.DateTimeFormat.supportedLocalesOf(locale).length && onError) {
    onError(new MissingDataError('Missing locale data for locale: "'.concat(locale, '" in Intl.DateTimeFormat. Using default locale: "').concat(defaultLocale, '" as fallback. See https://formatjs.io/docs/react-intl#runtime-requirements for more details')));
  }
  verifyConfigMessages(resolvedConfig);
  return __assign(__assign({}, resolvedConfig), { formatters, formatNumber: formatNumber.bind(null, resolvedConfig, formatters.getNumberFormat), formatNumberToParts: formatNumberToParts.bind(null, resolvedConfig, formatters.getNumberFormat), formatRelativeTime: formatRelativeTime.bind(null, resolvedConfig, formatters.getRelativeTimeFormat), formatDate: formatDate.bind(null, resolvedConfig, formatters.getDateTimeFormat), formatDateToParts: formatDateToParts.bind(null, resolvedConfig, formatters.getDateTimeFormat), formatTime: formatTime.bind(null, resolvedConfig, formatters.getDateTimeFormat), formatDateTimeRange: formatDateTimeRange.bind(null, resolvedConfig, formatters.getDateTimeFormat), formatTimeToParts: formatTimeToParts.bind(null, resolvedConfig, formatters.getDateTimeFormat), formatPlural: formatPlural.bind(null, resolvedConfig, formatters.getPluralRules), formatMessage: formatMessage$1.bind(null, resolvedConfig, formatters), formatList: formatList.bind(null, resolvedConfig, formatters.getListFormat), formatListToParts: formatListToParts.bind(null, resolvedConfig, formatters.getListFormat), formatDisplayName: formatDisplayName.bind(null, resolvedConfig, formatters.getDisplayNames) });
}
function invariantIntlContext(intl) {
  invariant$1(intl, "[React Intl] Could not find required `intl` object. <IntlProvider> needs to exist in the component ancestry.");
}
var DEFAULT_INTL_CONFIG = __assign(__assign({}, DEFAULT_INTL_CONFIG$1), { textComponent: React__default.Fragment });
function assignUniqueKeysToParts(formatXMLElementFn) {
  return function(parts) {
    return formatXMLElementFn(React.Children.toArray(parts));
  };
}
function shallowEqual(objA, objB) {
  if (objA === objB) {
    return true;
  }
  if (!objA || !objB) {
    return false;
  }
  var aKeys = Object.keys(objA);
  var bKeys = Object.keys(objB);
  var len = aKeys.length;
  if (bKeys.length !== len) {
    return false;
  }
  for (var i2 = 0; i2 < len; i2++) {
    var key = aKeys[i2];
    if (objA[key] !== objB[key] || !Object.prototype.hasOwnProperty.call(objB, key)) {
      return false;
    }
  }
  return true;
}
var IntlContext = React.createContext(null);
IntlContext.Consumer;
var IntlProvider$2 = IntlContext.Provider;
var Provider = IntlProvider$2;
var Context = IntlContext;
function useIntl() {
  var intl = React.useContext(Context);
  invariantIntlContext(intl);
  return intl;
}
function processIntlConfig(config) {
  return {
    locale: config.locale,
    timeZone: config.timeZone,
    fallbackOnEmptyString: config.fallbackOnEmptyString,
    formats: config.formats,
    textComponent: config.textComponent,
    messages: config.messages,
    defaultLocale: config.defaultLocale,
    defaultFormats: config.defaultFormats,
    onError: config.onError,
    wrapRichTextChunksInFragment: config.wrapRichTextChunksInFragment,
    defaultRichTextElements: config.defaultRichTextElements
  };
}
function assignUniqueKeysToFormatXMLElementFnArgument(values) {
  if (!values) {
    return values;
  }
  return Object.keys(values).reduce(function(acc, k2) {
    var v2 = values[k2];
    acc[k2] = isFormatXMLElementFn(v2) ? assignUniqueKeysToParts(v2) : v2;
    return acc;
  }, {});
}
var formatMessage = function(config, formatters, descriptor, rawValues) {
  var rest = [];
  for (var _i = 4; _i < arguments.length; _i++) {
    rest[_i - 4] = arguments[_i];
  }
  var values = assignUniqueKeysToFormatXMLElementFnArgument(rawValues);
  var chunks = formatMessage$1.apply(void 0, __spreadArray([
    config,
    formatters,
    descriptor,
    values
  ], rest, false));
  if (Array.isArray(chunks)) {
    return React.Children.toArray(chunks);
  }
  return chunks;
};
var createIntl = function(_a2, cache) {
  var rawDefaultRichTextElements = _a2.defaultRichTextElements, config = __rest(_a2, ["defaultRichTextElements"]);
  var defaultRichTextElements = assignUniqueKeysToFormatXMLElementFnArgument(rawDefaultRichTextElements);
  var coreIntl = createIntl$1(__assign(__assign(__assign({}, DEFAULT_INTL_CONFIG), config), { defaultRichTextElements }), cache);
  return __assign(__assign({}, coreIntl), { formatMessage: formatMessage.bind(null, {
    locale: coreIntl.locale,
    timeZone: coreIntl.timeZone,
    fallbackOnEmptyString: coreIntl.fallbackOnEmptyString,
    formats: coreIntl.formats,
    defaultLocale: coreIntl.defaultLocale,
    defaultFormats: coreIntl.defaultFormats,
    messages: coreIntl.messages,
    onError: coreIntl.onError,
    defaultRichTextElements
  }, coreIntl.formatters) });
};
var IntlProvider = function(_super) {
  __extends(IntlProvider2, _super);
  function IntlProvider2() {
    var _this = _super !== null && _super.apply(this, arguments) || this;
    _this.cache = createIntlCache();
    _this.state = {
      cache: _this.cache,
      intl: createIntl(processIntlConfig(_this.props), _this.cache),
      prevConfig: processIntlConfig(_this.props)
    };
    return _this;
  }
  IntlProvider2.getDerivedStateFromProps = function(props2, _a2) {
    var prevConfig = _a2.prevConfig, cache = _a2.cache;
    var config = processIntlConfig(props2);
    if (!shallowEqual(prevConfig, config)) {
      return {
        intl: createIntl(config, cache),
        prevConfig: config
      };
    }
    return null;
  };
  IntlProvider2.prototype.render = function() {
    invariantIntlContext(this.state.intl);
    return React__default.createElement(Provider, { value: this.state.intl }, this.props.children);
  };
  IntlProvider2.displayName = "IntlProvider";
  IntlProvider2.defaultProps = DEFAULT_INTL_CONFIG;
  return IntlProvider2;
}(React.PureComponent);
var IntlProvider$1 = IntlProvider;
function areEqual(prevProps, nextProps) {
  var values = prevProps.values, otherProps = __rest(prevProps, ["values"]);
  var nextValues = nextProps.values, nextOtherProps = __rest(nextProps, ["values"]);
  return shallowEqual(nextValues, values) && shallowEqual(otherProps, nextOtherProps);
}
function FormattedMessage(props2) {
  var intl = useIntl();
  var formatMessage2 = intl.formatMessage, _a2 = intl.textComponent, Text = _a2 === void 0 ? React__default.Fragment : _a2;
  var id2 = props2.id, description = props2.description, defaultMessage = props2.defaultMessage, values = props2.values, children = props2.children, _b = props2.tagName, Component = _b === void 0 ? Text : _b, ignoreTag = props2.ignoreTag;
  var descriptor = { id: id2, description, defaultMessage };
  var nodes = formatMessage2(descriptor, values, {
    ignoreTag
  });
  if (typeof children === "function") {
    return children(Array.isArray(nodes) ? nodes : [nodes]);
  }
  if (Component) {
    return React__default.createElement(Component, null, React.Children.toArray(nodes));
  }
  return React__default.createElement(React__default.Fragment, null, nodes);
}
FormattedMessage.displayName = "FormattedMessage";
var MemoizedFormattedMessage = React.memo(FormattedMessage, areEqual);
MemoizedFormattedMessage.displayName = "MemoizedFormattedMessage";
var FormattedMessage$1 = MemoizedFormattedMessage;
function defineMessages(msgs) {
  return msgs;
}
function defineMessage(msg) {
  return msg;
}
var EditorMode = /* @__PURE__ */ ((EditorMode2) => {
  EditorMode2["INLINE"] = "inline";
  EditorMode2["OVERLAY"] = "overlay";
  return EditorMode2;
})(EditorMode || {});
var NavPosition = /* @__PURE__ */ ((NavPosition2) => {
  NavPosition2["TOP"] = "top";
  NavPosition2["BOTTOM"] = "bottom";
  NavPosition2["HIDDEN"] = "";
  return NavPosition2;
})(NavPosition || {});
const defaultShapes = [{
  name: "circle",
  type: "Circle"
}, {
  name: "square",
  type: "Rect",
  options: {
    lockUniScaling: false
  }
}, {
  name: "triangle",
  type: "Triangle"
}, {
  name: "ellipse",
  type: "Ellipse",
  options: {
    lockUniScaling: false
  }
}, {
  name: "Arrow #1",
  type: "Path",
  options: {
    path: "M 294.9 16.4 l 15.7 42.2 c -171.4 70.3 -294 242.3 -289.1 437.4 l 14.7 -1 c 9.1 -0.6 18.1 -1.2 27.1 -1.9 l 14.7 -1 c -4.3 -170.1 102.5 -320 252 -381.3 l 15.7 42.2 c 34.7 -40.5 83.1 -76.6 144.8 -99.8 c -58.1 -26.2 -124.9 -39.6 -195.6 -36.8 z"
  }
}, {
  name: "Arrow #2",
  type: "Path",
  options: {
    path: "M 16 248.4 v 14.9 h 447.5 l -93.2 82.5 l 11.9 10.5 l 113.8 -100.2 l -113.6 -100.4 l -11.8 10.5 l 92.9 82.2 z"
  }
}, {
  name: "Arrow #3",
  type: "Path",
  options: {
    path: "M 496 256 l -118.6 -66 v 40.8 h -361.4 v 50.4 h 361.4 v 40.8 l 118.6 -66 z"
  }
}, {
  name: "Line",
  type: "Path",
  options: {
    path: "M 16 256 h 480",
    strokeWidth: 10,
    stroke: "#000",
    padding: 10
  }
}, {
  name: "Star",
  type: "Path",
  options: {
    path: "M 256 406.3 l 148.3 78 l -28.3 -165.2 l 120 -117 l -165.8 -24.1 l -74.2 -150.3 l -74.2 150.3 l -165.8 24.1 l 120 117 l -28.3 165.2 z"
  }
}, {
  name: "Polygon",
  type: "Path",
  options: {
    path: "M 256 19.6 l 156.6 57.1 l 83.4 144.3 l -28.9 164.2 l -127.7 107.2 h -166.8 l -127.7 -107.2 l -28.9 -164.2 l 83.4 -144.3 z"
  }
}, {
  name: "Badge",
  type: "Path",
  options: {
    path: "M 257.3 16.2 s -148 58.2 -204.4 81.4 c 0 75.7 -16.8 303.5 204.4 398.2 c 218.7 -94.6 201.9 -322.4 201.9 -398.2 c -62.1 -23.6 -201.9 -81.4 -201.9 -81.4 z"
  }
}];
const emoticonsList = ["afro-1", "afro", "agent", "alien-1", "alien", "angel", "angry-1", "angry-2", "angry-3", "angry-4", "angry-5", "angry", "arguing", "arrogant", "asian-1", "asian", "avatar", "baby-1", "baby-2", "baby", "bully", "burglar", "businessman", "cheeky-1", "cheeky", "clown", "confused-1", "confused-2", "confused-3", "confused", "creepy", "crying-1", "crying-2", "crying-3", "crying", "dazed-1", "dazed-2", "dazed-3", "dazed", "dead-1", "dead-2", "dead-3", "dead-4", "dead-5", "dead-6", "dead", "desperate-1", "desperate", "detective", "dissapointment", "doctor", "drunk", "dumb", "emo-1", "emo-2", "emo", "emoticon", "evil", "faint-1", "faint", "flirt-1", "flirt-2", "flirt", "flirty", "gangster", "geek-1", "geek", "gentleman-1", "gentleman-2", "gentleman-3", "gentleman-4", "gentleman", "ginger", "girl-1", "girl", "goofy-1", "goofy-2", "goofy-3", "goofy-4", "goofy", "grubby-1", "grubby", "happy-1", "happy-10", "happy-11", "happy-12", "happy-13", "happy-14", "happy-15", "happy-16", "happy-2", "happy-3", "happy-4", "happy-5", "happy-6", "happy-7", "happy-8", "happy-9", "happy", "harry-potter", "heisenberg", "hipster-1", "hipster-2", "hipster", "in-love-1", "in-love-2", "in-love-3", "in-love-4", "in-love-5", "in-love-6", "in-love", "japan", "jew", "joyful-1", "joyful-2", "joyful", "kiss-1", "kiss-2", "kiss-3", "kiss-4", "kiss", "laughing-1", "laughing-2", "laughing-3", "laughing", "listening", "love", "manly", "miserly-1", "miserly", "nerd-1", "nerd-2", "nerd-3", "nerd-4", "nerd", "ninja", "pirate-1", "pirate-2", "pirate", "punk-1", "punk-2", "punk", "rapper", "relieved", "rich-1", "rich-2", "rich", "rockstar", "sad-1", "sad-2", "sad-3", "sad-4", "sad-5", "sad-6", "sad", "scared-1", "scared-2", "scared-3", "scared", "sceptic-1", "sceptic-2", "sceptic-3", "sceptic-4", "sceptic-5", "sceptic-6", "sceptic-7", "sceptic", "secret", "shocked-1", "shocked-2", "shocked-3", "shocked", "sick-1", "sick-2", "sick-3", "sick-4", "sick", "silent", "skeleton", "smile", "smiling-1", "smiling", "smoked", "smug-1", "smug-2", "smug-3", "smug-4", "smug-5", "smug-6", "smug", "sporty", "stunned", "superhero-1", "superhero-2", "superhero-3", "superhero-4", "superhero", "surprised-1", "surprised", "thinking", "tired-1", "tired-2", "tired-3", "tired", "tough-1", "tough", "trendy", "vampire-1", "vampire", "wink-1", "wink-2", "wink", "winking-1", "winking", "yawning-1", "yawning-2", "yawning-3", "yawning", "yelling", "zombie"];
const defaultStickers = [{
  name: "emoticons",
  list: emoticonsList,
  type: "svg",
  thumbnailUrl: "images/stickers/categories/emoticon.svg"
}, {
  name: "doodles",
  items: 100,
  type: "svg",
  thumbnailUrl: "images/stickers/categories/doodles.svg"
}, {
  name: "landmarks",
  items: 100,
  type: "svg",
  thumbnailUrl: "images/stickers/categories/landmark.svg",
  invertPreview: true
}, {
  name: "bubbles",
  items: 104,
  type: "png",
  thumbnailUrl: "images/stickers/categories/speech-bubble.svg"
}, {
  name: "transportation",
  items: 22,
  type: "svg",
  thumbnailUrl: "images/stickers/categories/transportation.svg",
  invertPreview: true
}, {
  name: "beach",
  items: 22,
  type: "svg",
  thumbnailUrl: "images/stickers/categories/beach.svg",
  invertPreview: true
}];
const StickerCategoryMessages = defineMessages({
  emoticons: {
    id: "ndJMAh",
    defaultMessage: [{
      "type": 0,
      "value": "Emoticons"
    }]
  },
  doodles: {
    id: "XCd0W/",
    defaultMessage: [{
      "type": 0,
      "value": "Doodles"
    }]
  },
  landmarks: {
    id: "hqIEba",
    defaultMessage: [{
      "type": 0,
      "value": "Landmarks"
    }]
  },
  bubbles: {
    id: "ovg8vQ",
    defaultMessage: [{
      "type": 0,
      "value": "Bubbles"
    }]
  },
  transportation: {
    id: "nDt4cJ",
    defaultMessage: [{
      "type": 0,
      "value": "Transportation"
    }]
  },
  beach: {
    id: "PfXXAT",
    defaultMessage: [{
      "type": 0,
      "value": "Beach"
    }]
  }
});
const defaultObjectProps = {
  fill: "#1565C0",
  opacity: 1,
  backgroundColor: null,
  strokeWidth: 0.05,
  stroke: "#000"
};
const BrushTypes = ["PencilBrush", "SprayBrush", "CircleBrush", "DiamondBrush", "VLineBrush", "HLineBrush", "SquareBrush"];
const BrushSizes = [1, 8, 15, 20, 25];
var EditorTheme = /* @__PURE__ */ ((EditorTheme2) => {
  EditorTheme2["DARK"] = "dark";
  EditorTheme2["LIGHT"] = "light";
  return EditorTheme2;
})(EditorTheme || {});
const DEFAULT_THEMES = [{
  name: EditorTheme.LIGHT,
  colors: {
    "--be-foreground-base": "0 0 0",
    "--be-primary-light": "191 219 254",
    "--be-primary": "59 130 246",
    "--be-primary-dark": "37 99 235",
    "--be-on-primary": "255 255 255",
    "--be-error": "179 38 30",
    "--be-on-error": "255 255 255",
    "--be-background": "255 255 255",
    "--be-background-alt": "250 250 250",
    "--be-paper": "255 255 255",
    "--be-disabled-bg-opacity": "12%",
    "--be-disabled-fg-opacity": "26%",
    "--be-hover-opacity": "4%",
    "--be-focus-opacity": "12%",
    "--be-selected-opacity": "8%",
    "--be-text-main-opacity": "87%",
    "--be-text-muted-opacity": "60%",
    "--be-divider-opacity": "12%"
  }
}, {
  name: EditorTheme.DARK,
  isDark: true,
  colors: {
    "--be-foreground-base": "255 255 255",
    "--be-primary-light": "239 246 255",
    "--be-primary": "191 219 254",
    "--be-primary-dark": "147 197 253",
    "--be-on-primary": "56 30 114",
    "--be-error": "242 184 181",
    "--be-on-error": "96 20 16",
    "--be-background": "20 21 23",
    "--be-background-alt": "26 27 30",
    "--be-paper": "44 46 51",
    "--be-disabled-bg-opacity": "12%",
    "--be-disabled-fg-opacity": "30%",
    "--be-hover-opacity": "8%",
    "--be-focus-opacity": "12%",
    "--be-selected-opacity": "16%",
    "--be-text-main-opacity": "100%",
    "--be-text-muted-opacity": "70%",
    "--be-divider-opacity": "12%"
  }
}];
var ToolName = /* @__PURE__ */ ((ToolName2) => {
  ToolName2["FILTER"] = "filter";
  ToolName2["RESIZE"] = "resize";
  ToolName2["CROP"] = "crop";
  ToolName2["DRAW"] = "draw";
  ToolName2["TEXT"] = "text";
  ToolName2["SHAPES"] = "shapes";
  ToolName2["STICKERS"] = "stickers";
  ToolName2["FRAME"] = "frame";
  ToolName2["CORNERS"] = "corners";
  ToolName2["MERGE"] = "merge";
  return ToolName2;
})(ToolName || {});
var jsxRuntime = { exports: {} };
var reactJsxRuntime_production_min = {};
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
  if (val === null || val === void 0) {
    throw new TypeError("Object.assign cannot be called with null or undefined");
  }
  return Object(val);
}
function shouldUseNative() {
  try {
    if (!Object.assign) {
      return false;
    }
    var test1 = new String("abc");
    test1[5] = "de";
    if (Object.getOwnPropertyNames(test1)[0] === "5") {
      return false;
    }
    var test2 = {};
    for (var i2 = 0; i2 < 10; i2++) {
      test2["_" + String.fromCharCode(i2)] = i2;
    }
    var order2 = Object.getOwnPropertyNames(test2).map(function(n2) {
      return test2[n2];
    });
    if (order2.join("") !== "0123456789") {
      return false;
    }
    var test3 = {};
    "abcdefghijklmnopqrst".split("").forEach(function(letter) {
      test3[letter] = letter;
    });
    if (Object.keys(Object.assign({}, test3)).join("") !== "abcdefghijklmnopqrst") {
      return false;
    }
    return true;
  } catch (err) {
    return false;
  }
}
shouldUseNative() ? Object.assign : function(target, source) {
  var from;
  var to = toObject(target);
  var symbols;
  for (var s2 = 1; s2 < arguments.length; s2++) {
    from = Object(arguments[s2]);
    for (var key in from) {
      if (hasOwnProperty$1.call(from, key)) {
        to[key] = from[key];
      }
    }
    if (getOwnPropertySymbols) {
      symbols = getOwnPropertySymbols(from);
      for (var i2 = 0; i2 < symbols.length; i2++) {
        if (propIsEnumerable.call(from, symbols[i2])) {
          to[symbols[i2]] = from[symbols[i2]];
        }
      }
    }
  }
  return to;
};
/** @license React v17.0.2
 * react-jsx-runtime.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
var f$4 = React__default, g$4 = 60103;
reactJsxRuntime_production_min.Fragment = 60107;
if (typeof Symbol === "function" && Symbol.for) {
  var h$5 = Symbol.for;
  g$4 = h$5("react.element");
  reactJsxRuntime_production_min.Fragment = h$5("react.fragment");
}
var m$3 = f$4.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, n$4 = Object.prototype.hasOwnProperty, p$4 = { key: true, ref: true, __self: true, __source: true };
function q$2(c2, a2, k2) {
  var b2, d2 = {}, e2 = null, l2 = null;
  k2 !== void 0 && (e2 = "" + k2);
  a2.key !== void 0 && (e2 = "" + a2.key);
  a2.ref !== void 0 && (l2 = a2.ref);
  for (b2 in a2)
    n$4.call(a2, b2) && !p$4.hasOwnProperty(b2) && (d2[b2] = a2[b2]);
  if (c2 && c2.defaultProps)
    for (b2 in a2 = c2.defaultProps, a2)
      d2[b2] === void 0 && (d2[b2] = a2[b2]);
  return { $$typeof: g$4, type: c2, key: e2, ref: l2, props: d2, _owner: m$3.current };
}
reactJsxRuntime_production_min.jsx = q$2;
reactJsxRuntime_production_min.jsxs = q$2;
{
  jsxRuntime.exports = reactJsxRuntime_production_min;
}
const jsx = jsxRuntime.exports.jsx;
const jsxs = jsxRuntime.exports.jsxs;
const Fragment = jsxRuntime.exports.Fragment;
const SvgIcon = forwardRef((props2, ref) => {
  const _a2 = props2, {
    attr,
    size,
    title,
    className,
    color: color2,
    style: style2,
    children,
    viewBox
  } = _a2, svgProps = __objRest(_a2, [
    "attr",
    "size",
    "title",
    "className",
    "color",
    "style",
    "children",
    "viewBox"
  ]);
  const computedSize = size || "1em";
  let mergedClassName = "svg-icon";
  if (className) {
    mergedClassName += ` ${className}`;
  }
  return /* @__PURE__ */ jsxs("svg", __spreadProps(__spreadValues(__spreadValues({
    "aria-hidden": !title,
    focusable: false,
    xmlns: "http://www.w3.org/2000/svg",
    viewBox: viewBox || "0 0 24 24"
  }, attr), svgProps), {
    className: mergedClassName,
    style: __spreadValues({
      color: color2
    }, style2),
    ref,
    height: computedSize,
    width: computedSize,
    children: [title && /* @__PURE__ */ jsx("title", {
      children: title
    }), children]
  }));
});
function createSvgIcon(path, displayName = "") {
  const Component = (props2, ref) => /* @__PURE__ */ jsx(SvgIcon, __spreadProps(__spreadValues({
    "data-testid": `${displayName}Icon`,
    ref
  }, props2), {
    children: path
  }));
  return React__default.memo(React__default.forwardRef(Component));
}
function createSvgIconFromTree(data, displayName = "") {
  const path = Tree2Element(data);
  return createSvgIcon(path, displayName);
}
function Tree2Element(tree) {
  return tree && tree.map((node, i2) => {
    return React__default.createElement(node.tag, __spreadValues({
      key: i2
    }, node.attr), Tree2Element(node.child));
  });
}
const TuneIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M3 17v2h6v-2H3zM3 5v2h10V5H3zm10 16v-2h8v-2h-8v-2h-2v6h2zM7 9v2H3v2h4v2h2V9H7zm14 4v-2H11v2h10zm-6-4h2V7h4V5h-4V3h-2v6z"
}), "TuneOutlined");
const PhotoSizeSelectLargeIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M21 15h2v2h-2v-2zm0-4h2v2h-2v-2zm2 8h-2v2c1 0 2-1 2-2zM13 3h2v2h-2V3zm8 4h2v2h-2V7zm0-4v2h2c0-1-1-2-2-2zM1 7h2v2H1V7zm16-4h2v2h-2V3zm0 16h2v2h-2v-2zM3 3C2 3 1 4 1 5h2V3zm6 0h2v2H9V3zM5 3h2v2H5V3zm-4 8v8c0 1.1.9 2 2 2h12V11H1zm2 8 2.5-3.21 1.79 2.15 2.5-3.22L13 19H3z"
}), "PhotoSizeSelectLargeOutlined");
const CropIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M17 15h2V7c0-1.1-.9-2-2-2H9v2h8v8zM7 17V1H5v4H1v2h4v10c0 1.1.9 2 2 2h10v4h2v-4h4v-2H7z"
}), "CropOutlined");
const TextFieldsIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M2.5 4v3h5v12h3V7h5V4h-13zm19 5h-9v3h3v7h3v-7h3V9z"
}), "TextFieldsOutlined");
const ExtensionIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M10.5 4.5c.28 0 .5.22.5.5v2h6v6h2c.28 0 .5.22.5.5s-.22.5-.5.5h-2v6h-2.12c-.68-1.75-2.39-3-4.38-3s-3.7 1.25-4.38 3H4v-2.12c1.75-.68 3-2.39 3-4.38 0-1.99-1.24-3.7-2.99-4.38L4 7h6V5c0-.28.22-.5.5-.5m0-2C9.12 2.5 8 3.62 8 5H4c-1.1 0-1.99.9-1.99 2v3.8h.29c1.49 0 2.7 1.21 2.7 2.7s-1.21 2.7-2.7 2.7H2V20c0 1.1.9 2 2 2h3.8v-.3c0-1.49 1.21-2.7 2.7-2.7s2.7 1.21 2.7 2.7v.3H17c1.1 0 2-.9 2-2v-4c1.38 0 2.5-1.12 2.5-2.5S20.38 11 19 11V7c0-1.1-.9-2-2-2h-4c0-1.38-1.12-2.5-2.5-2.5z"
}), "ExtensionOutlined");
const FaceIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M10.25 13c0 .69-.56 1.25-1.25 1.25S7.75 13.69 7.75 13s.56-1.25 1.25-1.25 1.25.56 1.25 1.25zM15 11.75c-.69 0-1.25.56-1.25 1.25s.56 1.25 1.25 1.25 1.25-.56 1.25-1.25-.56-1.25-1.25-1.25zm7 .25c0 5.52-4.48 10-10 10S2 17.52 2 12 6.48 2 12 2s10 4.48 10 10zM10.66 4.12C12.06 6.44 14.6 8 17.5 8c.46 0 .91-.05 1.34-.12C17.44 5.56 14.9 4 12 4c-.46 0-.91.05-1.34.12zM4.42 9.47c1.71-.97 3.03-2.55 3.66-4.44C6.37 6 5.05 7.58 4.42 9.47zM20 12c0-.78-.12-1.53-.33-2.24-.7.15-1.42.24-2.17.24-3.13 0-5.92-1.44-7.76-3.69C8.69 8.87 6.6 10.88 4 11.86c.01.04 0 .09 0 .14 0 4.41 3.59 8 8 8s8-3.59 8-8z"
}), "FaceOutlined");
const FilterFramesIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M20 4h-4l-4-4-4 4H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 16H4V6h4.52l3.52-3.5L15.52 6H20v14zM6 18h12V8H6v10zm2-8h8v6H8v-6z"
}), "FilterFramesOutlined");
const MergeIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M6.41 21 5 19.59l4.83-4.83c.75-.75 1.17-1.77 1.17-2.83v-5.1L9.41 8.41 8 7l4-4 4 4-1.41 1.41L13 6.83v5.1c0 1.06.42 2.08 1.17 2.83L19 19.59 17.59 21 12 15.41 6.41 21z"
}), "MergeOutlined");
const RoundedCornerIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M19 19h2v2h-2v-2zm0-2h2v-2h-2v2zM3 13h2v-2H3v2zm0 4h2v-2H3v2zm0-8h2V7H3v2zm0-4h2V3H3v2zm4 0h2V3H7v2zm8 16h2v-2h-2v2zm-4 0h2v-2h-2v2zm4 0h2v-2h-2v2zm-8 0h2v-2H7v2zm-4 0h2v-2H3v2zM21 8c0-2.76-2.24-5-5-5h-5v2h5c1.65 0 3 1.35 3 3v5h2V8z"
}), "RoundedCornerOutlined");
const PhotoLibraryIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M20 4v12H8V4h12m0-2H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-8.5 9.67 1.69 2.26 2.48-3.1L19 15H9zM2 6v14c0 1.1.9 2 2 2h14v-2H4V6H2z"
}), "PhotoLibraryOutlined");
const HistoryIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M13 3c-4.97 0-9 4.03-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42C8.27 19.99 10.51 21 13 21c4.97 0 9-4.03 9-9s-4.03-9-9-9zm-1 5v5l4.25 2.52.77-1.28-3.52-2.09V8z"
}), "HistoryOutlined");
const StyleIcon = createSvgIcon([/* @__PURE__ */ jsx("path", {
  d: "m2.53 19.65 1.34.56v-9.03l-2.43 5.86c-.41 1.02.08 2.19 1.09 2.61zm19.5-3.7L17.07 3.98c-.31-.75-1.04-1.21-1.81-1.23-.26 0-.53.04-.79.15L7.1 5.95c-.75.31-1.21 1.03-1.23 1.8-.01.27.04.54.15.8l4.96 11.97c.31.76 1.05 1.22 1.83 1.23.26 0 .52-.05.77-.15l7.36-3.05c1.02-.42 1.51-1.59 1.09-2.6zm-9.2 3.8L7.87 7.79l7.35-3.04h.01l4.95 11.95-7.35 3.05z"
}, "0"), /* @__PURE__ */ jsx("circle", {
  cx: "11",
  cy: "9",
  r: "1"
}, "1"), /* @__PURE__ */ jsx("path", {
  d: "M5.88 19.75c0 1.1.9 2 2 2h1.45l-3.45-8.34v6.34z"
}, "2")], "StyleOutlined");
const DeleteIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M16 9v10H8V9h8m-1.5-6h-5l-1 1H5v2h14V4h-3.5l-1-1zM18 7H6v12c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7z"
}), "DeleteOutlined");
const DrawIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M18.85,10.39l1.06-1.06c0.78-0.78,0.78-2.05,0-2.83L18.5,5.09c-0.78-0.78-2.05-0.78-2.83,0l-1.06,1.06L18.85,10.39z M14.61,11.81L7.41,19H6v-1.41l7.19-7.19L14.61,11.81z M13.19,7.56L4,16.76V21h4.24l9.19-9.19L13.19,7.56L13.19,7.56z M19,17.5 c0,2.19-2.54,3.5-5,3.5c-0.55,0-1-0.45-1-1s0.45-1,1-1c1.54,0,3-0.73,3-1.5c0-0.47-0.48-0.87-1.23-1.2l1.48-1.48 C18.32,15.45,19,16.29,19,17.5z M4.58,13.35C3.61,12.79,3,12.06,3,11c0-1.8,1.89-2.63,3.56-3.36C7.59,7.18,9,6.56,9,6 c0-0.41-0.78-1-2-1C5.74,5,5.2,5.61,5.17,5.64C4.82,6.05,4.19,6.1,3.77,5.76C3.36,5.42,3.28,4.81,3.62,4.38C3.73,4.24,4.76,3,7,3 c2.24,0,4,1.32,4,3c0,1.87-1.93,2.72-3.64,3.47C6.42,9.88,5,10.5,5,11c0,0.31,0.43,0.6,1.07,0.86L4.58,13.35z"
}), "Draw");
const HomeIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "m12 5.69 5 4.5V18h-2v-6H9v6H7v-7.81l5-4.5M12 3 2 12h3v8h6v-6h2v6h6v-8h3L12 3z"
}), "HomeOutlined");
const HISTORY_DISPLAY_NAMES = {
  [ToolName.FILTER]: {
    name: defineMessage({
      id: "QYTzdT",
      defaultMessage: [{
        "type": 0,
        "value": "Applied Filters"
      }]
    }),
    icon: TuneIcon
  },
  [ToolName.RESIZE]: {
    name: defineMessage({
      id: "OEDpaM",
      defaultMessage: [{
        "type": 0,
        "value": "Resized Image"
      }]
    }),
    icon: PhotoSizeSelectLargeIcon
  },
  [ToolName.CROP]: {
    name: defineMessage({
      id: "Lg6O5a",
      defaultMessage: [{
        "type": 0,
        "value": "Cropped Image"
      }]
    }),
    icon: CropIcon
  },
  [ToolName.DRAW]: {
    name: defineMessage({
      id: "Jc05Ei",
      defaultMessage: [{
        "type": 0,
        "value": "Added Drawing"
      }]
    }),
    icon: DrawIcon
  },
  [ToolName.TEXT]: {
    name: defineMessage({
      id: "TBhTYM",
      defaultMessage: [{
        "type": 0,
        "value": "Added Text"
      }]
    }),
    icon: TextFieldsIcon
  },
  [ToolName.SHAPES]: {
    name: defineMessage({
      id: "JSL/ji",
      defaultMessage: [{
        "type": 0,
        "value": "Added Shape"
      }]
    }),
    icon: ExtensionIcon
  },
  [ToolName.STICKERS]: {
    name: defineMessage({
      id: "xDTFjk",
      defaultMessage: [{
        "type": 0,
        "value": "Added Sticker"
      }]
    }),
    icon: FaceIcon
  },
  [ToolName.FRAME]: {
    name: defineMessage({
      id: "hgv63I",
      defaultMessage: [{
        "type": 0,
        "value": "Added Frame"
      }]
    }),
    icon: FilterFramesIcon
  },
  [ToolName.MERGE]: {
    name: defineMessage({
      id: "cXik3L",
      defaultMessage: [{
        "type": 0,
        "value": "Merged Objects"
      }]
    }),
    icon: MergeIcon
  },
  [ToolName.CORNERS]: {
    name: defineMessage({
      id: "zjEigN",
      defaultMessage: [{
        "type": 0,
        "value": "Rounded Corner"
      }]
    }),
    icon: RoundedCornerIcon
  },
  bgImage: {
    name: defineMessage({
      id: "bSC4J/",
      defaultMessage: [{
        "type": 0,
        "value": "Replaced Background Image"
      }]
    }),
    icon: PhotoLibraryIcon
  },
  overlayImage: {
    name: defineMessage({
      id: "2PcrJ7",
      defaultMessage: [{
        "type": 0,
        "value": "Added Image"
      }]
    }),
    icon: PhotoLibraryIcon
  },
  initial: {
    name: defineMessage({
      id: "fCGryv",
      defaultMessage: [{
        "type": 0,
        "value": "Initial"
      }]
    }),
    icon: HomeIcon
  },
  loadedState: {
    name: defineMessage({
      id: "UA9zHK",
      defaultMessage: [{
        "type": 0,
        "value": "Loaded State"
      }]
    }),
    icon: HistoryIcon
  },
  objectStyle: {
    name: defineMessage({
      id: "33NkCL",
      defaultMessage: [{
        "type": 0,
        "value": "Changed Style"
      }]
    }),
    icon: StyleIcon
  },
  deletedObject: {
    name: defineMessage({
      id: "7kDDgB",
      defaultMessage: [{
        "type": 0,
        "value": "Deleted object"
      }]
    }),
    icon: DeleteIcon
  }
};
const DEFAULT_NAV_ITEMS = Object.values(ToolName).map((toolName) => {
  return {
    name: toolName,
    icon: HISTORY_DISPLAY_NAMES[toolName].icon,
    action: toolName === ToolName.MERGE ? (editor) => {
      editor.tools.merge.apply();
    } : toolName
  };
});
const navItemMessages = defineMessages({
  filter: {
    id: "baCdKH",
    defaultMessage: [{
      "type": 0,
      "value": "Filter"
    }]
  },
  resize: {
    id: "F5usg6",
    defaultMessage: [{
      "type": 0,
      "value": "Resize"
    }]
  },
  crop: {
    id: "khFxHA",
    defaultMessage: [{
      "type": 0,
      "value": "Crop"
    }]
  },
  draw: {
    id: "aBdNBx",
    defaultMessage: [{
      "type": 0,
      "value": "Draw"
    }]
  },
  text: {
    id: "kn9SmW",
    defaultMessage: [{
      "type": 0,
      "value": "Text"
    }]
  },
  shapes: {
    id: "RpVV/g",
    defaultMessage: [{
      "type": 0,
      "value": "Shapes"
    }]
  },
  Stickers: {
    id: "mcHXNc",
    defaultMessage: [{
      "type": 0,
      "value": "Stickers"
    }]
  },
  frame: {
    id: "nuDv1J",
    defaultMessage: [{
      "type": 0,
      "value": "Frame"
    }]
  },
  corners: {
    id: "+bdU7f",
    defaultMessage: [{
      "type": 0,
      "value": "Corners"
    }]
  },
  merge: {
    id: "Ln1cJu",
    defaultMessage: [{
      "type": 0,
      "value": "Merge"
    }]
  }
});
const FileDownloadIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M18 15v3H6v-3H4v3c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2v-3h-2zm-1-4-1.41-1.41L13 12.17V4h-2v8.17L8.41 9.59 7 11l5 5 5-5z"
}), "FileDownloadOutlined");
const name$1 = "pixie";
const version = "3.0.2";
const main = "dist/pixie.umd.js";
const module$1 = "dist/pixie.es.js";
const types$1 = "dist/types/pixie.d.ts";
const exports = {
  ".": {
    "import": "./dist/pixie.es.js",
    require: "./dist/pixie.umd.js"
  }
};
const files = [
  "dist"
];
const scripts = {
  dev: "vite --host",
  build: "vite build && npm run build-umd && npm run build-cc",
  types: "tsc --skipLibCheck --emitDeclarationOnly --noEmit false --declarationMap false",
  "build-umd": "vite build --config scripts/vite-umd.config.ts",
  "build-cc": "./scripts/build-cc.sh",
  serve: "vite preview",
  extract: "formatjs extract 'src/**/*.{ts,tsx}' --out-file lang.json",
  compile: "formatjs compile"
};
const dependencies = {
  "@floating-ui/react-dom": "^0.6.0",
  "@internationalized/number": "^3.0.3",
  "@react-aria/button": "^3.3.4",
  "@react-aria/checkbox": "^3.2.3",
  "@react-aria/dialog": "^3.1.4",
  "@react-aria/focus": "^3.5.0",
  "@react-aria/i18n": "^3.3.4",
  "@react-aria/interactions": "^3.7.0",
  "@react-aria/label": "^3.2.1",
  "@react-aria/listbox": "^3.4.0",
  "@react-aria/menu": "^3.3.0",
  "@react-aria/numberfield": "^3.1.1",
  "@react-aria/overlays": "^3.8.0",
  "@react-aria/radio": "^3.1.6",
  "@react-aria/select": "^3.6.0",
  "@react-aria/slider": "^3.0.3",
  "@react-aria/ssr": "^3.1.0",
  "@react-aria/tabs": "^3.1.0",
  "@react-aria/textfield": "^3.5.0",
  "@react-aria/utils": "^3.11.0",
  "@react-aria/visually-hidden": "^3.2.3",
  "@react-stately/checkbox": "^3.0.3",
  "@react-stately/collections": "^3.3.4",
  "@react-stately/list": "^3.4.1",
  "@react-stately/menu": "^3.2.3",
  "@react-stately/numberfield": "^3.0.2",
  "@react-stately/overlays": "^3.1.3",
  "@react-stately/radio": "^3.3.2",
  "@react-stately/select": "^3.1.3",
  "@react-stately/slider": "^3.0.3",
  "@react-stately/tabs": "^3.0.1",
  "@react-stately/toggle": "^3.2.3",
  "@react-stately/tree": "^3.2.0",
  "@sentry/react": "^6.17.4",
  "@sentry/tracing": "^6.17.4",
  "@use-gesture/react": "^10.2.4",
  clsx: "^1.1.1",
  color: "^4.2.0",
  deepmerge: "^4.2.2",
  "dot-object": "^2.1.4",
  fabric: "^4.6.0",
  "file-saver": "^2.0.5",
  "framer-motion": "^5.3.3",
  immer: "^9.0.7",
  "number-precision": "^1.5.1",
  "react-colorful": "^5.5.1",
  "react-dropzone": "^11.5.1",
  "react-hot-toast": "^2.2.0",
  "react-intl": "^5.24.0",
  "react-virtual": "^2.10.0",
  "style-inject": "^0.3.0",
  zustand: "^3.6.9"
};
const peerDependencies = {
  react: "^17.0.2",
  "react-dom": "^17.0.0"
};
const devDependencies = {
  "@formatjs/cli": "^4.5.0",
  "@react-types/numberfield": "^3.1.0",
  "@react-types/select": "^3.5.1",
  "@react-types/tabs": "^3.0.1",
  "@types/color": "^3.0.2",
  "@types/fabric": "^4.5.3",
  "@types/file-saver": "^2.0.4",
  "@types/react": "^17.0.0",
  "@types/react-dom": "^17.0.10",
  "@typescript-eslint/eslint-plugin": "^4.33.0",
  "@typescript-eslint/parser": "^4.33.0",
  "@vitejs/plugin-react": "^1.2.0",
  autoprefixer: "^10.3.7",
  "babel-plugin-formatjs": "^10.3.12",
  cssnano: "^5.0.16",
  eslint: "^7.32.0",
  "eslint-config-airbnb": "^18.2.1",
  "eslint-config-airbnb-typescript": "^14.0.1",
  "eslint-config-prettier": "^8.3.0",
  "eslint-plugin-import": "^2.25.2",
  "eslint-plugin-jsx-a11y": "^6.4.1",
  "eslint-plugin-react": "^7.26.1",
  "eslint-plugin-react-hooks": "^4.2.0",
  "fast-xml-parser": "^4.0.0-beta.8",
  postcss: "^8.4.5",
  prettier: "^2.4.1",
  tailwindcss: "^3.0.1",
  typescript: "^4.5.2",
  vite: "^2.6.14",
  "vite-plugin-checker": "^0.3.4",
  "vite-tsconfig-paths": "^3.3.17"
};
var packageConfig = {
  name: name$1,
  version,
  main,
  module: module$1,
  types: types$1,
  "private": true,
  exports,
  files,
  scripts,
  dependencies,
  peerDependencies,
  devDependencies
};
const PIXIE_VERSION = packageConfig.version;
const DEFAULT_CONFIG = {
  selector: "pixie-editor",
  textureSize: 4096,
  ui: {
    visible: true,
    mode: EditorMode.INLINE,
    forceOverlayModeOnMobile: true,
    activeTheme: EditorTheme.LIGHT,
    themes: DEFAULT_THEMES,
    allowEditorClose: true,
    menubar: {
      items: [{
        type: "undoWidget",
        align: "left"
      }, {
        type: "zoomWidget",
        align: "center",
        desktopOnly: true
      }, {
        type: "button",
        icon: HistoryIcon,
        align: "right",
        desktopOnly: true,
        action: (editor) => {
          editor.togglePanel("history");
        }
      }, {
        type: "button",
        icon: FileDownloadIcon,
        label: defineMessage({
          id: "JXdbo8",
          defaultMessage: [{
            "type": 0,
            "value": "Done"
          }]
        }),
        align: "right",
        action: (editor) => {
          var _a2;
          if ((_a2 = editor.state.config.ui) == null ? void 0 : _a2.showExportPanel) {
            editor.state.togglePanel("export", true);
          } else {
            editor.tools.export.save("image");
          }
        }
      }]
    },
    nav: {
      position: NavPosition.BOTTOM,
      items: [...DEFAULT_NAV_ITEMS]
    },
    openImageDialog: {
      show: true,
      sampleImages: [{
        url: "images/samples/sample1.jpg",
        thumbnail: "images/samples/sample1_thumbnail.jpg"
      }, {
        url: "images/samples/sample2.jpg",
        thumbnail: "images/samples/sample2_thumbnail.jpg"
      }, {
        url: "images/samples/sample3.jpg",
        thumbnail: "images/samples/sample3_thumbnail.jpg"
      }]
    },
    colorPresets: {
      items: ["rgb(0,0,0)", "rgb(255, 255, 255)", "rgb(242, 38, 19)", "rgb(249, 105, 14)", "rgb(253, 227, 167)", "rgb(4, 147, 114)", "rgb(30, 139, 195)", "rgb(142, 68, 173)"]
    }
  },
  objectDefaults: {
    global: __spreadValues({}, defaultObjectProps),
    sticker: {
      fill: void 0
    },
    text: {
      textAlign: "initial",
      underline: false,
      linethrough: false,
      fontStyle: "normal",
      fontFamily: "Times New Roman",
      fontWeight: "normal",
      stroke: void 0,
      fontSize: 40
    }
  },
  tools: {
    filter: {
      items: ["grayscale", "blackWhite", "sharpen", "invert", "vintage", "polaroid", "kodachrome", "technicolor", "brownie", "sepia", "removeColor", "brightness", "gamma", "noise", "pixelate", "blur", "emboss", "blendColor"]
    },
    zoom: {
      allowUserZoom: true,
      fitImageToScreen: true
    },
    crop: {
      allowCustomRatio: true,
      defaultRatio: "1:1",
      presets: [{
        ratio: null,
        name: "Custom"
      }, {
        ratio: "1:1",
        name: "Square"
      }, {
        ratio: "4:3"
      }, {
        ratio: "16:9"
      }, {
        ratio: "5:3"
      }, {
        ratio: "5:4"
      }, {
        ratio: "6:4"
      }, {
        ratio: "7:5"
      }, {
        ratio: "10:8"
      }]
    },
    text: {
      defaultText: "Double click to edit",
      items: [{
        family: "Roboto",
        src: "fonts/open-sans-v27-latin-ext_latin-regular.woff2"
      }, {
        family: "Fuzzy Bubbles",
        src: "fonts/fuzzy-bubbles-v3-latin-700.woff2",
        descriptors: {
          weight: "700"
        }
      }, {
        family: "Aleo Bold",
        src: "fonts/aleo-v4-latin-ext_latin-700.woff2",
        descriptors: {
          weight: "700"
        }
      }, {
        family: "Amatic SC",
        src: "fonts/amatic-sc-v16-latin-ext_latin-regular.woff2"
      }, {
        family: "Corinthia Bold",
        src: "fonts/corinthia-v7-latin-ext_latin-700.woff2"
      }, {
        family: "Bungee Inline",
        src: "fonts/bungee-inline-v6-latin-ext_latin-regular.woff2"
      }, {
        family: "Robot Slab Bold",
        src: "fonts/roboto-slab-v16-latin-ext_latin-500.woff2"
      }, {
        family: "Carter One",
        src: "fonts/carter-one-v12-latin-regular.woff2"
      }, {
        family: "Cody Star",
        src: "fonts/codystar-v10-latin-ext_latin-regular.woff2"
      }, {
        family: "Fira Sans",
        src: "fonts/fira-sans-v11-latin-ext_latin_cyrillic-regular.woff2"
      }, {
        family: "Krona One",
        src: "fonts/krona-one-v9-latin-ext_latin-regular.woff2"
      }, {
        family: "Kumar One Outline",
        src: "fonts/kumar-one-outline-v8-latin-ext_latin-regular.woff2"
      }, {
        family: "Lobster Two",
        src: "fonts/lobster-two-v13-latin-regular.woff2"
      }, {
        family: "Molle Italic",
        src: "fonts/molle-v11-latin-ext_latin-italic.woff2"
      }, {
        family: "Monoton",
        src: "fonts/monoton-v10-latin-regular.woff2"
      }, {
        family: "Nixie One",
        src: "fonts/nixie-one-v11-latin-regular.woff2"
      }, {
        family: "Permanent Marker",
        src: "fonts/permanent-marker-v10-latin-regular.woff2"
      }, {
        family: "Sancreek",
        src: "fonts/sancreek-v13-latin-ext_latin-regular.woff2"
      }, {
        family: "Stint Ultra Expanded",
        src: "fonts/stint-ultra-expanded-v10-latin-regular.woff2"
      }, {
        family: "VT323",
        src: "fonts/vt323-v12-latin-ext_latin-regular.woff2"
      }, {
        family: "Trash Hand",
        src: "fonts/TrashHand.ttf"
      }]
    },
    draw: {
      brushSizes: BrushSizes,
      brushTypes: BrushTypes
    },
    shapes: {
      items: defaultShapes.slice()
    },
    stickers: {
      items: defaultStickers
    },
    import: {
      validImgExtensions: ["png", "jpg", "jpeg", "svg", "gif"],
      fitOverlayToScreen: true,
      openDroppedImageAsBackground: false
    },
    export: {
      defaultFormat: "png",
      defaultQuality: 0.8,
      defaultName: "image"
    },
    frame: {
      items: [{
        name: "basic",
        mode: "basic",
        size: {
          min: 1,
          max: 35,
          default: 10
        }
      }, {
        name: "pine",
        mode: "stretch",
        size: {
          min: 1,
          max: 35,
          default: 15
        }
      }, {
        name: "oak",
        mode: "stretch",
        size: {
          min: 1,
          max: 35,
          default: 15
        }
      }, {
        name: "rainbow",
        mode: "stretch",
        size: {
          min: 1,
          max: 35,
          default: 15
        }
      }, {
        name: "grunge1",
        display_name: "grunge #1",
        mode: "stretch",
        size: {
          min: 1,
          max: 35,
          default: 15
        }
      }, {
        name: "grunge2",
        display_name: "grunge #2",
        mode: "stretch",
        size: {
          min: 1,
          max: 35,
          default: 20
        }
      }, {
        name: "ebony",
        mode: "stretch",
        size: {
          min: 1,
          max: 35,
          default: 15
        }
      }, {
        name: "art1",
        display_name: "Art #1",
        mode: "repeat",
        size: {
          min: 10,
          max: 70,
          default: 55
        }
      }, {
        name: "art2",
        display_name: "Art #2",
        mode: "repeat",
        size: {
          min: 10,
          max: 70,
          default: 55
        }
      }]
    }
  }
};
function createStore(createState2) {
  let state2;
  const listeners2 = /* @__PURE__ */ new Set();
  const setState = (partial, replace) => {
    const nextState = typeof partial === "function" ? partial(state2) : partial;
    if (nextState !== state2) {
      const previousState = state2;
      state2 = replace ? nextState : Object.assign({}, state2, nextState);
      listeners2.forEach((listener) => listener(state2, previousState));
    }
  };
  const getState = () => state2;
  const subscribeWithSelector2 = (listener, selector = getState, equalityFn = Object.is) => {
    console.warn("[DEPRECATED] Please use `subscribeWithSelector` middleware");
    let currentSlice = selector(state2);
    function listenerToAdd() {
      const nextSlice = selector(state2);
      if (!equalityFn(currentSlice, nextSlice)) {
        const previousSlice = currentSlice;
        listener(currentSlice = nextSlice, previousSlice);
      }
    }
    listeners2.add(listenerToAdd);
    return () => listeners2.delete(listenerToAdd);
  };
  const subscribe = (listener, selector, equalityFn) => {
    if (selector || equalityFn) {
      return subscribeWithSelector2(listener, selector, equalityFn);
    }
    listeners2.add(listener);
    return () => listeners2.delete(listener);
  };
  const destroy = () => listeners2.clear();
  const api = { setState, getState, subscribe, destroy };
  state2 = createState2(setState, getState, api);
  return api;
}
const isSSR = typeof window === "undefined" || !window.navigator || /ServerSideRendering|^Deno\//.test(window.navigator.userAgent);
const useIsomorphicLayoutEffect$2 = isSSR ? useEffect : useLayoutEffect;
function create2(createState2) {
  const api = typeof createState2 === "function" ? createStore(createState2) : createState2;
  const useStore3 = (selector = api.getState, equalityFn = Object.is) => {
    const [, forceUpdate] = useReducer((c2) => c2 + 1, 0);
    const state2 = api.getState();
    const stateRef = useRef(state2);
    const selectorRef = useRef(selector);
    const equalityFnRef = useRef(equalityFn);
    const erroredRef = useRef(false);
    const currentSliceRef = useRef();
    if (currentSliceRef.current === void 0) {
      currentSliceRef.current = selector(state2);
    }
    let newStateSlice;
    let hasNewStateSlice = false;
    if (stateRef.current !== state2 || selectorRef.current !== selector || equalityFnRef.current !== equalityFn || erroredRef.current) {
      newStateSlice = selector(state2);
      hasNewStateSlice = !equalityFn(currentSliceRef.current, newStateSlice);
    }
    useIsomorphicLayoutEffect$2(() => {
      if (hasNewStateSlice) {
        currentSliceRef.current = newStateSlice;
      }
      stateRef.current = state2;
      selectorRef.current = selector;
      equalityFnRef.current = equalityFn;
      erroredRef.current = false;
    });
    const stateBeforeSubscriptionRef = useRef(state2);
    useIsomorphicLayoutEffect$2(() => {
      const listener = () => {
        try {
          const nextState = api.getState();
          const nextStateSlice = selectorRef.current(nextState);
          if (!equalityFnRef.current(currentSliceRef.current, nextStateSlice)) {
            stateRef.current = nextState;
            currentSliceRef.current = nextStateSlice;
            forceUpdate();
          }
        } catch (error) {
          erroredRef.current = true;
          forceUpdate();
        }
      };
      const unsubscribe = api.subscribe(listener);
      if (api.getState() !== stateBeforeSubscriptionRef.current) {
        listener();
      }
      return unsubscribe;
    }, []);
    const sliceToReturn = hasNewStateSlice ? newStateSlice : currentSliceRef.current;
    useDebugValue(sliceToReturn);
    return sliceToReturn;
  };
  Object.assign(useStore3, api);
  useStore3[Symbol.iterator] = function() {
    console.warn("[useStore, api] = create() is deprecated and will be removed in v4");
    const items = [useStore3, api];
    return {
      next() {
        const done = items.length <= 0;
        return { value: items.shift(), done };
      }
    };
  };
  return useStore3;
}
const subscribeWithSelector = (fn2) => (set, get, api) => {
  const origSubscribe = api.subscribe;
  api.subscribe = (selector, optListener, options) => {
    let listener = selector;
    if (optListener) {
      const equalityFn = (options == null ? void 0 : options.equalityFn) || Object.is;
      let currentSlice = selector(api.getState());
      listener = (state2) => {
        const nextSlice = selector(state2);
        if (!equalityFn(currentSlice, nextSlice)) {
          const previousSlice = currentSlice;
          optListener(currentSlice = nextSlice, previousSlice);
        }
      };
      if (options == null ? void 0 : options.fireImmediately) {
        optListener(currentSlice, currentSlice);
      }
    }
    return origSubscribe(listener);
  };
  const initialState2 = fn2(set, get, api);
  return initialState2;
};
function n$3(n2) {
  for (var r2 = arguments.length, t2 = Array(r2 > 1 ? r2 - 1 : 0), e2 = 1; e2 < r2; e2++)
    t2[e2 - 1] = arguments[e2];
  throw Error("[Immer] minified error nr: " + n2 + (t2.length ? " " + t2.map(function(n3) {
    return "'" + n3 + "'";
  }).join(",") : "") + ". Find the full error at: https://bit.ly/3cXEKWf");
}
function r$2(n2) {
  return !!n2 && !!n2[Q];
}
function t$2(n2) {
  return !!n2 && (function(n3) {
    if (!n3 || typeof n3 != "object")
      return false;
    var r2 = Object.getPrototypeOf(n3);
    if (r2 === null)
      return true;
    var t2 = Object.hasOwnProperty.call(r2, "constructor") && r2.constructor;
    return t2 === Object || typeof t2 == "function" && Function.toString.call(t2) === Z;
  }(n2) || Array.isArray(n2) || !!n2[L$2] || !!n2.constructor[L$2] || s$4(n2) || v$2(n2));
}
function i$4(n2, r2, t2) {
  t2 === void 0 && (t2 = false), o$3(n2) === 0 ? (t2 ? Object.keys : nn)(n2).forEach(function(e2) {
    t2 && typeof e2 == "symbol" || r2(e2, n2[e2], n2);
  }) : n2.forEach(function(t3, e2) {
    return r2(e2, t3, n2);
  });
}
function o$3(n2) {
  var r2 = n2[Q];
  return r2 ? r2.i > 3 ? r2.i - 4 : r2.i : Array.isArray(n2) ? 1 : s$4(n2) ? 2 : v$2(n2) ? 3 : 0;
}
function u$4(n2, r2) {
  return o$3(n2) === 2 ? n2.has(r2) : Object.prototype.hasOwnProperty.call(n2, r2);
}
function a$4(n2, r2) {
  return o$3(n2) === 2 ? n2.get(r2) : n2[r2];
}
function f$3(n2, r2, t2) {
  var e2 = o$3(n2);
  e2 === 2 ? n2.set(r2, t2) : e2 === 3 ? (n2.delete(r2), n2.add(t2)) : n2[r2] = t2;
}
function c$5(n2, r2) {
  return n2 === r2 ? n2 !== 0 || 1 / n2 == 1 / r2 : n2 != n2 && r2 != r2;
}
function s$4(n2) {
  return X$1 && n2 instanceof Map;
}
function v$2(n2) {
  return q$1 && n2 instanceof Set;
}
function p$3(n2) {
  return n2.o || n2.t;
}
function l$3(n2) {
  if (Array.isArray(n2))
    return Array.prototype.slice.call(n2);
  var r2 = rn(n2);
  delete r2[Q];
  for (var t2 = nn(r2), e2 = 0; e2 < t2.length; e2++) {
    var i2 = t2[e2], o2 = r2[i2];
    o2.writable === false && (o2.writable = true, o2.configurable = true), (o2.get || o2.set) && (r2[i2] = { configurable: true, writable: true, enumerable: o2.enumerable, value: n2[i2] });
  }
  return Object.create(Object.getPrototypeOf(n2), r2);
}
function d$3(n2, e2) {
  return e2 === void 0 && (e2 = false), y$2(n2) || r$2(n2) || !t$2(n2) ? n2 : (o$3(n2) > 1 && (n2.set = n2.add = n2.clear = n2.delete = h$4), Object.freeze(n2), e2 && i$4(n2, function(n3, r2) {
    return d$3(r2, true);
  }, true), n2);
}
function h$4() {
  n$3(2);
}
function y$2(n2) {
  return n2 == null || typeof n2 != "object" || Object.isFrozen(n2);
}
function b$4(r2) {
  var t2 = tn[r2];
  return t2 || n$3(18, r2), t2;
}
function _() {
  return U;
}
function j(n2, r2) {
  r2 && (b$4("Patches"), n2.u = [], n2.s = [], n2.v = r2);
}
function O$1(n2) {
  g$3(n2), n2.p.forEach(S), n2.p = null;
}
function g$3(n2) {
  n2 === U && (U = n2.l);
}
function w$2(n2) {
  return U = { p: [], l: U, h: n2, m: true, _: 0 };
}
function S(n2) {
  var r2 = n2[Q];
  r2.i === 0 || r2.i === 1 ? r2.j() : r2.O = true;
}
function P$1(r2, e2) {
  e2._ = e2.p.length;
  var i2 = e2.p[0], o2 = r2 !== void 0 && r2 !== i2;
  return e2.h.g || b$4("ES5").S(e2, r2, o2), o2 ? (i2[Q].P && (O$1(e2), n$3(4)), t$2(r2) && (r2 = M(e2, r2), e2.l || x$3(e2, r2)), e2.u && b$4("Patches").M(i2[Q].t, r2, e2.u, e2.s)) : r2 = M(e2, i2, []), O$1(e2), e2.u && e2.v(e2.u, e2.s), r2 !== H$1 ? r2 : void 0;
}
function M(n2, r2, t2) {
  if (y$2(r2))
    return r2;
  var e2 = r2[Q];
  if (!e2)
    return i$4(r2, function(i2, o3) {
      return A$1(n2, e2, r2, i2, o3, t2);
    }, true), r2;
  if (e2.A !== n2)
    return r2;
  if (!e2.P)
    return x$3(n2, e2.t, true), e2.t;
  if (!e2.I) {
    e2.I = true, e2.A._--;
    var o2 = e2.i === 4 || e2.i === 5 ? e2.o = l$3(e2.k) : e2.o;
    i$4(e2.i === 3 ? new Set(o2) : o2, function(r3, i2) {
      return A$1(n2, e2, o2, r3, i2, t2);
    }), x$3(n2, o2, false), t2 && n2.u && b$4("Patches").R(e2, t2, n2.u, n2.s);
  }
  return e2.o;
}
function A$1(e2, i2, o2, a2, c2, s2) {
  if (r$2(c2)) {
    var v2 = M(e2, c2, s2 && i2 && i2.i !== 3 && !u$4(i2.D, a2) ? s2.concat(a2) : void 0);
    if (f$3(o2, a2, v2), !r$2(v2))
      return;
    e2.m = false;
  }
  if (t$2(c2) && !y$2(c2)) {
    if (!e2.h.F && e2._ < 1)
      return;
    M(e2, c2), i2 && i2.A.l || x$3(e2, c2);
  }
}
function x$3(n2, r2, t2) {
  t2 === void 0 && (t2 = false), n2.h.F && n2.m && d$3(r2, t2);
}
function z$1(n2, r2) {
  var t2 = n2[Q];
  return (t2 ? p$3(t2) : n2)[r2];
}
function I(n2, r2) {
  if (r2 in n2)
    for (var t2 = Object.getPrototypeOf(n2); t2; ) {
      var e2 = Object.getOwnPropertyDescriptor(t2, r2);
      if (e2)
        return e2;
      t2 = Object.getPrototypeOf(t2);
    }
}
function k(n2) {
  n2.P || (n2.P = true, n2.l && k(n2.l));
}
function E$1(n2) {
  n2.o || (n2.o = l$3(n2.t));
}
function R$2(n2, r2, t2) {
  var e2 = s$4(r2) ? b$4("MapSet").N(r2, t2) : v$2(r2) ? b$4("MapSet").T(r2, t2) : n2.g ? function(n3, r3) {
    var t3 = Array.isArray(n3), e3 = { i: t3 ? 1 : 0, A: r3 ? r3.A : _(), P: false, I: false, D: {}, l: r3, t: n3, k: null, o: null, j: null, C: false }, i2 = e3, o2 = en;
    t3 && (i2 = [e3], o2 = on);
    var u2 = Proxy.revocable(i2, o2), a2 = u2.revoke, f2 = u2.proxy;
    return e3.k = f2, e3.j = a2, f2;
  }(r2, t2) : b$4("ES5").J(r2, t2);
  return (t2 ? t2.A : _()).p.push(e2), e2;
}
function D$2(e2) {
  return r$2(e2) || n$3(22, e2), function n2(r2) {
    if (!t$2(r2))
      return r2;
    var e3, u2 = r2[Q], c2 = o$3(r2);
    if (u2) {
      if (!u2.P && (u2.i < 4 || !b$4("ES5").K(u2)))
        return u2.t;
      u2.I = true, e3 = F(r2, c2), u2.I = false;
    } else
      e3 = F(r2, c2);
    return i$4(e3, function(r3, t2) {
      u2 && a$4(u2.t, r3) === t2 || f$3(e3, r3, n2(t2));
    }), c2 === 3 ? new Set(e3) : e3;
  }(e2);
}
function F(n2, r2) {
  switch (r2) {
    case 2:
      return new Map(n2);
    case 3:
      return Array.from(n2);
  }
  return l$3(n2);
}
function K$1(n2) {
  return n2;
}
var G$1, U, W$1 = typeof Symbol != "undefined" && typeof Symbol("x") == "symbol", X$1 = typeof Map != "undefined", q$1 = typeof Set != "undefined", B$1 = typeof Proxy != "undefined" && Proxy.revocable !== void 0 && typeof Reflect != "undefined", H$1 = W$1 ? Symbol.for("immer-nothing") : ((G$1 = {})["immer-nothing"] = true, G$1), L$2 = W$1 ? Symbol.for("immer-draftable") : "__$immer_draftable", Q = W$1 ? Symbol.for("immer-state") : "__$immer_state", Z = "" + Object.prototype.constructor, nn = typeof Reflect != "undefined" && Reflect.ownKeys ? Reflect.ownKeys : Object.getOwnPropertySymbols !== void 0 ? function(n2) {
  return Object.getOwnPropertyNames(n2).concat(Object.getOwnPropertySymbols(n2));
} : Object.getOwnPropertyNames, rn = Object.getOwnPropertyDescriptors || function(n2) {
  var r2 = {};
  return nn(n2).forEach(function(t2) {
    r2[t2] = Object.getOwnPropertyDescriptor(n2, t2);
  }), r2;
}, tn = {}, en = { get: function(n2, r2) {
  if (r2 === Q)
    return n2;
  var e2 = p$3(n2);
  if (!u$4(e2, r2))
    return function(n3, r3, t2) {
      var e3, i3 = I(r3, t2);
      return i3 ? "value" in i3 ? i3.value : (e3 = i3.get) === null || e3 === void 0 ? void 0 : e3.call(n3.k) : void 0;
    }(n2, e2, r2);
  var i2 = e2[r2];
  return n2.I || !t$2(i2) ? i2 : i2 === z$1(n2.t, r2) ? (E$1(n2), n2.o[r2] = R$2(n2.A.h, i2, n2)) : i2;
}, has: function(n2, r2) {
  return r2 in p$3(n2);
}, ownKeys: function(n2) {
  return Reflect.ownKeys(p$3(n2));
}, set: function(n2, r2, t2) {
  var e2 = I(p$3(n2), r2);
  if (e2 == null ? void 0 : e2.set)
    return e2.set.call(n2.k, t2), true;
  if (!n2.P) {
    var i2 = z$1(p$3(n2), r2), o2 = i2 == null ? void 0 : i2[Q];
    if (o2 && o2.t === t2)
      return n2.o[r2] = t2, n2.D[r2] = false, true;
    if (c$5(t2, i2) && (t2 !== void 0 || u$4(n2.t, r2)))
      return true;
    E$1(n2), k(n2);
  }
  return n2.o[r2] === t2 && typeof t2 != "number" && (t2 !== void 0 || r2 in n2.o) || (n2.o[r2] = t2, n2.D[r2] = true, true);
}, deleteProperty: function(n2, r2) {
  return z$1(n2.t, r2) !== void 0 || r2 in n2.t ? (n2.D[r2] = false, E$1(n2), k(n2)) : delete n2.D[r2], n2.o && delete n2.o[r2], true;
}, getOwnPropertyDescriptor: function(n2, r2) {
  var t2 = p$3(n2), e2 = Reflect.getOwnPropertyDescriptor(t2, r2);
  return e2 ? { writable: true, configurable: n2.i !== 1 || r2 !== "length", enumerable: e2.enumerable, value: t2[r2] } : e2;
}, defineProperty: function() {
  n$3(11);
}, getPrototypeOf: function(n2) {
  return Object.getPrototypeOf(n2.t);
}, setPrototypeOf: function() {
  n$3(12);
} }, on = {};
i$4(en, function(n2, r2) {
  on[n2] = function() {
    return arguments[0] = arguments[0][0], r2.apply(this, arguments);
  };
}), on.deleteProperty = function(r2, t2) {
  return on.set.call(this, r2, t2, void 0);
}, on.set = function(r2, t2, e2) {
  return en.set.call(this, r2[0], t2, e2, r2[0]);
};
var un = function() {
  function e2(r2) {
    var e3 = this;
    this.g = B$1, this.F = true, this.produce = function(r3, i3, o2) {
      if (typeof r3 == "function" && typeof i3 != "function") {
        var u2 = i3;
        i3 = r3;
        var a2 = e3;
        return function(n2) {
          var r4 = this;
          n2 === void 0 && (n2 = u2);
          for (var t2 = arguments.length, e4 = Array(t2 > 1 ? t2 - 1 : 0), o3 = 1; o3 < t2; o3++)
            e4[o3 - 1] = arguments[o3];
          return a2.produce(n2, function(n3) {
            var t3;
            return (t3 = i3).call.apply(t3, [r4, n3].concat(e4));
          });
        };
      }
      var f2;
      if (typeof i3 != "function" && n$3(6), o2 !== void 0 && typeof o2 != "function" && n$3(7), t$2(r3)) {
        var c2 = w$2(e3), s2 = R$2(e3, r3, void 0), v2 = true;
        try {
          f2 = i3(s2), v2 = false;
        } finally {
          v2 ? O$1(c2) : g$3(c2);
        }
        return typeof Promise != "undefined" && f2 instanceof Promise ? f2.then(function(n2) {
          return j(c2, o2), P$1(n2, c2);
        }, function(n2) {
          throw O$1(c2), n2;
        }) : (j(c2, o2), P$1(f2, c2));
      }
      if (!r3 || typeof r3 != "object") {
        if ((f2 = i3(r3)) === void 0 && (f2 = r3), f2 === H$1 && (f2 = void 0), e3.F && d$3(f2, true), o2) {
          var p2 = [], l2 = [];
          b$4("Patches").M(r3, f2, p2, l2), o2(p2, l2);
        }
        return f2;
      }
      n$3(21, r3);
    }, this.produceWithPatches = function(n2, r3) {
      if (typeof n2 == "function")
        return function(r4) {
          for (var t3 = arguments.length, i4 = Array(t3 > 1 ? t3 - 1 : 0), o3 = 1; o3 < t3; o3++)
            i4[o3 - 1] = arguments[o3];
          return e3.produceWithPatches(r4, function(r5) {
            return n2.apply(void 0, [r5].concat(i4));
          });
        };
      var t2, i3, o2 = e3.produce(n2, r3, function(n3, r4) {
        t2 = n3, i3 = r4;
      });
      return typeof Promise != "undefined" && o2 instanceof Promise ? o2.then(function(n3) {
        return [n3, t2, i3];
      }) : [o2, t2, i3];
    }, typeof (r2 == null ? void 0 : r2.useProxies) == "boolean" && this.setUseProxies(r2.useProxies), typeof (r2 == null ? void 0 : r2.autoFreeze) == "boolean" && this.setAutoFreeze(r2.autoFreeze);
  }
  var i2 = e2.prototype;
  return i2.createDraft = function(e3) {
    t$2(e3) || n$3(8), r$2(e3) && (e3 = D$2(e3));
    var i3 = w$2(this), o2 = R$2(this, e3, void 0);
    return o2[Q].C = true, g$3(i3), o2;
  }, i2.finishDraft = function(r2, t2) {
    var e3 = r2 && r2[Q];
    var i3 = e3.A;
    return j(i3, t2), P$1(void 0, i3);
  }, i2.setAutoFreeze = function(n2) {
    this.F = n2;
  }, i2.setUseProxies = function(r2) {
    r2 && !B$1 && n$3(20), this.g = r2;
  }, i2.applyPatches = function(n2, t2) {
    var e3;
    for (e3 = t2.length - 1; e3 >= 0; e3--) {
      var i3 = t2[e3];
      if (i3.path.length === 0 && i3.op === "replace") {
        n2 = i3.value;
        break;
      }
    }
    e3 > -1 && (t2 = t2.slice(e3 + 1));
    var o2 = b$4("Patches").$;
    return r$2(n2) ? o2(n2, t2) : this.produce(n2, function(n3) {
      return o2(n3, t2);
    });
  }, e2;
}(), an = new un(), fn = an.produce;
an.produceWithPatches.bind(an);
an.setAutoFreeze.bind(an);
an.setUseProxies.bind(an);
an.applyPatches.bind(an);
an.createDraft.bind(an);
an.finishDraft.bind(an);
var produce = fn;
function lowerFirst(string) {
  if (!string)
    return "";
  return string.charAt(0).toLowerCase() + string.slice(1);
}
function mergeConfig(userConfig, currentConfig) {
  const merged = cjs(currentConfig, userConfig);
  return replaceDefaultConfigItems(merged, userConfig);
}
function replaceDefaultConfigItems(config, userConfig) {
  Object.keys(config).forEach((key) => {
    if (key.startsWith("replaceDefault") && config[key]) {
      const iterablesKey = lowerFirst(key.replace("replaceDefault", "") || "items");
      config[iterablesKey] = userConfig ? userConfig[iterablesKey] : [];
      delete config[key];
    } else if (typeof config[key] === "object" && config[key] !== null) {
      replaceDefaultConfigItems(config[key], userConfig == null ? void 0 : userConfig[key]);
    }
  });
  return config;
}
const createHistorySlice = (set, get) => ({
  history: __spreadProps(__spreadValues({}, historySliceDefaults), {
    updatePointerById: (id2) => {
      const index2 = get().history.items.findIndex((i2) => i2.id === id2);
      get().history.update(index2);
    },
    update: (pointer, items) => {
      set((state2) => {
        state2.history.pointer = pointer;
        if (items) {
          state2.history.items = K$1(items);
        }
        state2.history.canUndo = state2.history.pointer > 0;
        state2.history.canRedo = state2.history.items.length > state2.history.pointer + 1;
      });
    },
    reset: () => {
      set({
        history: __spreadValues(__spreadValues({}, get().history), historySliceDefaults)
      });
    }
  })
});
const historySliceDefaults = {
  items: [],
  pointer: 0,
  canUndo: false,
  canRedo: false
};
var ActiveToolOverlay = /* @__PURE__ */ ((ActiveToolOverlay2) => {
  ActiveToolOverlay2["Filter"] = "filter";
  ActiveToolOverlay2["Frame"] = "frame";
  ActiveToolOverlay2["ActiveObject"] = "activeObj";
  ActiveToolOverlay2["Text"] = "text";
  return ActiveToolOverlay2;
})(ActiveToolOverlay || {});
const createFilterSlice = (set, get) => ({
  filter: __spreadProps(__spreadValues({}, filterSliceDefaults), {
    select(filterName, hasOptions = false) {
      set((state2) => {
        state2.filter.selected = filterName;
        state2.activeToolOverlay = hasOptions ? ActiveToolOverlay.Filter : null;
        state2.dirty = true;
      });
    },
    deselect(filterName) {
      if (get().filter.selected === filterName) {
        set((state2) => {
          state2.filter.selected = null;
          state2.activeToolOverlay = null;
          state2.dirty = true;
        });
      }
    },
    reset() {
      set({
        filter: __spreadValues(__spreadValues({}, get().filter), filterSliceDefaults)
      });
    }
  })
});
const filterSliceDefaults = {
  selected: null,
  applied: []
};
const createCropSlice = (set, get) => ({
  crop: __spreadProps(__spreadValues({}, cropSliceDefaults), {
    setCropzoneRect: (rect) => {
      set((state2) => {
        state2.crop.zoneRect = rect;
      });
    },
    setAspectRatio: (ratio) => {
      set((state2) => {
        state2.crop.selectedAspectRatio = ratio;
      });
    },
    setTransformAngle: (angle) => {
      set((state2) => {
        state2.crop.straightenAngle = angle;
      });
    },
    apply: async () => {
      const rect = get().crop.zoneRect;
      if (rect) {
        const scaledRect = {
          width: Math.ceil(rect.width / get().zoom),
          height: Math.ceil(rect.height / get().zoom),
          left: Math.ceil(rect.left / get().zoom),
          top: Math.ceil(rect.top / get().zoom)
        };
        await get().editor.tools.crop.apply(scaledRect);
      }
    },
    reset: () => {
      set({
        crop: __spreadValues(__spreadValues({}, get().crop), cropSliceDefaults)
      });
    }
  })
});
const cropSliceDefaults = {
  zoneRect: null,
  selectedAspectRatio: null,
  straightenAngle: 0
};
function isText(obj) {
  return (obj == null ? void 0 : obj.type) === "i-text";
}
var ObjectName = /* @__PURE__ */ ((ObjectName2) => {
  ObjectName2["Text"] = "text";
  ObjectName2["Shape"] = "shape";
  ObjectName2["Sticker"] = "sticker";
  ObjectName2["Drawing"] = "drawing";
  ObjectName2["Image"] = "image";
  ObjectName2["MainImage"] = "mainImage";
  ObjectName2["StraightenAnchor"] = "straightenHelper";
  return ObjectName2;
})(ObjectName || {});
const OBJ_DISPLAY_NAMES = {
  ["text"]: {
    name: defineMessage({
      id: "aA8bDw",
      defaultMessage: [{
        "type": 0,
        "value": "Text"
      }]
    }),
    icon: HISTORY_DISPLAY_NAMES.text.icon
  },
  ["shape"]: {
    name: defineMessage({
      id: "5Ws83M",
      defaultMessage: [{
        "type": 0,
        "value": "Shape"
      }]
    }),
    icon: HISTORY_DISPLAY_NAMES.shapes.icon
  },
  ["sticker"]: {
    name: defineMessage({
      id: "2Hku0l",
      defaultMessage: [{
        "type": 0,
        "value": "Sticker"
      }]
    }),
    icon: HISTORY_DISPLAY_NAMES.stickers.icon
  },
  ["drawing"]: {
    name: defineMessage({
      id: "jPQp7Q",
      defaultMessage: [{
        "type": 0,
        "value": "Drawing"
      }]
    }),
    icon: HISTORY_DISPLAY_NAMES.draw.icon
  },
  ["image"]: {
    name: defineMessage({
      id: "+0zv6g",
      defaultMessage: [{
        "type": 0,
        "value": "Image"
      }]
    }),
    icon: HISTORY_DISPLAY_NAMES.overlayImage.icon
  },
  ["mainImage"]: {
    name: defineMessage({
      id: "LOA559",
      defaultMessage: [{
        "type": 0,
        "value": "Background Image"
      }]
    }),
    icon: HISTORY_DISPLAY_NAMES.bgImage.icon
  }
};
function isImage(obj) {
  return obj.name === ObjectName.Image;
}
const DEFAULT_ACTIVE_OBJ_PROPS = {
  isMoving: false,
  editableProps: {},
  id: null,
  isText: false,
  isImage: false,
  name: null
};
function fabricObjToState(obj) {
  if (!obj)
    return {};
  const props2 = {
    fill: obj.fill,
    opacity: obj.opacity,
    backgroundColor: obj.backgroundColor,
    stroke: obj.stroke,
    strokeWidth: obj.strokeWidth
  };
  const shadow = obj.shadow;
  if (shadow) {
    props2.shadow = {
      color: shadow.color,
      blur: shadow.blur,
      offsetX: shadow.offsetX,
      offsetY: shadow.offsetY
    };
  }
  if (isText(obj)) {
    props2.textAlign = obj.textAlign;
    props2.underline = obj.underline;
    props2.linethrough = obj.linethrough;
    props2.fontStyle = obj.fontStyle;
    props2.fontFamily = obj.fontFamily;
    props2.fontWeight = obj.fontWeight;
    props2.fontSize = obj.fontSize;
  }
  return props2;
}
const createObjectsSlice = (set, get) => ({
  objects: __spreadProps(__spreadValues({}, objectsSliceDefaults), {
    setActiveIsMoving: (value) => {
      set((state2) => {
        state2.objects.active.isMoving = value;
      });
    },
    setIsEditingText: (value) => {
      set((state2) => {
        state2.objects.isEditingText = value;
      });
    },
    setActive: (obj) => {
      if (obj) {
        set((state2) => {
          var _a2;
          state2.objects.active.editableProps = K$1(fabricObjToState(obj));
          state2.objects.active.id = obj.data.id;
          state2.objects.active.name = (_a2 = obj.name) != null ? _a2 : null;
          state2.objects.active.isText = isText(obj);
          state2.objects.active.isImage = isImage(obj);
        });
      } else {
        set((state2) => {
          var _a2, _b, _c, _d, _e2;
          const defaultEditableProps = __spreadProps(__spreadValues({}, (_a2 = get().config.objectDefaults) == null ? void 0 : _a2.global), {
            fontFamily: (_c = (_b = get().config.objectDefaults) == null ? void 0 : _b.text) == null ? void 0 : _c.fontFamily,
            fontSize: (_e2 = (_d = get().config.objectDefaults) == null ? void 0 : _d.text) == null ? void 0 : _e2.fontSize
          });
          state2.objects.active = __spreadProps(__spreadValues({}, DEFAULT_ACTIVE_OBJ_PROPS), {
            editableProps: defaultEditableProps
          });
        });
      }
    },
    reset() {
      set({
        objects: __spreadValues(__spreadValues({}, get().objects), objectsSliceDefaults)
      });
    }
  })
});
const objectsSliceDefaults = {
  all: [],
  isEditingText: false,
  active: DEFAULT_ACTIVE_OBJ_PROPS
};
const createFrameSlice = (set, get) => ({
  frame: __spreadProps(__spreadValues({}, frameSliceDefaults), {
    select: (frame2) => {
      set((state2) => {
        state2.frame.active = frame2;
      });
      get().frame.showOptionsPanel();
    },
    deselect: () => {
      set((state2) => {
        state2.frame.active = null;
        state2.activeToolOverlay = null;
      });
    },
    showOptionsPanel: () => {
      if (get().activeTool === ToolName.FRAME) {
        set((state2) => {
          state2.activeToolOverlay = ActiveToolOverlay.Frame;
        });
      }
    },
    reset() {
      set({
        frame: __spreadValues(__spreadValues({}, get().frame), frameSliceDefaults)
      });
    }
  })
});
const frameSliceDefaults = {
  active: null
};
const createResizeSlice = (set, get) => ({
  resize: __spreadProps(__spreadValues({}, resizeSliceDefaults), {
    setFormValue: (value) => {
      set((state2) => {
        Object.entries(value).forEach(([k2, v2]) => {
          state2.resize.formValue[k2] = v2;
        });
      });
    },
    apply() {
      const newSize = get().resize.formValue;
      const oldSize = get().original;
      if (newSize.width === oldSize.width && newSize.height === oldSize.height) {
        return false;
      }
      get().editor.tools.resize.apply(newSize);
    },
    reset() {
      set({
        resize: __spreadValues(__spreadValues({}, get().resize), resizeSliceDefaults)
      });
    }
  })
});
const resizeSliceDefaults = {
  formValue: {
    width: 1,
    height: 1,
    maintainAspect: true,
    usePercentages: false
  }
};
const createCornersSlice = (set, get) => ({
  corners: __spreadProps(__spreadValues({}, cornerSliceDefaults), {
    setRadius: (newRadius) => {
      set((s2) => {
        s2.corners.radius = newRadius;
      });
    },
    apply() {
      return get().editor.tools.corners.apply(get().corners.radius);
    },
    reset() {
      set({
        corners: __spreadValues(__spreadValues({}, get().corners), cornerSliceDefaults)
      });
    }
  })
});
const cornerSliceDefaults = {
  radius: 50
};
const EMPTY_PLAIN_RECT = {
  top: 0,
  right: 0,
  bottom: 0,
  left: 0,
  width: 0,
  height: 0
};
const immer = (config) => (set, get, api) => config((partial, replace) => {
  const nextState = typeof partial === "function" ? produce(partial) : partial;
  return set(nextState, replace);
}, get, api);
const useStore$1 = create2(subscribeWithSelector(immer((set, get) => __spreadProps(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
  editor: null,
  fabric: null,
  config: DEFAULT_CONFIG,
  zoom: 1,
  dirty: false,
  original: {
    width: 1,
    height: 1
  },
  stageSize: EMPTY_PLAIN_RECT,
  canvasSize: EMPTY_PLAIN_RECT,
  activeTool: null,
  activeToolOverlay: null,
  loading: false,
  openPanels: {
    newImage: false,
    history: false,
    objects: false,
    export: false
  }
}, createHistorySlice(set, get)), createObjectsSlice(set, get)), createFilterSlice(set, get)), createCropSlice(set, get)), createFrameSlice(set, get)), createResizeSlice(set, get)), createCornersSlice(set, get)), {
  setZoom: (newZoom) => set((state2) => {
    state2.zoom = newZoom;
  }),
  setOriginal: (width, height) => set((state2) => {
    state2.original = {
      width,
      height
    };
  }),
  setDirty: (isDirty) => set((state2) => {
    state2.dirty = isDirty;
  }),
  toggleLoading: (isLoading) => set((state2) => {
    state2.loading = isLoading;
  }),
  setStageSize: (size) => set((state2) => {
    state2.stageSize = size;
  }),
  setCanvasSize: (size) => set((state2) => {
    state2.canvasSize = size;
  }),
  setActiveTool: (toolName, overlay) => set((state2) => {
    state2.activeTool = toolName;
    state2.activeToolOverlay = overlay;
  }),
  setConfig: (partialConfig) => set((state2) => {
    state2.config = K$1(mergeConfig(partialConfig, get().config));
  }),
  togglePanel: (panelName, isOpen) => set((state2) => {
    state2.openPanels[panelName] = isOpen != null ? isOpen : !state2.openPanels[panelName];
  }),
  applyChanges: async () => {
    var _a2;
    const activeToolName = get().activeTool;
    if (!activeToolName)
      return;
    const toolSlice = get()[activeToolName];
    const result = await ((_a2 = toolSlice == null ? void 0 : toolSlice.apply) == null ? void 0 : _a2.call(toolSlice));
    set((state2) => {
      state2.dirty = false;
      state2.activeTool = null;
      state2.activeToolOverlay = null;
    });
    if (result !== false) {
      get().editor.tools.history.addHistoryItem({
        name: activeToolName
      });
    }
    toolSlice == null ? void 0 : toolSlice.reset();
  },
  cancelChanges: async () => {
    const activeToolName = get().activeTool;
    if (!activeToolName)
      return;
    const wasDirty = get().dirty;
    set((state2) => {
      state2.dirty = false;
      state2.activeTool = null;
      state2.activeToolOverlay = null;
    });
    if (wasDirty) {
      await get().editor.tools.history.reload();
    }
    const toolSlice = get()[activeToolName];
    toolSlice == null ? void 0 : toolSlice.reset();
  },
  reset: () => {
    get().editor.tools.transform.resetStraightenAnchor();
    set({
      activeTool: null,
      activeToolOverlay: null,
      zoom: 1,
      dirty: false,
      loading: false,
      openPanels: {
        newImage: false,
        history: false,
        objects: false,
        export: false
      }
    });
    get().history.reset();
    get().objects.reset();
    get().filter.reset();
    get().crop.reset();
    get().frame.reset();
    get().resize.reset();
    get().corners.reset();
  }
}))));
var createDefinition = function(propNames) {
  return {
    isEnabled: function(props2) {
      return propNames.some(function(name) {
        return !!props2[name];
      });
    }
  };
};
var featureDefinitions = {
  measureLayout: createDefinition(["layout", "layoutId", "drag"]),
  animation: createDefinition([
    "animate",
    "exit",
    "variants",
    "whileHover",
    "whileTap",
    "whileFocus",
    "whileDrag",
    "whileInView"
  ]),
  exit: createDefinition(["exit"]),
  drag: createDefinition(["drag", "dragControls"]),
  focus: createDefinition(["whileFocus"]),
  hover: createDefinition(["whileHover", "onHoverStart", "onHoverEnd"]),
  tap: createDefinition(["whileTap", "onTap", "onTapStart", "onTapCancel"]),
  pan: createDefinition([
    "onPan",
    "onPanStart",
    "onPanSessionStart",
    "onPanEnd"
  ]),
  inView: createDefinition([
    "whileInView",
    "onViewportEnter",
    "onViewportLeave"
  ])
};
function loadFeatures(features) {
  for (var key in features) {
    if (features[key] === null)
      continue;
    if (key === "projectionNodeConstructor") {
      featureDefinitions.projectionNodeConstructor = features[key];
    } else {
      featureDefinitions[key].Component = features[key];
    }
  }
}
var warning = function() {
};
var invariant = function() {
};
var LazyContext = createContext({ strict: false });
var featureNames = Object.keys(featureDefinitions);
var numFeatures = featureNames.length;
function useFeatures(props2, visualElement2, preloadedFeatures) {
  var features = [];
  useContext(LazyContext);
  if (!visualElement2)
    return null;
  for (var i2 = 0; i2 < numFeatures; i2++) {
    var name_1 = featureNames[i2];
    var _a2 = featureDefinitions[name_1], isEnabled = _a2.isEnabled, Component = _a2.Component;
    if (isEnabled(props2) && Component) {
      features.push(React__default.createElement(Component, __assign({ key: name_1 }, props2, { visualElement: visualElement2 })));
    }
  }
  return features;
}
var MotionConfigContext = createContext({
  transformPagePoint: function(p2) {
    return p2;
  },
  isStatic: false
});
var MotionContext = createContext({});
function useVisualElementContext() {
  return useContext(MotionContext).visualElement;
}
var PresenceContext = createContext(null);
var isBrowser$1 = typeof window !== "undefined";
var useIsomorphicLayoutEffect$1 = isBrowser$1 ? useLayoutEffect : useEffect;
function useVisualElement(Component, visualState, props2, createVisualElement) {
  var lazyContext = useContext(LazyContext);
  var parent = useVisualElementContext();
  var presenceContext = useContext(PresenceContext);
  var visualElementRef = useRef(void 0);
  if (!createVisualElement)
    createVisualElement = lazyContext.renderer;
  if (!visualElementRef.current && createVisualElement) {
    visualElementRef.current = createVisualElement(Component, {
      visualState,
      parent,
      props: props2,
      presenceId: presenceContext === null || presenceContext === void 0 ? void 0 : presenceContext.id,
      blockInitialAnimation: (presenceContext === null || presenceContext === void 0 ? void 0 : presenceContext.initial) === false
    });
  }
  var visualElement2 = visualElementRef.current;
  useIsomorphicLayoutEffect$1(function() {
    visualElement2 === null || visualElement2 === void 0 ? void 0 : visualElement2.syncRender();
  });
  useEffect(function() {
    var _a2;
    (_a2 = visualElement2 === null || visualElement2 === void 0 ? void 0 : visualElement2.animationState) === null || _a2 === void 0 ? void 0 : _a2.animateChanges();
  });
  useIsomorphicLayoutEffect$1(function() {
    return function() {
      return visualElement2 === null || visualElement2 === void 0 ? void 0 : visualElement2.notifyUnmount();
    };
  }, []);
  return visualElement2;
}
function isRefObject(ref) {
  return typeof ref === "object" && Object.prototype.hasOwnProperty.call(ref, "current");
}
function useMotionRef(visualState, visualElement2, externalRef) {
  return useCallback(function(instance) {
    var _a2;
    instance && ((_a2 = visualState.mount) === null || _a2 === void 0 ? void 0 : _a2.call(visualState, instance));
    if (visualElement2) {
      instance ? visualElement2.mount(instance) : visualElement2.unmount();
    }
    if (externalRef) {
      if (typeof externalRef === "function") {
        externalRef(instance);
      } else if (isRefObject(externalRef)) {
        externalRef.current = instance;
      }
    }
  }, [visualElement2]);
}
function isVariantLabels(v2) {
  return Array.isArray(v2);
}
function isVariantLabel(v2) {
  return typeof v2 === "string" || isVariantLabels(v2);
}
function getCurrent(visualElement2) {
  var current = {};
  visualElement2.forEachValue(function(value, key) {
    return current[key] = value.get();
  });
  return current;
}
function getVelocity(visualElement2) {
  var velocity = {};
  visualElement2.forEachValue(function(value, key) {
    return velocity[key] = value.getVelocity();
  });
  return velocity;
}
function resolveVariantFromProps(props2, definition, custom, currentValues, currentVelocity) {
  var _a2;
  if (currentValues === void 0) {
    currentValues = {};
  }
  if (currentVelocity === void 0) {
    currentVelocity = {};
  }
  if (typeof definition === "function") {
    definition = definition(custom !== null && custom !== void 0 ? custom : props2.custom, currentValues, currentVelocity);
  }
  if (typeof definition === "string") {
    definition = (_a2 = props2.variants) === null || _a2 === void 0 ? void 0 : _a2[definition];
  }
  if (typeof definition === "function") {
    definition = definition(custom !== null && custom !== void 0 ? custom : props2.custom, currentValues, currentVelocity);
  }
  return definition;
}
function resolveVariant(visualElement2, definition, custom) {
  var props2 = visualElement2.getProps();
  return resolveVariantFromProps(props2, definition, custom !== null && custom !== void 0 ? custom : props2.custom, getCurrent(visualElement2), getVelocity(visualElement2));
}
function checkIfControllingVariants(props2) {
  var _a2;
  return typeof ((_a2 = props2.animate) === null || _a2 === void 0 ? void 0 : _a2.start) === "function" || isVariantLabel(props2.initial) || isVariantLabel(props2.animate) || isVariantLabel(props2.whileHover) || isVariantLabel(props2.whileDrag) || isVariantLabel(props2.whileTap) || isVariantLabel(props2.whileFocus) || isVariantLabel(props2.exit);
}
function checkIfVariantNode(props2) {
  return Boolean(checkIfControllingVariants(props2) || props2.variants);
}
function getCurrentTreeVariants(props2, context) {
  if (checkIfControllingVariants(props2)) {
    var initial = props2.initial, animate2 = props2.animate;
    return {
      initial: initial === false || isVariantLabel(initial) ? initial : void 0,
      animate: isVariantLabel(animate2) ? animate2 : void 0
    };
  }
  return props2.inherit !== false ? context : {};
}
function useCreateMotionContext(props2) {
  var _a2 = getCurrentTreeVariants(props2, useContext(MotionContext)), initial = _a2.initial, animate2 = _a2.animate;
  return useMemo(function() {
    return { initial, animate: animate2 };
  }, [variantLabelsAsDependency(initial), variantLabelsAsDependency(animate2)]);
}
function variantLabelsAsDependency(prop) {
  return Array.isArray(prop) ? prop.join(" ") : prop;
}
function useConstant(init2) {
  var ref = useRef(null);
  if (ref.current === null) {
    ref.current = init2();
  }
  return ref.current;
}
const defaultTimestep = 1 / 60 * 1e3;
const getCurrentTime = typeof performance !== "undefined" ? () => performance.now() : () => Date.now();
const onNextFrame = typeof window !== "undefined" ? (callback) => window.requestAnimationFrame(callback) : (callback) => setTimeout(() => callback(getCurrentTime()), defaultTimestep);
function createRenderStep(runNextFrame2) {
  let toRun = [];
  let toRunNextFrame = [];
  let numToRun = 0;
  let isProcessing2 = false;
  let flushNextFrame = false;
  const toKeepAlive = /* @__PURE__ */ new WeakSet();
  const step = {
    schedule: (callback, keepAlive = false, immediate = false) => {
      const addToCurrentFrame = immediate && isProcessing2;
      const buffer = addToCurrentFrame ? toRun : toRunNextFrame;
      if (keepAlive)
        toKeepAlive.add(callback);
      if (buffer.indexOf(callback) === -1) {
        buffer.push(callback);
        if (addToCurrentFrame && isProcessing2)
          numToRun = toRun.length;
      }
      return callback;
    },
    cancel: (callback) => {
      const index2 = toRunNextFrame.indexOf(callback);
      if (index2 !== -1)
        toRunNextFrame.splice(index2, 1);
      toKeepAlive.delete(callback);
    },
    process: (frameData) => {
      if (isProcessing2) {
        flushNextFrame = true;
        return;
      }
      isProcessing2 = true;
      [toRun, toRunNextFrame] = [toRunNextFrame, toRun];
      toRunNextFrame.length = 0;
      numToRun = toRun.length;
      if (numToRun) {
        for (let i2 = 0; i2 < numToRun; i2++) {
          const callback = toRun[i2];
          callback(frameData);
          if (toKeepAlive.has(callback)) {
            step.schedule(callback);
            runNextFrame2();
          }
        }
      }
      isProcessing2 = false;
      if (flushNextFrame) {
        flushNextFrame = false;
        step.process(frameData);
      }
    }
  };
  return step;
}
const maxElapsed = 40;
let useDefaultElapsed = true;
let runNextFrame = false;
let isProcessing = false;
const frame = {
  delta: 0,
  timestamp: 0
};
const stepsOrder = [
  "read",
  "update",
  "preRender",
  "render",
  "postRender"
];
const steps = stepsOrder.reduce((acc, key) => {
  acc[key] = createRenderStep(() => runNextFrame = true);
  return acc;
}, {});
const sync = stepsOrder.reduce((acc, key) => {
  const step = steps[key];
  acc[key] = (process2, keepAlive = false, immediate = false) => {
    if (!runNextFrame)
      startLoop();
    return step.schedule(process2, keepAlive, immediate);
  };
  return acc;
}, {});
const cancelSync = stepsOrder.reduce((acc, key) => {
  acc[key] = steps[key].cancel;
  return acc;
}, {});
stepsOrder.reduce((acc, key) => {
  acc[key] = () => steps[key].process(frame);
  return acc;
}, {});
const processStep = (stepId) => steps[stepId].process(frame);
const processFrame = (timestamp) => {
  runNextFrame = false;
  frame.delta = useDefaultElapsed ? defaultTimestep : Math.max(Math.min(timestamp - frame.timestamp, maxElapsed), 1);
  frame.timestamp = timestamp;
  isProcessing = true;
  stepsOrder.forEach(processStep);
  isProcessing = false;
  if (runNextFrame) {
    useDefaultElapsed = false;
    onNextFrame(processFrame);
  }
};
const startLoop = () => {
  runNextFrame = true;
  useDefaultElapsed = true;
  if (!isProcessing)
    onNextFrame(processFrame);
};
const getFrameData = () => frame;
const clamp$3 = (min, max, v2) => Math.min(Math.max(v2, min), max);
const safeMin = 1e-3;
const minDuration = 0.01;
const maxDuration = 10;
const minDamping = 0.05;
const maxDamping = 1;
function findSpring({ duration = 800, bounce = 0.25, velocity = 0, mass = 1 }) {
  let envelope;
  let derivative;
  warning(duration <= maxDuration * 1e3);
  let dampingRatio = 1 - bounce;
  dampingRatio = clamp$3(minDamping, maxDamping, dampingRatio);
  duration = clamp$3(minDuration, maxDuration, duration / 1e3);
  if (dampingRatio < 1) {
    envelope = (undampedFreq2) => {
      const exponentialDecay = undampedFreq2 * dampingRatio;
      const delta = exponentialDecay * duration;
      const a2 = exponentialDecay - velocity;
      const b2 = calcAngularFreq(undampedFreq2, dampingRatio);
      const c2 = Math.exp(-delta);
      return safeMin - a2 / b2 * c2;
    };
    derivative = (undampedFreq2) => {
      const exponentialDecay = undampedFreq2 * dampingRatio;
      const delta = exponentialDecay * duration;
      const d2 = delta * velocity + velocity;
      const e2 = Math.pow(dampingRatio, 2) * Math.pow(undampedFreq2, 2) * duration;
      const f2 = Math.exp(-delta);
      const g2 = calcAngularFreq(Math.pow(undampedFreq2, 2), dampingRatio);
      const factor = -envelope(undampedFreq2) + safeMin > 0 ? -1 : 1;
      return factor * ((d2 - e2) * f2) / g2;
    };
  } else {
    envelope = (undampedFreq2) => {
      const a2 = Math.exp(-undampedFreq2 * duration);
      const b2 = (undampedFreq2 - velocity) * duration + 1;
      return -safeMin + a2 * b2;
    };
    derivative = (undampedFreq2) => {
      const a2 = Math.exp(-undampedFreq2 * duration);
      const b2 = (velocity - undampedFreq2) * (duration * duration);
      return a2 * b2;
    };
  }
  const initialGuess = 5 / duration;
  const undampedFreq = approximateRoot(envelope, derivative, initialGuess);
  duration = duration * 1e3;
  if (isNaN(undampedFreq)) {
    return {
      stiffness: 100,
      damping: 10,
      duration
    };
  } else {
    const stiffness = Math.pow(undampedFreq, 2) * mass;
    return {
      stiffness,
      damping: dampingRatio * 2 * Math.sqrt(mass * stiffness),
      duration
    };
  }
}
const rootIterations = 12;
function approximateRoot(envelope, derivative, initialGuess) {
  let result = initialGuess;
  for (let i2 = 1; i2 < rootIterations; i2++) {
    result = result - envelope(result) / derivative(result);
  }
  return result;
}
function calcAngularFreq(undampedFreq, dampingRatio) {
  return undampedFreq * Math.sqrt(1 - dampingRatio * dampingRatio);
}
const durationKeys = ["duration", "bounce"];
const physicsKeys = ["stiffness", "damping", "mass"];
function isSpringType(options, keys) {
  return keys.some((key) => options[key] !== void 0);
}
function getSpringOptions(options) {
  let springOptions = Object.assign({ velocity: 0, stiffness: 100, damping: 10, mass: 1, isResolvedFromDuration: false }, options);
  if (!isSpringType(options, physicsKeys) && isSpringType(options, durationKeys)) {
    const derived = findSpring(options);
    springOptions = Object.assign(Object.assign(Object.assign({}, springOptions), derived), { velocity: 0, mass: 1 });
    springOptions.isResolvedFromDuration = true;
  }
  return springOptions;
}
function spring(_a2) {
  var { from = 0, to = 1, restSpeed = 2, restDelta } = _a2, options = __rest(_a2, ["from", "to", "restSpeed", "restDelta"]);
  const state2 = { done: false, value: from };
  let { stiffness, damping, mass, velocity, duration, isResolvedFromDuration } = getSpringOptions(options);
  let resolveSpring = zero;
  let resolveVelocity = zero;
  function createSpring() {
    const initialVelocity = velocity ? -(velocity / 1e3) : 0;
    const initialDelta = to - from;
    const dampingRatio = damping / (2 * Math.sqrt(stiffness * mass));
    const undampedAngularFreq = Math.sqrt(stiffness / mass) / 1e3;
    if (restDelta === void 0) {
      restDelta = Math.min(Math.abs(to - from) / 100, 0.4);
    }
    if (dampingRatio < 1) {
      const angularFreq = calcAngularFreq(undampedAngularFreq, dampingRatio);
      resolveSpring = (t2) => {
        const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t2);
        return to - envelope * ((initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) / angularFreq * Math.sin(angularFreq * t2) + initialDelta * Math.cos(angularFreq * t2));
      };
      resolveVelocity = (t2) => {
        const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t2);
        return dampingRatio * undampedAngularFreq * envelope * (Math.sin(angularFreq * t2) * (initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) / angularFreq + initialDelta * Math.cos(angularFreq * t2)) - envelope * (Math.cos(angularFreq * t2) * (initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) - angularFreq * initialDelta * Math.sin(angularFreq * t2));
      };
    } else if (dampingRatio === 1) {
      resolveSpring = (t2) => to - Math.exp(-undampedAngularFreq * t2) * (initialDelta + (initialVelocity + undampedAngularFreq * initialDelta) * t2);
    } else {
      const dampedAngularFreq = undampedAngularFreq * Math.sqrt(dampingRatio * dampingRatio - 1);
      resolveSpring = (t2) => {
        const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t2);
        const freqForT = Math.min(dampedAngularFreq * t2, 300);
        return to - envelope * ((initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) * Math.sinh(freqForT) + dampedAngularFreq * initialDelta * Math.cosh(freqForT)) / dampedAngularFreq;
      };
    }
  }
  createSpring();
  return {
    next: (t2) => {
      const current = resolveSpring(t2);
      if (!isResolvedFromDuration) {
        const currentVelocity = resolveVelocity(t2) * 1e3;
        const isBelowVelocityThreshold = Math.abs(currentVelocity) <= restSpeed;
        const isBelowDisplacementThreshold = Math.abs(to - current) <= restDelta;
        state2.done = isBelowVelocityThreshold && isBelowDisplacementThreshold;
      } else {
        state2.done = t2 >= duration;
      }
      state2.value = state2.done ? to : current;
      return state2;
    },
    flipTarget: () => {
      velocity = -velocity;
      [from, to] = [to, from];
      createSpring();
    }
  };
}
spring.needsInterpolation = (a2, b2) => typeof a2 === "string" || typeof b2 === "string";
const zero = (_t) => 0;
const progress = (from, to, value) => {
  const toFromDifference = to - from;
  return toFromDifference === 0 ? 1 : (value - from) / toFromDifference;
};
const mix = (from, to, progress2) => -progress2 * from + progress2 * to + from;
const clamp$2 = (min, max) => (v2) => Math.max(Math.min(v2, max), min);
const sanitize = (v2) => v2 % 1 ? Number(v2.toFixed(5)) : v2;
const floatRegex = /(-)?([\d]*\.?[\d])+/g;
const colorRegex = /(#[0-9a-f]{6}|#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2,3}\s*\/*\s*[\d\.]+%?\))/gi;
const singleColorRegex = /^(#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2,3}\s*\/*\s*[\d\.]+%?\))$/i;
function isString(v2) {
  return typeof v2 === "string";
}
const number = {
  test: (v2) => typeof v2 === "number",
  parse: parseFloat,
  transform: (v2) => v2
};
const alpha = Object.assign(Object.assign({}, number), { transform: clamp$2(0, 1) });
const scale = Object.assign(Object.assign({}, number), { default: 1 });
const createUnitType = (unit) => ({
  test: (v2) => isString(v2) && v2.endsWith(unit) && v2.split(" ").length === 1,
  parse: parseFloat,
  transform: (v2) => `${v2}${unit}`
});
const degrees = createUnitType("deg");
const percent = createUnitType("%");
const px = createUnitType("px");
const vh = createUnitType("vh");
const vw = createUnitType("vw");
const progressPercentage = Object.assign(Object.assign({}, percent), { parse: (v2) => percent.parse(v2) / 100, transform: (v2) => percent.transform(v2 * 100) });
const isColorString = (type, testProp) => (v2) => {
  return Boolean(isString(v2) && singleColorRegex.test(v2) && v2.startsWith(type) || testProp && Object.prototype.hasOwnProperty.call(v2, testProp));
};
const splitColor = (aName, bName, cName) => (v2) => {
  if (!isString(v2))
    return v2;
  const [a2, b2, c2, alpha2] = v2.match(floatRegex);
  return {
    [aName]: parseFloat(a2),
    [bName]: parseFloat(b2),
    [cName]: parseFloat(c2),
    alpha: alpha2 !== void 0 ? parseFloat(alpha2) : 1
  };
};
const hsla = {
  test: isColorString("hsl", "hue"),
  parse: splitColor("hue", "saturation", "lightness"),
  transform: ({ hue, saturation, lightness, alpha: alpha$1 = 1 }) => {
    return "hsla(" + Math.round(hue) + ", " + percent.transform(sanitize(saturation)) + ", " + percent.transform(sanitize(lightness)) + ", " + sanitize(alpha.transform(alpha$1)) + ")";
  }
};
const clampRgbUnit = clamp$2(0, 255);
const rgbUnit = Object.assign(Object.assign({}, number), { transform: (v2) => Math.round(clampRgbUnit(v2)) });
const rgba = {
  test: isColorString("rgb", "red"),
  parse: splitColor("red", "green", "blue"),
  transform: ({ red, green, blue, alpha: alpha$1 = 1 }) => "rgba(" + rgbUnit.transform(red) + ", " + rgbUnit.transform(green) + ", " + rgbUnit.transform(blue) + ", " + sanitize(alpha.transform(alpha$1)) + ")"
};
function parseHex(v2) {
  let r2 = "";
  let g2 = "";
  let b2 = "";
  let a2 = "";
  if (v2.length > 5) {
    r2 = v2.substr(1, 2);
    g2 = v2.substr(3, 2);
    b2 = v2.substr(5, 2);
    a2 = v2.substr(7, 2);
  } else {
    r2 = v2.substr(1, 1);
    g2 = v2.substr(2, 1);
    b2 = v2.substr(3, 1);
    a2 = v2.substr(4, 1);
    r2 += r2;
    g2 += g2;
    b2 += b2;
    a2 += a2;
  }
  return {
    red: parseInt(r2, 16),
    green: parseInt(g2, 16),
    blue: parseInt(b2, 16),
    alpha: a2 ? parseInt(a2, 16) / 255 : 1
  };
}
const hex = {
  test: isColorString("#"),
  parse: parseHex,
  transform: rgba.transform
};
const color$1 = {
  test: (v2) => rgba.test(v2) || hex.test(v2) || hsla.test(v2),
  parse: (v2) => {
    if (rgba.test(v2)) {
      return rgba.parse(v2);
    } else if (hsla.test(v2)) {
      return hsla.parse(v2);
    } else {
      return hex.parse(v2);
    }
  },
  transform: (v2) => {
    return isString(v2) ? v2 : v2.hasOwnProperty("red") ? rgba.transform(v2) : hsla.transform(v2);
  }
};
const colorToken = "${c}";
const numberToken = "${n}";
function test(v2) {
  var _a2, _b, _c, _d;
  return isNaN(v2) && isString(v2) && ((_b = (_a2 = v2.match(floatRegex)) === null || _a2 === void 0 ? void 0 : _a2.length) !== null && _b !== void 0 ? _b : 0) + ((_d = (_c = v2.match(colorRegex)) === null || _c === void 0 ? void 0 : _c.length) !== null && _d !== void 0 ? _d : 0) > 0;
}
function analyse$1(v2) {
  if (typeof v2 === "number")
    v2 = `${v2}`;
  const values = [];
  let numColors = 0;
  const colors = v2.match(colorRegex);
  if (colors) {
    numColors = colors.length;
    v2 = v2.replace(colorRegex, colorToken);
    values.push(...colors.map(color$1.parse));
  }
  const numbers = v2.match(floatRegex);
  if (numbers) {
    v2 = v2.replace(floatRegex, numberToken);
    values.push(...numbers.map(number.parse));
  }
  return { values, numColors, tokenised: v2 };
}
function parse$1(v2) {
  return analyse$1(v2).values;
}
function createTransformer(v2) {
  const { values, numColors, tokenised } = analyse$1(v2);
  const numValues = values.length;
  return (v3) => {
    let output = tokenised;
    for (let i2 = 0; i2 < numValues; i2++) {
      output = output.replace(i2 < numColors ? colorToken : numberToken, i2 < numColors ? color$1.transform(v3[i2]) : sanitize(v3[i2]));
    }
    return output;
  };
}
const convertNumbersToZero = (v2) => typeof v2 === "number" ? 0 : v2;
function getAnimatableNone$1(v2) {
  const parsed = parse$1(v2);
  const transformer = createTransformer(v2);
  return transformer(parsed.map(convertNumbersToZero));
}
const complex = { test, parse: parse$1, createTransformer, getAnimatableNone: getAnimatableNone$1 };
const maxDefaults = /* @__PURE__ */ new Set(["brightness", "contrast", "saturate", "opacity"]);
function applyDefaultFilter(v2) {
  let [name, value] = v2.slice(0, -1).split("(");
  if (name === "drop-shadow")
    return v2;
  const [number2] = value.match(floatRegex) || [];
  if (!number2)
    return v2;
  const unit = value.replace(number2, "");
  let defaultValue = maxDefaults.has(name) ? 1 : 0;
  if (number2 !== value)
    defaultValue *= 100;
  return name + "(" + defaultValue + unit + ")";
}
const functionRegex = /([a-z-]*)\(.*?\)/g;
const filter = Object.assign(Object.assign({}, complex), { getAnimatableNone: (v2) => {
  const functions = v2.match(functionRegex);
  return functions ? functions.map(applyDefaultFilter).join(" ") : v2;
} });
function hueToRgb(p2, q2, t2) {
  if (t2 < 0)
    t2 += 1;
  if (t2 > 1)
    t2 -= 1;
  if (t2 < 1 / 6)
    return p2 + (q2 - p2) * 6 * t2;
  if (t2 < 1 / 2)
    return q2;
  if (t2 < 2 / 3)
    return p2 + (q2 - p2) * (2 / 3 - t2) * 6;
  return p2;
}
function hslaToRgba({ hue, saturation, lightness, alpha: alpha2 }) {
  hue /= 360;
  saturation /= 100;
  lightness /= 100;
  let red = 0;
  let green = 0;
  let blue = 0;
  if (!saturation) {
    red = green = blue = lightness;
  } else {
    const q2 = lightness < 0.5 ? lightness * (1 + saturation) : lightness + saturation - lightness * saturation;
    const p2 = 2 * lightness - q2;
    red = hueToRgb(p2, q2, hue + 1 / 3);
    green = hueToRgb(p2, q2, hue);
    blue = hueToRgb(p2, q2, hue - 1 / 3);
  }
  return {
    red: Math.round(red * 255),
    green: Math.round(green * 255),
    blue: Math.round(blue * 255),
    alpha: alpha2
  };
}
const mixLinearColor = (from, to, v2) => {
  const fromExpo = from * from;
  const toExpo = to * to;
  return Math.sqrt(Math.max(0, v2 * (toExpo - fromExpo) + fromExpo));
};
const colorTypes = [hex, rgba, hsla];
const getColorType = (v2) => colorTypes.find((type) => type.test(v2));
const mixColor = (from, to) => {
  let fromColorType = getColorType(from);
  let toColorType = getColorType(to);
  let fromColor = fromColorType.parse(from);
  let toColor = toColorType.parse(to);
  if (fromColorType === hsla) {
    fromColor = hslaToRgba(fromColor);
    fromColorType = rgba;
  }
  if (toColorType === hsla) {
    toColor = hslaToRgba(toColor);
    toColorType = rgba;
  }
  const blended = Object.assign({}, fromColor);
  return (v2) => {
    for (const key in blended) {
      if (key !== "alpha") {
        blended[key] = mixLinearColor(fromColor[key], toColor[key], v2);
      }
    }
    blended.alpha = mix(fromColor.alpha, toColor.alpha, v2);
    return fromColorType.transform(blended);
  };
};
const isNum = (v2) => typeof v2 === "number";
const combineFunctions = (a2, b2) => (v2) => b2(a2(v2));
const pipe = (...transformers) => transformers.reduce(combineFunctions);
function getMixer(origin, target) {
  if (isNum(origin)) {
    return (v2) => mix(origin, target, v2);
  } else if (color$1.test(origin)) {
    return mixColor(origin, target);
  } else {
    return mixComplex(origin, target);
  }
}
const mixArray = (from, to) => {
  const output = [...from];
  const numValues = output.length;
  const blendValue = from.map((fromThis, i2) => getMixer(fromThis, to[i2]));
  return (v2) => {
    for (let i2 = 0; i2 < numValues; i2++) {
      output[i2] = blendValue[i2](v2);
    }
    return output;
  };
};
const mixObject = (origin, target) => {
  const output = Object.assign(Object.assign({}, origin), target);
  const blendValue = {};
  for (const key in output) {
    if (origin[key] !== void 0 && target[key] !== void 0) {
      blendValue[key] = getMixer(origin[key], target[key]);
    }
  }
  return (v2) => {
    for (const key in blendValue) {
      output[key] = blendValue[key](v2);
    }
    return output;
  };
};
function analyse(value) {
  const parsed = complex.parse(value);
  const numValues = parsed.length;
  let numNumbers = 0;
  let numRGB = 0;
  let numHSL = 0;
  for (let i2 = 0; i2 < numValues; i2++) {
    if (numNumbers || typeof parsed[i2] === "number") {
      numNumbers++;
    } else {
      if (parsed[i2].hue !== void 0) {
        numHSL++;
      } else {
        numRGB++;
      }
    }
  }
  return { parsed, numNumbers, numRGB, numHSL };
}
const mixComplex = (origin, target) => {
  const template = complex.createTransformer(target);
  const originStats = analyse(origin);
  const targetStats = analyse(target);
  const canInterpolate = originStats.numHSL === targetStats.numHSL && originStats.numRGB === targetStats.numRGB && originStats.numNumbers >= targetStats.numNumbers;
  if (canInterpolate) {
    return pipe(mixArray(originStats.parsed, targetStats.parsed), template);
  } else {
    return (p2) => `${p2 > 0 ? target : origin}`;
  }
};
const mixNumber = (from, to) => (p2) => mix(from, to, p2);
function detectMixerFactory(v2) {
  if (typeof v2 === "number") {
    return mixNumber;
  } else if (typeof v2 === "string") {
    if (color$1.test(v2)) {
      return mixColor;
    } else {
      return mixComplex;
    }
  } else if (Array.isArray(v2)) {
    return mixArray;
  } else if (typeof v2 === "object") {
    return mixObject;
  }
}
function createMixers(output, ease, customMixer) {
  const mixers = [];
  const mixerFactory = customMixer || detectMixerFactory(output[0]);
  const numMixers = output.length - 1;
  for (let i2 = 0; i2 < numMixers; i2++) {
    let mixer = mixerFactory(output[i2], output[i2 + 1]);
    if (ease) {
      const easingFunction = Array.isArray(ease) ? ease[i2] : ease;
      mixer = pipe(easingFunction, mixer);
    }
    mixers.push(mixer);
  }
  return mixers;
}
function fastInterpolate([from, to], [mixer]) {
  return (v2) => mixer(progress(from, to, v2));
}
function slowInterpolate(input, mixers) {
  const inputLength = input.length;
  const lastInputIndex = inputLength - 1;
  return (v2) => {
    let mixerIndex = 0;
    let foundMixerIndex = false;
    if (v2 <= input[0]) {
      foundMixerIndex = true;
    } else if (v2 >= input[lastInputIndex]) {
      mixerIndex = lastInputIndex - 1;
      foundMixerIndex = true;
    }
    if (!foundMixerIndex) {
      let i2 = 1;
      for (; i2 < inputLength; i2++) {
        if (input[i2] > v2 || i2 === lastInputIndex) {
          break;
        }
      }
      mixerIndex = i2 - 1;
    }
    const progressInRange = progress(input[mixerIndex], input[mixerIndex + 1], v2);
    return mixers[mixerIndex](progressInRange);
  };
}
function interpolate(input, output, { clamp: isClamp = true, ease, mixer } = {}) {
  const inputLength = input.length;
  invariant(inputLength === output.length);
  invariant(!ease || !Array.isArray(ease) || ease.length === inputLength - 1);
  if (input[0] > input[inputLength - 1]) {
    input = [].concat(input);
    output = [].concat(output);
    input.reverse();
    output.reverse();
  }
  const mixers = createMixers(output, ease, mixer);
  const interpolator = inputLength === 2 ? fastInterpolate(input, mixers) : slowInterpolate(input, mixers);
  return isClamp ? (v2) => interpolator(clamp$3(input[0], input[inputLength - 1], v2)) : interpolator;
}
const reverseEasing = (easing) => (p2) => 1 - easing(1 - p2);
const mirrorEasing = (easing) => (p2) => p2 <= 0.5 ? easing(2 * p2) / 2 : (2 - easing(2 * (1 - p2))) / 2;
const createExpoIn = (power) => (p2) => Math.pow(p2, power);
const createBackIn = (power) => (p2) => p2 * p2 * ((power + 1) * p2 - power);
const createAnticipate = (power) => {
  const backEasing = createBackIn(power);
  return (p2) => (p2 *= 2) < 1 ? 0.5 * backEasing(p2) : 0.5 * (2 - Math.pow(2, -10 * (p2 - 1)));
};
const DEFAULT_OVERSHOOT_STRENGTH = 1.525;
const BOUNCE_FIRST_THRESHOLD = 4 / 11;
const BOUNCE_SECOND_THRESHOLD = 8 / 11;
const BOUNCE_THIRD_THRESHOLD = 9 / 10;
const linear = (p2) => p2;
const easeIn = createExpoIn(2);
const easeOut = reverseEasing(easeIn);
const easeInOut = mirrorEasing(easeIn);
const circIn = (p2) => 1 - Math.sin(Math.acos(p2));
const circOut = reverseEasing(circIn);
const circInOut = mirrorEasing(circOut);
const backIn = createBackIn(DEFAULT_OVERSHOOT_STRENGTH);
const backOut = reverseEasing(backIn);
const backInOut = mirrorEasing(backIn);
const anticipate = createAnticipate(DEFAULT_OVERSHOOT_STRENGTH);
const ca = 4356 / 361;
const cb = 35442 / 1805;
const cc = 16061 / 1805;
const bounceOut = (p2) => {
  if (p2 === 1 || p2 === 0)
    return p2;
  const p22 = p2 * p2;
  return p2 < BOUNCE_FIRST_THRESHOLD ? 7.5625 * p22 : p2 < BOUNCE_SECOND_THRESHOLD ? 9.075 * p22 - 9.9 * p2 + 3.4 : p2 < BOUNCE_THIRD_THRESHOLD ? ca * p22 - cb * p2 + cc : 10.8 * p2 * p2 - 20.52 * p2 + 10.72;
};
const bounceIn = reverseEasing(bounceOut);
const bounceInOut = (p2) => p2 < 0.5 ? 0.5 * (1 - bounceOut(1 - p2 * 2)) : 0.5 * bounceOut(p2 * 2 - 1) + 0.5;
function defaultEasing(values, easing) {
  return values.map(() => easing || easeInOut).splice(0, values.length - 1);
}
function defaultOffset(values) {
  const numValues = values.length;
  return values.map((_value, i2) => i2 !== 0 ? i2 / (numValues - 1) : 0);
}
function convertOffsetToTimes(offset2, duration) {
  return offset2.map((o2) => o2 * duration);
}
function keyframes$1({ from = 0, to = 1, ease, offset: offset2, duration = 300 }) {
  const state2 = { done: false, value: from };
  const values = Array.isArray(to) ? to : [from, to];
  const times2 = convertOffsetToTimes(offset2 && offset2.length === values.length ? offset2 : defaultOffset(values), duration);
  function createInterpolator() {
    return interpolate(times2, values, {
      ease: Array.isArray(ease) ? ease : defaultEasing(values, ease)
    });
  }
  let interpolator = createInterpolator();
  return {
    next: (t2) => {
      state2.value = interpolator(t2);
      state2.done = t2 >= duration;
      return state2;
    },
    flipTarget: () => {
      values.reverse();
      interpolator = createInterpolator();
    }
  };
}
function decay({ velocity = 0, from = 0, power = 0.8, timeConstant = 350, restDelta = 0.5, modifyTarget }) {
  const state2 = { done: false, value: from };
  let amplitude = power * velocity;
  const ideal = from + amplitude;
  const target = modifyTarget === void 0 ? ideal : modifyTarget(ideal);
  if (target !== ideal)
    amplitude = target - from;
  return {
    next: (t2) => {
      const delta = -amplitude * Math.exp(-t2 / timeConstant);
      state2.done = !(delta > restDelta || delta < -restDelta);
      state2.value = state2.done ? target : target + delta;
      return state2;
    },
    flipTarget: () => {
    }
  };
}
const types = { keyframes: keyframes$1, spring, decay };
function detectAnimationFromOptions(config) {
  if (Array.isArray(config.to)) {
    return keyframes$1;
  } else if (types[config.type]) {
    return types[config.type];
  }
  const keys = new Set(Object.keys(config));
  if (keys.has("ease") || keys.has("duration") && !keys.has("dampingRatio")) {
    return keyframes$1;
  } else if (keys.has("dampingRatio") || keys.has("stiffness") || keys.has("mass") || keys.has("damping") || keys.has("restSpeed") || keys.has("restDelta")) {
    return spring;
  }
  return keyframes$1;
}
function loopElapsed(elapsed, duration, delay = 0) {
  return elapsed - duration - delay;
}
function reverseElapsed(elapsed, duration, delay = 0, isForwardPlayback = true) {
  return isForwardPlayback ? loopElapsed(duration + -elapsed, duration, delay) : duration - (elapsed - duration) + delay;
}
function hasRepeatDelayElapsed(elapsed, duration, delay, isForwardPlayback) {
  return isForwardPlayback ? elapsed >= duration + delay : elapsed <= -delay;
}
const framesync = (update) => {
  const passTimestamp = ({ delta }) => update(delta);
  return {
    start: () => sync.update(passTimestamp, true),
    stop: () => cancelSync.update(passTimestamp)
  };
};
function animate(_a2) {
  var _b, _c;
  var { from, autoplay = true, driver = framesync, elapsed = 0, repeat: repeatMax = 0, repeatType = "loop", repeatDelay = 0, onPlay, onStop, onComplete, onRepeat, onUpdate } = _a2, options = __rest(_a2, ["from", "autoplay", "driver", "elapsed", "repeat", "repeatType", "repeatDelay", "onPlay", "onStop", "onComplete", "onRepeat", "onUpdate"]);
  let { to } = options;
  let driverControls;
  let repeatCount = 0;
  let computedDuration = options.duration;
  let latest;
  let isComplete = false;
  let isForwardPlayback = true;
  let interpolateFromNumber;
  const animator = detectAnimationFromOptions(options);
  if ((_c = (_b = animator).needsInterpolation) === null || _c === void 0 ? void 0 : _c.call(_b, from, to)) {
    interpolateFromNumber = interpolate([0, 100], [from, to], {
      clamp: false
    });
    from = 0;
    to = 100;
  }
  const animation = animator(Object.assign(Object.assign({}, options), { from, to }));
  function repeat() {
    repeatCount++;
    if (repeatType === "reverse") {
      isForwardPlayback = repeatCount % 2 === 0;
      elapsed = reverseElapsed(elapsed, computedDuration, repeatDelay, isForwardPlayback);
    } else {
      elapsed = loopElapsed(elapsed, computedDuration, repeatDelay);
      if (repeatType === "mirror")
        animation.flipTarget();
    }
    isComplete = false;
    onRepeat && onRepeat();
  }
  function complete() {
    driverControls.stop();
    onComplete && onComplete();
  }
  function update(delta) {
    if (!isForwardPlayback)
      delta = -delta;
    elapsed += delta;
    if (!isComplete) {
      const state2 = animation.next(Math.max(0, elapsed));
      latest = state2.value;
      if (interpolateFromNumber)
        latest = interpolateFromNumber(latest);
      isComplete = isForwardPlayback ? state2.done : elapsed <= 0;
    }
    onUpdate === null || onUpdate === void 0 ? void 0 : onUpdate(latest);
    if (isComplete) {
      if (repeatCount === 0)
        computedDuration !== null && computedDuration !== void 0 ? computedDuration : computedDuration = elapsed;
      if (repeatCount < repeatMax) {
        hasRepeatDelayElapsed(elapsed, computedDuration, repeatDelay, isForwardPlayback) && repeat();
      } else {
        complete();
      }
    }
  }
  function play() {
    onPlay === null || onPlay === void 0 ? void 0 : onPlay();
    driverControls = driver(update);
    driverControls.start();
  }
  autoplay && play();
  return {
    stop: () => {
      onStop === null || onStop === void 0 ? void 0 : onStop();
      driverControls.stop();
    }
  };
}
function velocityPerSecond(velocity, frameDuration) {
  return frameDuration ? velocity * (1e3 / frameDuration) : 0;
}
function inertia({ from = 0, velocity = 0, min, max, power = 0.8, timeConstant = 750, bounceStiffness = 500, bounceDamping = 10, restDelta = 1, modifyTarget, driver, onUpdate, onComplete, onStop }) {
  let currentAnimation;
  function isOutOfBounds(v2) {
    return min !== void 0 && v2 < min || max !== void 0 && v2 > max;
  }
  function boundaryNearest(v2) {
    if (min === void 0)
      return max;
    if (max === void 0)
      return min;
    return Math.abs(min - v2) < Math.abs(max - v2) ? min : max;
  }
  function startAnimation2(options) {
    currentAnimation === null || currentAnimation === void 0 ? void 0 : currentAnimation.stop();
    currentAnimation = animate(Object.assign(Object.assign({}, options), {
      driver,
      onUpdate: (v2) => {
        var _a2;
        onUpdate === null || onUpdate === void 0 ? void 0 : onUpdate(v2);
        (_a2 = options.onUpdate) === null || _a2 === void 0 ? void 0 : _a2.call(options, v2);
      },
      onComplete,
      onStop
    }));
  }
  function startSpring(options) {
    startAnimation2(Object.assign({ type: "spring", stiffness: bounceStiffness, damping: bounceDamping, restDelta }, options));
  }
  if (isOutOfBounds(from)) {
    startSpring({ from, velocity, to: boundaryNearest(from) });
  } else {
    let target = power * velocity + from;
    if (typeof modifyTarget !== "undefined")
      target = modifyTarget(target);
    const boundary = boundaryNearest(target);
    const heading = boundary === min ? -1 : 1;
    let prev;
    let current;
    const checkBoundary2 = (v2) => {
      prev = current;
      current = v2;
      velocity = velocityPerSecond(v2 - prev, getFrameData().delta);
      if (heading === 1 && v2 > boundary || heading === -1 && v2 < boundary) {
        startSpring({ from: v2, to: boundary, velocity });
      }
    };
    startAnimation2({
      type: "decay",
      from,
      velocity,
      timeConstant,
      power,
      restDelta,
      modifyTarget,
      onUpdate: isOutOfBounds(target) ? checkBoundary2 : void 0
    });
  }
  return {
    stop: () => currentAnimation === null || currentAnimation === void 0 ? void 0 : currentAnimation.stop()
  };
}
const a$3 = (a1, a2) => 1 - 3 * a2 + 3 * a1;
const b$3 = (a1, a2) => 3 * a2 - 6 * a1;
const c$4 = (a1) => 3 * a1;
const calcBezier = (t2, a1, a2) => ((a$3(a1, a2) * t2 + b$3(a1, a2)) * t2 + c$4(a1)) * t2;
const getSlope = (t2, a1, a2) => 3 * a$3(a1, a2) * t2 * t2 + 2 * b$3(a1, a2) * t2 + c$4(a1);
const subdivisionPrecision = 1e-7;
const subdivisionMaxIterations = 10;
function binarySubdivide(aX, aA, aB, mX1, mX2) {
  let currentX;
  let currentT;
  let i2 = 0;
  do {
    currentT = aA + (aB - aA) / 2;
    currentX = calcBezier(currentT, mX1, mX2) - aX;
    if (currentX > 0) {
      aB = currentT;
    } else {
      aA = currentT;
    }
  } while (Math.abs(currentX) > subdivisionPrecision && ++i2 < subdivisionMaxIterations);
  return currentT;
}
const newtonIterations = 8;
const newtonMinSlope = 1e-3;
function newtonRaphsonIterate(aX, aGuessT, mX1, mX2) {
  for (let i2 = 0; i2 < newtonIterations; ++i2) {
    const currentSlope = getSlope(aGuessT, mX1, mX2);
    if (currentSlope === 0) {
      return aGuessT;
    }
    const currentX = calcBezier(aGuessT, mX1, mX2) - aX;
    aGuessT -= currentX / currentSlope;
  }
  return aGuessT;
}
const kSplineTableSize = 11;
const kSampleStepSize = 1 / (kSplineTableSize - 1);
function cubicBezier(mX1, mY1, mX2, mY2) {
  if (mX1 === mY1 && mX2 === mY2)
    return linear;
  const sampleValues = new Float32Array(kSplineTableSize);
  for (let i2 = 0; i2 < kSplineTableSize; ++i2) {
    sampleValues[i2] = calcBezier(i2 * kSampleStepSize, mX1, mX2);
  }
  function getTForX(aX) {
    let intervalStart = 0;
    let currentSample = 1;
    const lastSample = kSplineTableSize - 1;
    for (; currentSample !== lastSample && sampleValues[currentSample] <= aX; ++currentSample) {
      intervalStart += kSampleStepSize;
    }
    --currentSample;
    const dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]);
    const guessForT = intervalStart + dist * kSampleStepSize;
    const initialSlope = getSlope(guessForT, mX1, mX2);
    if (initialSlope >= newtonMinSlope) {
      return newtonRaphsonIterate(aX, guessForT, mX1, mX2);
    } else if (initialSlope === 0) {
      return guessForT;
    } else {
      return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2);
    }
  }
  return (t2) => t2 === 0 || t2 === 1 ? t2 : calcBezier(getTForX(t2), mY1, mY2);
}
function addUniqueItem(arr, item) {
  arr.indexOf(item) === -1 && arr.push(item);
}
function removeItem(arr, item) {
  var index2 = arr.indexOf(item);
  index2 > -1 && arr.splice(index2, 1);
}
var SubscriptionManager = function() {
  function SubscriptionManager2() {
    this.subscriptions = [];
  }
  SubscriptionManager2.prototype.add = function(handler) {
    var _this = this;
    addUniqueItem(this.subscriptions, handler);
    return function() {
      return removeItem(_this.subscriptions, handler);
    };
  };
  SubscriptionManager2.prototype.notify = function(a2, b2, c2) {
    var numSubscriptions = this.subscriptions.length;
    if (!numSubscriptions)
      return;
    if (numSubscriptions === 1) {
      this.subscriptions[0](a2, b2, c2);
    } else {
      for (var i2 = 0; i2 < numSubscriptions; i2++) {
        var handler = this.subscriptions[i2];
        handler && handler(a2, b2, c2);
      }
    }
  };
  SubscriptionManager2.prototype.getSize = function() {
    return this.subscriptions.length;
  };
  SubscriptionManager2.prototype.clear = function() {
    this.subscriptions.length = 0;
  };
  return SubscriptionManager2;
}();
var isFloat = function(value) {
  return !isNaN(parseFloat(value));
};
var MotionValue = function() {
  function MotionValue2(init2) {
    var _this = this;
    this.timeDelta = 0;
    this.lastUpdated = 0;
    this.updateSubscribers = new SubscriptionManager();
    this.velocityUpdateSubscribers = new SubscriptionManager();
    this.renderSubscribers = new SubscriptionManager();
    this.canTrackVelocity = false;
    this.updateAndNotify = function(v2, render) {
      if (render === void 0) {
        render = true;
      }
      _this.prev = _this.current;
      _this.current = v2;
      var _a2 = getFrameData(), delta = _a2.delta, timestamp = _a2.timestamp;
      if (_this.lastUpdated !== timestamp) {
        _this.timeDelta = delta;
        _this.lastUpdated = timestamp;
        sync.postRender(_this.scheduleVelocityCheck);
      }
      if (_this.prev !== _this.current) {
        _this.updateSubscribers.notify(_this.current);
      }
      if (_this.velocityUpdateSubscribers.getSize()) {
        _this.velocityUpdateSubscribers.notify(_this.getVelocity());
      }
      if (render) {
        _this.renderSubscribers.notify(_this.current);
      }
    };
    this.scheduleVelocityCheck = function() {
      return sync.postRender(_this.velocityCheck);
    };
    this.velocityCheck = function(_a2) {
      var timestamp = _a2.timestamp;
      if (timestamp !== _this.lastUpdated) {
        _this.prev = _this.current;
        _this.velocityUpdateSubscribers.notify(_this.getVelocity());
      }
    };
    this.hasAnimated = false;
    this.prev = this.current = init2;
    this.canTrackVelocity = isFloat(this.current);
  }
  MotionValue2.prototype.onChange = function(subscription) {
    return this.updateSubscribers.add(subscription);
  };
  MotionValue2.prototype.clearListeners = function() {
    this.updateSubscribers.clear();
  };
  MotionValue2.prototype.onRenderRequest = function(subscription) {
    subscription(this.get());
    return this.renderSubscribers.add(subscription);
  };
  MotionValue2.prototype.attach = function(passiveEffect) {
    this.passiveEffect = passiveEffect;
  };
  MotionValue2.prototype.set = function(v2, render) {
    if (render === void 0) {
      render = true;
    }
    if (!render || !this.passiveEffect) {
      this.updateAndNotify(v2, render);
    } else {
      this.passiveEffect(v2, this.updateAndNotify);
    }
  };
  MotionValue2.prototype.get = function() {
    return this.current;
  };
  MotionValue2.prototype.getPrevious = function() {
    return this.prev;
  };
  MotionValue2.prototype.getVelocity = function() {
    return this.canTrackVelocity ? velocityPerSecond(parseFloat(this.current) - parseFloat(this.prev), this.timeDelta) : 0;
  };
  MotionValue2.prototype.start = function(animation) {
    var _this = this;
    this.stop();
    return new Promise(function(resolve) {
      _this.hasAnimated = true;
      _this.stopAnimation = animation(resolve);
    }).then(function() {
      return _this.clearAnimation();
    });
  };
  MotionValue2.prototype.stop = function() {
    if (this.stopAnimation)
      this.stopAnimation();
    this.clearAnimation();
  };
  MotionValue2.prototype.isAnimating = function() {
    return !!this.stopAnimation;
  };
  MotionValue2.prototype.clearAnimation = function() {
    this.stopAnimation = null;
  };
  MotionValue2.prototype.destroy = function() {
    this.updateSubscribers.clear();
    this.renderSubscribers.clear();
    this.stop();
  };
  return MotionValue2;
}();
function motionValue(init2) {
  return new MotionValue(init2);
}
var isMotionValue = function(value) {
  return Boolean(value !== null && typeof value === "object" && value.getVelocity);
};
var secondsToMilliseconds = function(seconds) {
  return seconds * 1e3;
};
var easingLookup = {
  linear,
  easeIn,
  easeInOut,
  easeOut,
  circIn,
  circInOut,
  circOut,
  backIn,
  backInOut,
  backOut,
  anticipate,
  bounceIn,
  bounceInOut,
  bounceOut
};
var easingDefinitionToFunction = function(definition) {
  if (Array.isArray(definition)) {
    invariant(definition.length === 4);
    var _a2 = __read(definition, 4), x1 = _a2[0], y1 = _a2[1], x2 = _a2[2], y2 = _a2[3];
    return cubicBezier(x1, y1, x2, y2);
  } else if (typeof definition === "string") {
    return easingLookup[definition];
  }
  return definition;
};
var isEasingArray = function(ease) {
  return Array.isArray(ease) && typeof ease[0] !== "number";
};
var isAnimatable = function(key, value) {
  if (key === "zIndex")
    return false;
  if (typeof value === "number" || Array.isArray(value))
    return true;
  if (typeof value === "string" && complex.test(value) && !value.startsWith("url(")) {
    return true;
  }
  return false;
};
var isKeyframesTarget = function(v2) {
  return Array.isArray(v2);
};
var underDampedSpring = function() {
  return {
    type: "spring",
    stiffness: 500,
    damping: 25,
    restSpeed: 10
  };
};
var criticallyDampedSpring = function(to) {
  return {
    type: "spring",
    stiffness: 550,
    damping: to === 0 ? 2 * Math.sqrt(550) : 30,
    restSpeed: 10
  };
};
var linearTween = function() {
  return {
    type: "keyframes",
    ease: "linear",
    duration: 0.3
  };
};
var keyframes = function(values) {
  return {
    type: "keyframes",
    duration: 0.8,
    values
  };
};
var defaultTransitions = {
  x: underDampedSpring,
  y: underDampedSpring,
  z: underDampedSpring,
  rotate: underDampedSpring,
  rotateX: underDampedSpring,
  rotateY: underDampedSpring,
  rotateZ: underDampedSpring,
  scaleX: criticallyDampedSpring,
  scaleY: criticallyDampedSpring,
  scale: criticallyDampedSpring,
  opacity: linearTween,
  backgroundColor: linearTween,
  color: linearTween,
  default: criticallyDampedSpring
};
var getDefaultTransition = function(valueKey, to) {
  var transitionFactory;
  if (isKeyframesTarget(to)) {
    transitionFactory = keyframes;
  } else {
    transitionFactory = defaultTransitions[valueKey] || defaultTransitions.default;
  }
  return __assign({ to }, transitionFactory(to));
};
var int = __assign(__assign({}, number), { transform: Math.round });
var numberValueTypes = {
  borderWidth: px,
  borderTopWidth: px,
  borderRightWidth: px,
  borderBottomWidth: px,
  borderLeftWidth: px,
  borderRadius: px,
  radius: px,
  borderTopLeftRadius: px,
  borderTopRightRadius: px,
  borderBottomRightRadius: px,
  borderBottomLeftRadius: px,
  width: px,
  maxWidth: px,
  height: px,
  maxHeight: px,
  size: px,
  top: px,
  right: px,
  bottom: px,
  left: px,
  padding: px,
  paddingTop: px,
  paddingRight: px,
  paddingBottom: px,
  paddingLeft: px,
  margin: px,
  marginTop: px,
  marginRight: px,
  marginBottom: px,
  marginLeft: px,
  rotate: degrees,
  rotateX: degrees,
  rotateY: degrees,
  rotateZ: degrees,
  scale,
  scaleX: scale,
  scaleY: scale,
  scaleZ: scale,
  skew: degrees,
  skewX: degrees,
  skewY: degrees,
  distance: px,
  translateX: px,
  translateY: px,
  translateZ: px,
  x: px,
  y: px,
  z: px,
  perspective: px,
  transformPerspective: px,
  opacity: alpha,
  originX: progressPercentage,
  originY: progressPercentage,
  originZ: px,
  zIndex: int,
  fillOpacity: alpha,
  strokeOpacity: alpha,
  numOctaves: int
};
var defaultValueTypes = __assign(__assign({}, numberValueTypes), {
  color: color$1,
  backgroundColor: color$1,
  outlineColor: color$1,
  fill: color$1,
  stroke: color$1,
  borderColor: color$1,
  borderTopColor: color$1,
  borderRightColor: color$1,
  borderBottomColor: color$1,
  borderLeftColor: color$1,
  filter,
  WebkitFilter: filter
});
var getDefaultValueType = function(key) {
  return defaultValueTypes[key];
};
function getAnimatableNone(key, value) {
  var _a2;
  var defaultValueType = getDefaultValueType(key);
  if (defaultValueType !== filter)
    defaultValueType = complex;
  return (_a2 = defaultValueType.getAnimatableNone) === null || _a2 === void 0 ? void 0 : _a2.call(defaultValueType, value);
}
var instantAnimationState = {
  current: false
};
var isCustomValue = function(v2) {
  return Boolean(v2 && typeof v2 === "object" && v2.mix && v2.toValue);
};
var resolveFinalValueInKeyframes = function(v2) {
  return isKeyframesTarget(v2) ? v2[v2.length - 1] || 0 : v2;
};
function isTransitionDefined(_a2) {
  _a2.when;
  _a2.delay;
  _a2.delayChildren;
  _a2.staggerChildren;
  _a2.staggerDirection;
  _a2.repeat;
  _a2.repeatType;
  _a2.repeatDelay;
  _a2.from;
  var transition = __rest(_a2, ["when", "delay", "delayChildren", "staggerChildren", "staggerDirection", "repeat", "repeatType", "repeatDelay", "from"]);
  return !!Object.keys(transition).length;
}
function convertTransitionToAnimationOptions(_a2) {
  var ease = _a2.ease, times2 = _a2.times, yoyo = _a2.yoyo, flip = _a2.flip, loop = _a2.loop, transition = __rest(_a2, ["ease", "times", "yoyo", "flip", "loop"]);
  var options = __assign({}, transition);
  if (times2)
    options["offset"] = times2;
  if (transition.duration)
    options["duration"] = secondsToMilliseconds(transition.duration);
  if (transition.repeatDelay)
    options.repeatDelay = secondsToMilliseconds(transition.repeatDelay);
  if (ease) {
    options["ease"] = isEasingArray(ease) ? ease.map(easingDefinitionToFunction) : easingDefinitionToFunction(ease);
  }
  if (transition.type === "tween")
    options.type = "keyframes";
  if (yoyo || loop || flip) {
    if (yoyo) {
      options.repeatType = "reverse";
    } else if (loop) {
      options.repeatType = "loop";
    } else if (flip) {
      options.repeatType = "mirror";
    }
    options.repeat = loop || yoyo || flip || transition.repeat;
  }
  if (transition.type !== "spring")
    options.type = "keyframes";
  return options;
}
function getDelayFromTransition(transition, key) {
  var _a2, _b;
  var valueTransition = getValueTransition(transition, key) || {};
  return (_b = (_a2 = valueTransition.delay) !== null && _a2 !== void 0 ? _a2 : transition.delay) !== null && _b !== void 0 ? _b : 0;
}
function hydrateKeyframes(options) {
  if (Array.isArray(options.to) && options.to[0] === null) {
    options.to = __spreadArray([], __read(options.to), false);
    options.to[0] = options.from;
  }
  return options;
}
function getPopmotionAnimationOptions(transition, options, key) {
  var _a2;
  if (Array.isArray(options.to)) {
    (_a2 = transition.duration) !== null && _a2 !== void 0 ? _a2 : transition.duration = 0.8;
  }
  hydrateKeyframes(options);
  if (!isTransitionDefined(transition)) {
    transition = __assign(__assign({}, transition), getDefaultTransition(key, options.to));
  }
  return __assign(__assign({}, options), convertTransitionToAnimationOptions(transition));
}
function getAnimation(key, value, target, transition, onComplete) {
  var _a2;
  var valueTransition = getValueTransition(transition, key);
  var origin = (_a2 = valueTransition.from) !== null && _a2 !== void 0 ? _a2 : value.get();
  var isTargetAnimatable = isAnimatable(key, target);
  if (origin === "none" && isTargetAnimatable && typeof target === "string") {
    origin = getAnimatableNone(key, target);
  } else if (isZero(origin) && typeof target === "string") {
    origin = getZeroUnit(target);
  } else if (!Array.isArray(target) && isZero(target) && typeof origin === "string") {
    target = getZeroUnit(origin);
  }
  var isOriginAnimatable = isAnimatable(key, origin);
  function start() {
    var options = {
      from: origin,
      to: target,
      velocity: value.getVelocity(),
      onComplete,
      onUpdate: function(v2) {
        return value.set(v2);
      }
    };
    return valueTransition.type === "inertia" || valueTransition.type === "decay" ? inertia(__assign(__assign({}, options), valueTransition)) : animate(__assign(__assign({}, getPopmotionAnimationOptions(valueTransition, options, key)), { onUpdate: function(v2) {
      var _a3;
      options.onUpdate(v2);
      (_a3 = valueTransition.onUpdate) === null || _a3 === void 0 ? void 0 : _a3.call(valueTransition, v2);
    }, onComplete: function() {
      var _a3;
      options.onComplete();
      (_a3 = valueTransition.onComplete) === null || _a3 === void 0 ? void 0 : _a3.call(valueTransition);
    } }));
  }
  function set() {
    var _a3, _b;
    var finalTarget = resolveFinalValueInKeyframes(target);
    value.set(finalTarget);
    onComplete();
    (_a3 = valueTransition === null || valueTransition === void 0 ? void 0 : valueTransition.onUpdate) === null || _a3 === void 0 ? void 0 : _a3.call(valueTransition, finalTarget);
    (_b = valueTransition === null || valueTransition === void 0 ? void 0 : valueTransition.onComplete) === null || _b === void 0 ? void 0 : _b.call(valueTransition);
    return { stop: function() {
    } };
  }
  return !isOriginAnimatable || !isTargetAnimatable || valueTransition.type === false ? set : start;
}
function isZero(value) {
  return value === 0 || typeof value === "string" && parseFloat(value) === 0 && value.indexOf(" ") === -1;
}
function getZeroUnit(potentialUnitType) {
  return typeof potentialUnitType === "number" ? 0 : getAnimatableNone("", potentialUnitType);
}
function getValueTransition(transition, key) {
  return transition[key] || transition["default"] || transition;
}
function startAnimation(key, value, target, transition) {
  if (transition === void 0) {
    transition = {};
  }
  if (instantAnimationState.current) {
    transition = { type: false };
  }
  return value.start(function(onComplete) {
    var delayTimer;
    var controls2;
    var animation = getAnimation(key, value, target, transition, onComplete);
    var delay = getDelayFromTransition(transition, key);
    var start = function() {
      return controls2 = animation();
    };
    if (delay) {
      delayTimer = setTimeout(start, secondsToMilliseconds(delay));
    } else {
      start();
    }
    return function() {
      clearTimeout(delayTimer);
      controls2 === null || controls2 === void 0 ? void 0 : controls2.stop();
    };
  });
}
var scaleCorrectors = {};
var transformAxes = ["", "X", "Y", "Z"];
var order = ["translate", "scale", "rotate", "skew"];
var transformProps = ["transformPerspective", "x", "y", "z"];
order.forEach(function(operationKey) {
  return transformAxes.forEach(function(axesKey) {
    return transformProps.push(operationKey + axesKey);
  });
});
function sortTransformProps(a2, b2) {
  return transformProps.indexOf(a2) - transformProps.indexOf(b2);
}
var transformPropSet = new Set(transformProps);
function isTransformProp(key) {
  return transformPropSet.has(key);
}
var transformOriginProps = /* @__PURE__ */ new Set(["originX", "originY", "originZ"]);
function isTransformOriginProp(key) {
  return transformOriginProps.has(key);
}
function resolveMotionValue(value) {
  var unwrappedValue = isMotionValue(value) ? value.get() : value;
  return isCustomValue(unwrappedValue) ? unwrappedValue.toValue() : unwrappedValue;
}
var globalProjectionState = {
  hasAnimatedSinceResize: true,
  hasEverUpdated: false
};
var id = 1;
function useProjectionId() {
  return useConstant(function() {
    if (globalProjectionState.hasEverUpdated) {
      return id++;
    }
  });
}
var LayoutGroupContext = createContext({});
var SwitchLayoutGroupContext = createContext({});
function useProjection(projectionId, _a2, visualElement2, ProjectionNodeConstructor) {
  var _b;
  var layoutId = _a2.layoutId, layout = _a2.layout, drag = _a2.drag, dragConstraints = _a2.dragConstraints, layoutScroll = _a2.layoutScroll;
  var initialPromotionConfig = useContext(SwitchLayoutGroupContext);
  if (!ProjectionNodeConstructor || !visualElement2 || (visualElement2 === null || visualElement2 === void 0 ? void 0 : visualElement2.projection)) {
    return;
  }
  visualElement2.projection = new ProjectionNodeConstructor(projectionId, visualElement2.getLatestValues(), (_b = visualElement2.parent) === null || _b === void 0 ? void 0 : _b.projection);
  visualElement2.projection.setOptions({
    layoutId,
    layout,
    alwaysMeasureLayout: Boolean(drag) || dragConstraints && isRefObject(dragConstraints),
    visualElement: visualElement2,
    scheduleRender: function() {
      return visualElement2.scheduleRender();
    },
    animationType: typeof layout === "string" ? layout : "both",
    initialPromotionConfig,
    layoutScroll
  });
}
var VisualElementHandler = function(_super) {
  __extends(VisualElementHandler2, _super);
  function VisualElementHandler2() {
    return _super !== null && _super.apply(this, arguments) || this;
  }
  VisualElementHandler2.prototype.getSnapshotBeforeUpdate = function() {
    this.updateProps();
    return null;
  };
  VisualElementHandler2.prototype.componentDidUpdate = function() {
  };
  VisualElementHandler2.prototype.updateProps = function() {
    var _a2 = this.props, visualElement2 = _a2.visualElement, props2 = _a2.props;
    if (visualElement2)
      visualElement2.setProps(props2);
  };
  VisualElementHandler2.prototype.render = function() {
    return this.props.children;
  };
  return VisualElementHandler2;
}(React__default.Component);
function createMotionComponent(_a2) {
  var preloadedFeatures = _a2.preloadedFeatures, createVisualElement = _a2.createVisualElement, projectionNodeConstructor = _a2.projectionNodeConstructor, useRender = _a2.useRender, useVisualState = _a2.useVisualState, Component = _a2.Component;
  preloadedFeatures && loadFeatures(preloadedFeatures);
  function MotionComponent(props2, externalRef) {
    var layoutId = useLayoutId(props2);
    props2 = __assign(__assign({}, props2), { layoutId });
    var config = useContext(MotionConfigContext);
    var features = null;
    var context = useCreateMotionContext(props2);
    var projectionId = config.isStatic ? void 0 : useProjectionId();
    var visualState = useVisualState(props2, config.isStatic);
    if (!config.isStatic && isBrowser$1) {
      context.visualElement = useVisualElement(Component, visualState, __assign(__assign({}, config), props2), createVisualElement);
      useProjection(projectionId, props2, context.visualElement, projectionNodeConstructor || featureDefinitions.projectionNodeConstructor);
      features = useFeatures(props2, context.visualElement);
    }
    return React__default.createElement(VisualElementHandler, { visualElement: context.visualElement, props: __assign(__assign({}, config), props2) }, features, React__default.createElement(MotionContext.Provider, { value: context }, useRender(Component, props2, projectionId, useMotionRef(visualState, context.visualElement, externalRef), visualState, config.isStatic, context.visualElement)));
  }
  return forwardRef(MotionComponent);
}
function useLayoutId(_a2) {
  var _b;
  var layoutId = _a2.layoutId;
  var layoutGroupId = (_b = useContext(LayoutGroupContext)) === null || _b === void 0 ? void 0 : _b.id;
  return layoutGroupId && layoutId !== void 0 ? layoutGroupId + "-" + layoutId : layoutId;
}
function createMotionProxy(createConfig) {
  function custom(Component, customMotionComponentConfig) {
    if (customMotionComponentConfig === void 0) {
      customMotionComponentConfig = {};
    }
    return createMotionComponent(createConfig(Component, customMotionComponentConfig));
  }
  if (typeof Proxy === "undefined") {
    return custom;
  }
  var componentCache = /* @__PURE__ */ new Map();
  return new Proxy(custom, {
    get: function(_target, key) {
      if (!componentCache.has(key)) {
        componentCache.set(key, custom(key));
      }
      return componentCache.get(key);
    }
  });
}
var lowercaseSVGElements = [
  "animate",
  "circle",
  "defs",
  "desc",
  "ellipse",
  "g",
  "image",
  "line",
  "filter",
  "marker",
  "mask",
  "metadata",
  "path",
  "pattern",
  "polygon",
  "polyline",
  "rect",
  "stop",
  "svg",
  "switch",
  "symbol",
  "text",
  "tspan",
  "use",
  "view"
];
function isSVGComponent(Component) {
  if (typeof Component !== "string" || Component.includes("-")) {
    return false;
  } else if (lowercaseSVGElements.indexOf(Component) > -1 || /[A-Z]/.test(Component)) {
    return true;
  }
  return false;
}
function isForcedMotionValue(key, _a2) {
  var layout = _a2.layout, layoutId = _a2.layoutId;
  return isTransformProp(key) || isTransformOriginProp(key) || (layout || layoutId !== void 0) && (!!scaleCorrectors[key] || key === "opacity");
}
var translateAlias = {
  x: "translateX",
  y: "translateY",
  z: "translateZ",
  transformPerspective: "perspective"
};
function buildTransform(_a2, _b, transformIsDefault, transformTemplate) {
  var transform2 = _a2.transform, transformKeys2 = _a2.transformKeys;
  var _c = _b.enableHardwareAcceleration, enableHardwareAcceleration = _c === void 0 ? true : _c, _d = _b.allowTransformNone, allowTransformNone = _d === void 0 ? true : _d;
  var transformString = "";
  transformKeys2.sort(sortTransformProps);
  var transformHasZ = false;
  var numTransformKeys = transformKeys2.length;
  for (var i2 = 0; i2 < numTransformKeys; i2++) {
    var key = transformKeys2[i2];
    transformString += "".concat(translateAlias[key] || key, "(").concat(transform2[key], ") ");
    if (key === "z")
      transformHasZ = true;
  }
  if (!transformHasZ && enableHardwareAcceleration) {
    transformString += "translateZ(0)";
  } else {
    transformString = transformString.trim();
  }
  if (transformTemplate) {
    transformString = transformTemplate(transform2, transformIsDefault ? "" : transformString);
  } else if (allowTransformNone && transformIsDefault) {
    transformString = "none";
  }
  return transformString;
}
function buildTransformOrigin(_a2) {
  var _b = _a2.originX, originX = _b === void 0 ? "50%" : _b, _c = _a2.originY, originY = _c === void 0 ? "50%" : _c, _d = _a2.originZ, originZ = _d === void 0 ? 0 : _d;
  return "".concat(originX, " ").concat(originY, " ").concat(originZ);
}
function isCSSVariable$1(key) {
  return key.startsWith("--");
}
var getValueAsType = function(value, type) {
  return type && typeof value === "number" ? type.transform(value) : value;
};
function buildHTMLStyles(state2, latestValues, options, transformTemplate) {
  var _a2;
  var style2 = state2.style, vars = state2.vars, transform2 = state2.transform, transformKeys2 = state2.transformKeys, transformOrigin = state2.transformOrigin;
  transformKeys2.length = 0;
  var hasTransform = false;
  var hasTransformOrigin = false;
  var transformIsNone = true;
  for (var key in latestValues) {
    var value = latestValues[key];
    if (isCSSVariable$1(key)) {
      vars[key] = value;
      continue;
    }
    var valueType = numberValueTypes[key];
    var valueAsType = getValueAsType(value, valueType);
    if (isTransformProp(key)) {
      hasTransform = true;
      transform2[key] = valueAsType;
      transformKeys2.push(key);
      if (!transformIsNone)
        continue;
      if (value !== ((_a2 = valueType.default) !== null && _a2 !== void 0 ? _a2 : 0))
        transformIsNone = false;
    } else if (isTransformOriginProp(key)) {
      transformOrigin[key] = valueAsType;
      hasTransformOrigin = true;
    } else {
      style2[key] = valueAsType;
    }
  }
  if (hasTransform) {
    style2.transform = buildTransform(state2, options, transformIsNone, transformTemplate);
  } else if (transformTemplate) {
    style2.transform = transformTemplate({}, "");
  } else if (!latestValues.transform && style2.transform) {
    style2.transform = "none";
  }
  if (hasTransformOrigin) {
    style2.transformOrigin = buildTransformOrigin(transformOrigin);
  }
}
var createHtmlRenderState = function() {
  return {
    style: {},
    transform: {},
    transformKeys: [],
    transformOrigin: {},
    vars: {}
  };
};
function copyRawValuesOnly(target, source, props2) {
  for (var key in source) {
    if (!isMotionValue(source[key]) && !isForcedMotionValue(key, props2)) {
      target[key] = source[key];
    }
  }
}
function useInitialMotionValues(_a2, visualState, isStatic) {
  var transformTemplate = _a2.transformTemplate;
  return useMemo(function() {
    var state2 = createHtmlRenderState();
    buildHTMLStyles(state2, visualState, { enableHardwareAcceleration: !isStatic }, transformTemplate);
    var vars = state2.vars, style2 = state2.style;
    return __assign(__assign({}, vars), style2);
  }, [visualState]);
}
function useStyle(props2, visualState, isStatic) {
  var styleProp = props2.style || {};
  var style2 = {};
  copyRawValuesOnly(style2, styleProp, props2);
  Object.assign(style2, useInitialMotionValues(props2, visualState, isStatic));
  if (props2.transformValues) {
    style2 = props2.transformValues(style2);
  }
  return style2;
}
function useHTMLProps(props2, visualState, isStatic) {
  var htmlProps = {};
  var style2 = useStyle(props2, visualState, isStatic);
  if (Boolean(props2.drag) && props2.dragListener !== false) {
    htmlProps.draggable = false;
    style2.userSelect = style2.WebkitUserSelect = style2.WebkitTouchCallout = "none";
    style2.touchAction = props2.drag === true ? "none" : "pan-".concat(props2.drag === "x" ? "y" : "x");
  }
  htmlProps.style = style2;
  return htmlProps;
}
var validMotionProps = /* @__PURE__ */ new Set([
  "initial",
  "animate",
  "exit",
  "style",
  "variants",
  "transition",
  "transformTemplate",
  "transformValues",
  "custom",
  "inherit",
  "layout",
  "layoutId",
  "layoutDependency",
  "onLayoutAnimationComplete",
  "onLayoutMeasure",
  "onBeforeLayoutMeasure",
  "onAnimationStart",
  "onAnimationComplete",
  "onUpdate",
  "onDragStart",
  "onDrag",
  "onDragEnd",
  "onMeasureDragConstraints",
  "onDirectionLock",
  "onDragTransitionEnd",
  "drag",
  "dragControls",
  "dragListener",
  "dragConstraints",
  "dragDirectionLock",
  "dragSnapToOrigin",
  "_dragX",
  "_dragY",
  "dragElastic",
  "dragMomentum",
  "dragPropagation",
  "dragTransition",
  "whileDrag",
  "onPan",
  "onPanStart",
  "onPanEnd",
  "onPanSessionStart",
  "onTap",
  "onTapStart",
  "onTapCancel",
  "onHoverStart",
  "onHoverEnd",
  "whileFocus",
  "whileTap",
  "whileHover",
  "whileInView",
  "onViewportEnter",
  "onViewportLeave",
  "viewport",
  "layoutScroll"
]);
function isValidMotionProp(key) {
  return validMotionProps.has(key);
}
var shouldForward = function(key) {
  return !isValidMotionProp(key);
};
function loadExternalIsValidProp(isValidProp) {
  if (!isValidProp)
    return;
  shouldForward = function(key) {
    return key.startsWith("on") ? !isValidMotionProp(key) : isValidProp(key);
  };
}
try {
  loadExternalIsValidProp(require("@emotion/is-prop-valid").default);
} catch (_a2) {
}
function filterProps(props2, isDom, forwardMotionProps) {
  var filteredProps = {};
  for (var key in props2) {
    if (shouldForward(key) || forwardMotionProps === true && isValidMotionProp(key) || !isDom && !isValidMotionProp(key) || props2["draggable"] && key.startsWith("onDrag")) {
      filteredProps[key] = props2[key];
    }
  }
  return filteredProps;
}
function calcOrigin(origin, offset2, size) {
  return typeof origin === "string" ? origin : px.transform(offset2 + size * origin);
}
function calcSVGTransformOrigin(dimensions, originX, originY) {
  var pxOriginX = calcOrigin(originX, dimensions.x, dimensions.width);
  var pxOriginY = calcOrigin(originY, dimensions.y, dimensions.height);
  return "".concat(pxOriginX, " ").concat(pxOriginY);
}
var dashKeys = {
  offset: "stroke-dashoffset",
  array: "stroke-dasharray"
};
var camelKeys = {
  offset: "strokeDashoffset",
  array: "strokeDasharray"
};
function buildSVGPath(attrs, length, spacing, offset2, useDashCase) {
  if (spacing === void 0) {
    spacing = 1;
  }
  if (offset2 === void 0) {
    offset2 = 0;
  }
  if (useDashCase === void 0) {
    useDashCase = true;
  }
  attrs.pathLength = 1;
  var keys = useDashCase ? dashKeys : camelKeys;
  attrs[keys.offset] = px.transform(-offset2);
  var pathLength = px.transform(length);
  var pathSpacing = px.transform(spacing);
  attrs[keys.array] = "".concat(pathLength, " ").concat(pathSpacing);
}
function buildSVGAttrs(state2, _a2, options, transformTemplate) {
  var attrX = _a2.attrX, attrY = _a2.attrY, originX = _a2.originX, originY = _a2.originY, pathLength = _a2.pathLength, _b = _a2.pathSpacing, pathSpacing = _b === void 0 ? 1 : _b, _c = _a2.pathOffset, pathOffset = _c === void 0 ? 0 : _c, latest = __rest(_a2, ["attrX", "attrY", "originX", "originY", "pathLength", "pathSpacing", "pathOffset"]);
  buildHTMLStyles(state2, latest, options, transformTemplate);
  state2.attrs = state2.style;
  state2.style = {};
  var attrs = state2.attrs, style2 = state2.style, dimensions = state2.dimensions;
  if (attrs.transform) {
    if (dimensions)
      style2.transform = attrs.transform;
    delete attrs.transform;
  }
  if (dimensions && (originX !== void 0 || originY !== void 0 || style2.transform)) {
    style2.transformOrigin = calcSVGTransformOrigin(dimensions, originX !== void 0 ? originX : 0.5, originY !== void 0 ? originY : 0.5);
  }
  if (attrX !== void 0)
    attrs.x = attrX;
  if (attrY !== void 0)
    attrs.y = attrY;
  if (pathLength !== void 0) {
    buildSVGPath(attrs, pathLength, pathSpacing, pathOffset, false);
  }
}
var createSvgRenderState = function() {
  return __assign(__assign({}, createHtmlRenderState()), { attrs: {} });
};
function useSVGProps(props2, visualState) {
  var visualProps = useMemo(function() {
    var state2 = createSvgRenderState();
    buildSVGAttrs(state2, visualState, { enableHardwareAcceleration: false }, props2.transformTemplate);
    return __assign(__assign({}, state2.attrs), { style: __assign({}, state2.style) });
  }, [visualState]);
  if (props2.style) {
    var rawStyles = {};
    copyRawValuesOnly(rawStyles, props2.style, props2);
    visualProps.style = __assign(__assign({}, rawStyles), visualProps.style);
  }
  return visualProps;
}
function createUseRender(forwardMotionProps) {
  if (forwardMotionProps === void 0) {
    forwardMotionProps = false;
  }
  var useRender = function(Component, props2, projectionId, ref, _a2, isStatic) {
    var latestValues = _a2.latestValues;
    var useVisualProps = isSVGComponent(Component) ? useSVGProps : useHTMLProps;
    var visualProps = useVisualProps(props2, latestValues, isStatic);
    var filteredProps = filterProps(props2, typeof Component === "string", forwardMotionProps);
    var elementProps = __assign(__assign(__assign({}, filteredProps), visualProps), { ref });
    if (projectionId) {
      elementProps["data-projection-id"] = projectionId;
    }
    return createElement(Component, elementProps);
  };
  return useRender;
}
var CAMEL_CASE_PATTERN = /([a-z])([A-Z])/g;
var REPLACE_TEMPLATE = "$1-$2";
var camelToDash = function(str) {
  return str.replace(CAMEL_CASE_PATTERN, REPLACE_TEMPLATE).toLowerCase();
};
function renderHTML(element, _a2, styleProp, projection) {
  var style2 = _a2.style, vars = _a2.vars;
  Object.assign(element.style, style2, projection && projection.getProjectionStyles(styleProp));
  for (var key in vars) {
    element.style.setProperty(key, vars[key]);
  }
}
var camelCaseAttributes = /* @__PURE__ */ new Set([
  "baseFrequency",
  "diffuseConstant",
  "kernelMatrix",
  "kernelUnitLength",
  "keySplines",
  "keyTimes",
  "limitingConeAngle",
  "markerHeight",
  "markerWidth",
  "numOctaves",
  "targetX",
  "targetY",
  "surfaceScale",
  "specularConstant",
  "specularExponent",
  "stdDeviation",
  "tableValues",
  "viewBox",
  "gradientTransform",
  "pathLength"
]);
function renderSVG(element, renderState) {
  renderHTML(element, renderState);
  for (var key in renderState.attrs) {
    element.setAttribute(!camelCaseAttributes.has(key) ? camelToDash(key) : key, renderState.attrs[key]);
  }
}
function scrapeMotionValuesFromProps$1(props2) {
  var style2 = props2.style;
  var newValues = {};
  for (var key in style2) {
    if (isMotionValue(style2[key]) || isForcedMotionValue(key, props2)) {
      newValues[key] = style2[key];
    }
  }
  return newValues;
}
function scrapeMotionValuesFromProps(props2) {
  var newValues = scrapeMotionValuesFromProps$1(props2);
  for (var key in props2) {
    if (isMotionValue(props2[key])) {
      var targetKey = key === "x" || key === "y" ? "attr" + key.toUpperCase() : key;
      newValues[targetKey] = props2[key];
    }
  }
  return newValues;
}
function isAnimationControls(v2) {
  return typeof v2 === "object" && typeof v2.start === "function";
}
function makeState(_a2, props2, context, presenceContext) {
  var scrapeMotionValuesFromProps2 = _a2.scrapeMotionValuesFromProps, createRenderState = _a2.createRenderState, onMount = _a2.onMount;
  var state2 = {
    latestValues: makeLatestValues(props2, context, presenceContext, scrapeMotionValuesFromProps2),
    renderState: createRenderState()
  };
  if (onMount) {
    state2.mount = function(instance) {
      return onMount(props2, instance, state2);
    };
  }
  return state2;
}
var makeUseVisualState = function(config) {
  return function(props2, isStatic) {
    var context = useContext(MotionContext);
    var presenceContext = useContext(PresenceContext);
    return isStatic ? makeState(config, props2, context, presenceContext) : useConstant(function() {
      return makeState(config, props2, context, presenceContext);
    });
  };
};
function makeLatestValues(props2, context, presenceContext, scrapeMotionValues) {
  var values = {};
  var blockInitialAnimation = (presenceContext === null || presenceContext === void 0 ? void 0 : presenceContext.initial) === false;
  var motionValues = scrapeMotionValues(props2);
  for (var key in motionValues) {
    values[key] = resolveMotionValue(motionValues[key]);
  }
  var initial = props2.initial, animate2 = props2.animate;
  var isControllingVariants = checkIfControllingVariants(props2);
  var isVariantNode = checkIfVariantNode(props2);
  if (context && isVariantNode && !isControllingVariants && props2.inherit !== false) {
    initial !== null && initial !== void 0 ? initial : initial = context.initial;
    animate2 !== null && animate2 !== void 0 ? animate2 : animate2 = context.animate;
  }
  var initialAnimationIsBlocked = blockInitialAnimation || initial === false;
  var variantToSet = initialAnimationIsBlocked ? animate2 : initial;
  if (variantToSet && typeof variantToSet !== "boolean" && !isAnimationControls(variantToSet)) {
    var list = Array.isArray(variantToSet) ? variantToSet : [variantToSet];
    list.forEach(function(definition) {
      var resolved = resolveVariantFromProps(props2, definition);
      if (!resolved)
        return;
      var transitionEnd2 = resolved.transitionEnd;
      resolved.transition;
      var target = __rest(resolved, ["transitionEnd", "transition"]);
      for (var key2 in target) {
        var valueTarget = target[key2];
        if (Array.isArray(valueTarget)) {
          var index2 = initialAnimationIsBlocked ? valueTarget.length - 1 : 0;
          valueTarget = valueTarget[index2];
        }
        if (valueTarget !== null) {
          values[key2] = valueTarget;
        }
      }
      for (var key2 in transitionEnd2)
        values[key2] = transitionEnd2[key2];
    });
  }
  return values;
}
var svgMotionConfig = {
  useVisualState: makeUseVisualState({
    scrapeMotionValuesFromProps,
    createRenderState: createSvgRenderState,
    onMount: function(props2, instance, _a2) {
      var renderState = _a2.renderState, latestValues = _a2.latestValues;
      try {
        renderState.dimensions = typeof instance.getBBox === "function" ? instance.getBBox() : instance.getBoundingClientRect();
      } catch (e2) {
        renderState.dimensions = {
          x: 0,
          y: 0,
          width: 0,
          height: 0
        };
      }
      buildSVGAttrs(renderState, latestValues, { enableHardwareAcceleration: false }, props2.transformTemplate);
      renderSVG(instance, renderState);
    }
  })
};
var htmlMotionConfig = {
  useVisualState: makeUseVisualState({
    scrapeMotionValuesFromProps: scrapeMotionValuesFromProps$1,
    createRenderState: createHtmlRenderState
  })
};
function createDomMotionConfig(Component, _a2, preloadedFeatures, createVisualElement, projectionNodeConstructor) {
  var _b = _a2.forwardMotionProps, forwardMotionProps = _b === void 0 ? false : _b;
  var baseConfig = isSVGComponent(Component) ? svgMotionConfig : htmlMotionConfig;
  return __assign(__assign({}, baseConfig), { preloadedFeatures, useRender: createUseRender(forwardMotionProps), createVisualElement, projectionNodeConstructor, Component });
}
var AnimationType;
(function(AnimationType2) {
  AnimationType2["Animate"] = "animate";
  AnimationType2["Hover"] = "whileHover";
  AnimationType2["Tap"] = "whileTap";
  AnimationType2["Drag"] = "whileDrag";
  AnimationType2["Focus"] = "whileFocus";
  AnimationType2["InView"] = "whileInView";
  AnimationType2["Exit"] = "exit";
})(AnimationType || (AnimationType = {}));
function addDomEvent(target, eventName, handler, options) {
  target.addEventListener(eventName, handler, options);
  return function() {
    return target.removeEventListener(eventName, handler, options);
  };
}
function useDomEvent(ref, eventName, handler, options) {
  useEffect(function() {
    var element = ref.current;
    if (handler && element) {
      return addDomEvent(element, eventName, handler, options);
    }
  }, [ref, eventName, handler, options]);
}
function useFocusGesture(_a2) {
  var whileFocus = _a2.whileFocus, visualElement2 = _a2.visualElement;
  var onFocus = function() {
    var _a3;
    (_a3 = visualElement2.animationState) === null || _a3 === void 0 ? void 0 : _a3.setActive(AnimationType.Focus, true);
  };
  var onBlur = function() {
    var _a3;
    (_a3 = visualElement2.animationState) === null || _a3 === void 0 ? void 0 : _a3.setActive(AnimationType.Focus, false);
  };
  useDomEvent(visualElement2, "focus", whileFocus ? onFocus : void 0);
  useDomEvent(visualElement2, "blur", whileFocus ? onBlur : void 0);
}
function isMouseEvent(event) {
  if (typeof PointerEvent !== "undefined" && event instanceof PointerEvent) {
    return !!(event.pointerType === "mouse");
  }
  return event instanceof MouseEvent;
}
function isTouchEvent(event) {
  var hasTouches = !!event.touches;
  return hasTouches;
}
function filterPrimaryPointer(eventHandler) {
  return function(event) {
    var isMouseEvent2 = event instanceof MouseEvent;
    var isPrimaryPointer = !isMouseEvent2 || isMouseEvent2 && event.button === 0;
    if (isPrimaryPointer) {
      eventHandler(event);
    }
  };
}
var defaultPagePoint = { pageX: 0, pageY: 0 };
function pointFromTouch(e2, pointType) {
  if (pointType === void 0) {
    pointType = "page";
  }
  var primaryTouch = e2.touches[0] || e2.changedTouches[0];
  var point = primaryTouch || defaultPagePoint;
  return {
    x: point[pointType + "X"],
    y: point[pointType + "Y"]
  };
}
function pointFromMouse(point, pointType) {
  if (pointType === void 0) {
    pointType = "page";
  }
  return {
    x: point[pointType + "X"],
    y: point[pointType + "Y"]
  };
}
function extractEventInfo(event, pointType) {
  if (pointType === void 0) {
    pointType = "page";
  }
  return {
    point: isTouchEvent(event) ? pointFromTouch(event, pointType) : pointFromMouse(event, pointType)
  };
}
var wrapHandler = function(handler, shouldFilterPrimaryPointer) {
  if (shouldFilterPrimaryPointer === void 0) {
    shouldFilterPrimaryPointer = false;
  }
  var listener = function(event) {
    return handler(event, extractEventInfo(event));
  };
  return shouldFilterPrimaryPointer ? filterPrimaryPointer(listener) : listener;
};
var supportsPointerEvents$1 = function() {
  return isBrowser$1 && window.onpointerdown === null;
};
var supportsTouchEvents$1 = function() {
  return isBrowser$1 && window.ontouchstart === null;
};
var supportsMouseEvents = function() {
  return isBrowser$1 && window.onmousedown === null;
};
var mouseEventNames = {
  pointerdown: "mousedown",
  pointermove: "mousemove",
  pointerup: "mouseup",
  pointercancel: "mousecancel",
  pointerover: "mouseover",
  pointerout: "mouseout",
  pointerenter: "mouseenter",
  pointerleave: "mouseleave"
};
var touchEventNames = {
  pointerdown: "touchstart",
  pointermove: "touchmove",
  pointerup: "touchend",
  pointercancel: "touchcancel"
};
function getPointerEventName(name) {
  if (supportsPointerEvents$1()) {
    return name;
  } else if (supportsTouchEvents$1()) {
    return touchEventNames[name];
  } else if (supportsMouseEvents()) {
    return mouseEventNames[name];
  }
  return name;
}
function addPointerEvent(target, eventName, handler, options) {
  return addDomEvent(target, getPointerEventName(eventName), wrapHandler(handler, eventName === "pointerdown"), options);
}
function usePointerEvent(ref, eventName, handler, options) {
  return useDomEvent(ref, getPointerEventName(eventName), handler && wrapHandler(handler, eventName === "pointerdown"), options);
}
function createLock(name) {
  var lock = null;
  return function() {
    var openLock = function() {
      lock = null;
    };
    if (lock === null) {
      lock = name;
      return openLock;
    }
    return false;
  };
}
var globalHorizontalLock = createLock("dragHorizontal");
var globalVerticalLock = createLock("dragVertical");
function getGlobalLock(drag) {
  var lock = false;
  if (drag === "y") {
    lock = globalVerticalLock();
  } else if (drag === "x") {
    lock = globalHorizontalLock();
  } else {
    var openHorizontal_1 = globalHorizontalLock();
    var openVertical_1 = globalVerticalLock();
    if (openHorizontal_1 && openVertical_1) {
      lock = function() {
        openHorizontal_1();
        openVertical_1();
      };
    } else {
      if (openHorizontal_1)
        openHorizontal_1();
      if (openVertical_1)
        openVertical_1();
    }
  }
  return lock;
}
function isDragActive() {
  var openGestureLock = getGlobalLock(true);
  if (!openGestureLock)
    return true;
  openGestureLock();
  return false;
}
function createHoverEvent(visualElement2, isActive, callback) {
  return function(event, info) {
    var _a2;
    if (!isMouseEvent(event) || isDragActive())
      return;
    (_a2 = visualElement2.animationState) === null || _a2 === void 0 ? void 0 : _a2.setActive(AnimationType.Hover, isActive);
    callback === null || callback === void 0 ? void 0 : callback(event, info);
  };
}
function useHoverGesture(_a2) {
  var onHoverStart = _a2.onHoverStart, onHoverEnd = _a2.onHoverEnd, whileHover = _a2.whileHover, visualElement2 = _a2.visualElement;
  usePointerEvent(visualElement2, "pointerenter", onHoverStart || whileHover ? createHoverEvent(visualElement2, true, onHoverStart) : void 0);
  usePointerEvent(visualElement2, "pointerleave", onHoverEnd || whileHover ? createHoverEvent(visualElement2, false, onHoverEnd) : void 0);
}
var isNodeOrChild = function(parent, child) {
  if (!child) {
    return false;
  } else if (parent === child) {
    return true;
  } else {
    return isNodeOrChild(parent, child.parentElement);
  }
};
function useUnmountEffect(callback) {
  return useEffect(function() {
    return function() {
      return callback();
    };
  }, []);
}
function useTapGesture(_a2) {
  var onTap = _a2.onTap, onTapStart = _a2.onTapStart, onTapCancel = _a2.onTapCancel, whileTap = _a2.whileTap, visualElement2 = _a2.visualElement;
  var hasPressListeners = onTap || onTapStart || onTapCancel || whileTap;
  var isPressing = useRef(false);
  var cancelPointerEndListeners = useRef(null);
  function removePointerEndListener() {
    var _a3;
    (_a3 = cancelPointerEndListeners.current) === null || _a3 === void 0 ? void 0 : _a3.call(cancelPointerEndListeners);
    cancelPointerEndListeners.current = null;
  }
  function checkPointerEnd() {
    var _a3;
    removePointerEndListener();
    isPressing.current = false;
    (_a3 = visualElement2.animationState) === null || _a3 === void 0 ? void 0 : _a3.setActive(AnimationType.Tap, false);
    return !isDragActive();
  }
  function onPointerUp(event, info) {
    if (!checkPointerEnd())
      return;
    !isNodeOrChild(visualElement2.getInstance(), event.target) ? onTapCancel === null || onTapCancel === void 0 ? void 0 : onTapCancel(event, info) : onTap === null || onTap === void 0 ? void 0 : onTap(event, info);
  }
  function onPointerCancel(event, info) {
    if (!checkPointerEnd())
      return;
    onTapCancel === null || onTapCancel === void 0 ? void 0 : onTapCancel(event, info);
  }
  function onPointerDown(event, info) {
    var _a3;
    removePointerEndListener();
    if (isPressing.current)
      return;
    isPressing.current = true;
    cancelPointerEndListeners.current = pipe(addPointerEvent(window, "pointerup", onPointerUp), addPointerEvent(window, "pointercancel", onPointerCancel));
    (_a3 = visualElement2.animationState) === null || _a3 === void 0 ? void 0 : _a3.setActive(AnimationType.Tap, true);
    onTapStart === null || onTapStart === void 0 ? void 0 : onTapStart(event, info);
  }
  usePointerEvent(visualElement2, "pointerdown", hasPressListeners ? onPointerDown : void 0);
  useUnmountEffect(removePointerEndListener);
}
var observerCallbacks = /* @__PURE__ */ new WeakMap();
var observers = /* @__PURE__ */ new WeakMap();
var fireObserverCallback = function(entry) {
  var _a2;
  (_a2 = observerCallbacks.get(entry.target)) === null || _a2 === void 0 ? void 0 : _a2(entry);
};
var fireAllObserverCallbacks = function(entries) {
  entries.forEach(fireObserverCallback);
};
function initIntersectionObserver(_a2) {
  var root = _a2.root, options = __rest(_a2, ["root"]);
  var lookupRoot = root || document;
  if (!observers.has(lookupRoot)) {
    observers.set(lookupRoot, {});
  }
  var rootObservers = observers.get(lookupRoot);
  var key = JSON.stringify(options);
  if (!rootObservers[key]) {
    rootObservers[key] = new IntersectionObserver(fireAllObserverCallbacks, __assign({ root }, options));
  }
  return rootObservers[key];
}
function observeIntersection(element, options, callback) {
  var rootInteresectionObserver = initIntersectionObserver(options);
  observerCallbacks.set(element, callback);
  rootInteresectionObserver.observe(element);
  return function() {
    observerCallbacks.delete(element);
    rootInteresectionObserver.unobserve(element);
  };
}
function useViewport(_a2) {
  var visualElement2 = _a2.visualElement, whileInView = _a2.whileInView, onViewportEnter = _a2.onViewportEnter, onViewportLeave = _a2.onViewportLeave, _b = _a2.viewport, viewport = _b === void 0 ? {} : _b;
  var state2 = useRef({
    hasEnteredView: false,
    isInView: false
  });
  var shouldObserve = Boolean(whileInView || onViewportEnter || onViewportLeave);
  if (viewport.once && state2.current.hasEnteredView)
    shouldObserve = false;
  var useObserver = typeof IntersectionObserver === "undefined" ? useMissingIntersectionObserver : useIntersectionObserver;
  useObserver(shouldObserve, state2.current, visualElement2, viewport);
}
var thresholdNames = {
  some: 0,
  all: 1
};
function useIntersectionObserver(shouldObserve, state2, visualElement2, _a2) {
  var root = _a2.root, rootMargin = _a2.margin, _b = _a2.amount, amount = _b === void 0 ? "some" : _b, once = _a2.once;
  useEffect(function() {
    if (!shouldObserve)
      return;
    var options = {
      root: root === null || root === void 0 ? void 0 : root.current,
      rootMargin,
      threshold: typeof amount === "number" ? amount : thresholdNames[amount]
    };
    var intersectionCallback = function(entry) {
      var _a3;
      var isIntersecting = entry.isIntersecting;
      if (state2.isInView === isIntersecting)
        return;
      state2.isInView = isIntersecting;
      if (once && !isIntersecting && state2.hasEnteredView) {
        return;
      } else if (isIntersecting) {
        state2.hasEnteredView = true;
      }
      (_a3 = visualElement2.animationState) === null || _a3 === void 0 ? void 0 : _a3.setActive(AnimationType.InView, isIntersecting);
      var props2 = visualElement2.getProps();
      var callback = isIntersecting ? props2.onViewportEnter : props2.onViewportLeave;
      callback === null || callback === void 0 ? void 0 : callback(entry);
    };
    return observeIntersection(visualElement2.getInstance(), options, intersectionCallback);
  }, [shouldObserve, root, rootMargin, amount]);
}
function useMissingIntersectionObserver(shouldObserve, state2, visualElement2) {
  useEffect(function() {
    if (!shouldObserve)
      return;
    requestAnimationFrame(function() {
      var _a2;
      state2.hasEnteredView = true;
      var onViewportEnter = visualElement2.getProps().onViewportEnter;
      onViewportEnter === null || onViewportEnter === void 0 ? void 0 : onViewportEnter(null);
      (_a2 = visualElement2.animationState) === null || _a2 === void 0 ? void 0 : _a2.setActive(AnimationType.InView, true);
    });
  }, [shouldObserve]);
}
var makeRenderlessComponent = function(hook) {
  return function(props2) {
    hook(props2);
    return null;
  };
};
var gestureAnimations = {
  inView: makeRenderlessComponent(useViewport),
  tap: makeRenderlessComponent(useTapGesture),
  focus: makeRenderlessComponent(useFocusGesture),
  hover: makeRenderlessComponent(useHoverGesture)
};
function usePresence() {
  var context = useContext(PresenceContext);
  if (context === null)
    return [true, null];
  var isPresent = context.isPresent, onExitComplete = context.onExitComplete, register = context.register;
  var id2 = useUniqueId();
  useEffect(function() {
    return register(id2);
  }, []);
  var safeToRemove = function() {
    return onExitComplete === null || onExitComplete === void 0 ? void 0 : onExitComplete(id2);
  };
  return !isPresent && onExitComplete ? [false, safeToRemove] : [true];
}
var counter = 0;
var incrementId = function() {
  return counter++;
};
var useUniqueId = function() {
  return useConstant(incrementId);
};
function shallowCompare(next, prev) {
  if (!Array.isArray(prev))
    return false;
  var prevLength = prev.length;
  if (prevLength !== next.length)
    return false;
  for (var i2 = 0; i2 < prevLength; i2++) {
    if (prev[i2] !== next[i2])
      return false;
  }
  return true;
}
var isNumericalString = function(v2) {
  return /^\-?\d*\.?\d+$/.test(v2);
};
var isZeroValueString = function(v2) {
  return /^0[^.\s]+$/.test(v2);
};
var testValueType = function(v2) {
  return function(type) {
    return type.test(v2);
  };
};
var auto = {
  test: function(v2) {
    return v2 === "auto";
  },
  parse: function(v2) {
    return v2;
  }
};
var dimensionValueTypes = [number, px, percent, degrees, vw, vh, auto];
var findDimensionValueType = function(v2) {
  return dimensionValueTypes.find(testValueType(v2));
};
var valueTypes = __spreadArray(__spreadArray([], __read(dimensionValueTypes), false), [color$1, complex], false);
var findValueType = function(v2) {
  return valueTypes.find(testValueType(v2));
};
function setMotionValue(visualElement2, key, value) {
  if (visualElement2.hasValue(key)) {
    visualElement2.getValue(key).set(value);
  } else {
    visualElement2.addValue(key, motionValue(value));
  }
}
function setTarget(visualElement2, definition) {
  var resolved = resolveVariant(visualElement2, definition);
  var _a2 = resolved ? visualElement2.makeTargetAnimatable(resolved, false) : {}, _b = _a2.transitionEnd, transitionEnd2 = _b === void 0 ? {} : _b;
  _a2.transition;
  var target = __rest(_a2, ["transitionEnd", "transition"]);
  target = __assign(__assign({}, target), transitionEnd2);
  for (var key in target) {
    var value = resolveFinalValueInKeyframes(target[key]);
    setMotionValue(visualElement2, key, value);
  }
}
function checkTargetForNewValues(visualElement2, target, origin) {
  var _a2, _b, _c;
  var _d;
  var newValueKeys = Object.keys(target).filter(function(key2) {
    return !visualElement2.hasValue(key2);
  });
  var numNewValues = newValueKeys.length;
  if (!numNewValues)
    return;
  for (var i2 = 0; i2 < numNewValues; i2++) {
    var key = newValueKeys[i2];
    var targetValue = target[key];
    var value = null;
    if (Array.isArray(targetValue)) {
      value = targetValue[0];
    }
    if (value === null) {
      value = (_b = (_a2 = origin[key]) !== null && _a2 !== void 0 ? _a2 : visualElement2.readValue(key)) !== null && _b !== void 0 ? _b : target[key];
    }
    if (value === void 0 || value === null)
      continue;
    if (typeof value === "string" && (isNumericalString(value) || isZeroValueString(value))) {
      value = parseFloat(value);
    } else if (!findValueType(value) && complex.test(targetValue)) {
      value = getAnimatableNone(key, targetValue);
    }
    visualElement2.addValue(key, motionValue(value));
    (_c = (_d = origin)[key]) !== null && _c !== void 0 ? _c : _d[key] = value;
    visualElement2.setBaseTarget(key, value);
  }
}
function getOriginFromTransition(key, transition) {
  if (!transition)
    return;
  var valueTransition = transition[key] || transition["default"] || transition;
  return valueTransition.from;
}
function getOrigin(target, transition, visualElement2) {
  var _a2, _b;
  var origin = {};
  for (var key in target) {
    origin[key] = (_a2 = getOriginFromTransition(key, transition)) !== null && _a2 !== void 0 ? _a2 : (_b = visualElement2.getValue(key)) === null || _b === void 0 ? void 0 : _b.get();
  }
  return origin;
}
function animateVisualElement(visualElement2, definition, options) {
  if (options === void 0) {
    options = {};
  }
  visualElement2.notifyAnimationStart(definition);
  var animation;
  if (Array.isArray(definition)) {
    var animations2 = definition.map(function(variant) {
      return animateVariant(visualElement2, variant, options);
    });
    animation = Promise.all(animations2);
  } else if (typeof definition === "string") {
    animation = animateVariant(visualElement2, definition, options);
  } else {
    var resolvedDefinition = typeof definition === "function" ? resolveVariant(visualElement2, definition, options.custom) : definition;
    animation = animateTarget(visualElement2, resolvedDefinition, options);
  }
  return animation.then(function() {
    return visualElement2.notifyAnimationComplete(definition);
  });
}
function animateVariant(visualElement2, variant, options) {
  var _a2;
  if (options === void 0) {
    options = {};
  }
  var resolved = resolveVariant(visualElement2, variant, options.custom);
  var _b = (resolved || {}).transition, transition = _b === void 0 ? visualElement2.getDefaultTransition() || {} : _b;
  if (options.transitionOverride) {
    transition = options.transitionOverride;
  }
  var getAnimation2 = resolved ? function() {
    return animateTarget(visualElement2, resolved, options);
  } : function() {
    return Promise.resolve();
  };
  var getChildAnimations = ((_a2 = visualElement2.variantChildren) === null || _a2 === void 0 ? void 0 : _a2.size) ? function(forwardDelay) {
    if (forwardDelay === void 0) {
      forwardDelay = 0;
    }
    var _a3 = transition.delayChildren, delayChildren = _a3 === void 0 ? 0 : _a3, staggerChildren = transition.staggerChildren, staggerDirection = transition.staggerDirection;
    return animateChildren(visualElement2, variant, delayChildren + forwardDelay, staggerChildren, staggerDirection, options);
  } : function() {
    return Promise.resolve();
  };
  var when = transition.when;
  if (when) {
    var _c = __read(when === "beforeChildren" ? [getAnimation2, getChildAnimations] : [getChildAnimations, getAnimation2], 2), first = _c[0], last = _c[1];
    return first().then(last);
  } else {
    return Promise.all([getAnimation2(), getChildAnimations(options.delay)]);
  }
}
function animateTarget(visualElement2, definition, _a2) {
  var _b;
  var _c = _a2 === void 0 ? {} : _a2, _d = _c.delay, delay = _d === void 0 ? 0 : _d, transitionOverride = _c.transitionOverride, type = _c.type;
  var _e2 = visualElement2.makeTargetAnimatable(definition), _f2 = _e2.transition, transition = _f2 === void 0 ? visualElement2.getDefaultTransition() : _f2, transitionEnd2 = _e2.transitionEnd, target = __rest(_e2, ["transition", "transitionEnd"]);
  if (transitionOverride)
    transition = transitionOverride;
  var animations2 = [];
  var animationTypeState = type && ((_b = visualElement2.animationState) === null || _b === void 0 ? void 0 : _b.getState()[type]);
  for (var key in target) {
    var value = visualElement2.getValue(key);
    var valueTarget = target[key];
    if (!value || valueTarget === void 0 || animationTypeState && shouldBlockAnimation(animationTypeState, key)) {
      continue;
    }
    var animation = startAnimation(key, value, valueTarget, __assign({ delay }, transition));
    animations2.push(animation);
  }
  return Promise.all(animations2).then(function() {
    transitionEnd2 && setTarget(visualElement2, transitionEnd2);
  });
}
function animateChildren(visualElement2, variant, delayChildren, staggerChildren, staggerDirection, options) {
  if (delayChildren === void 0) {
    delayChildren = 0;
  }
  if (staggerChildren === void 0) {
    staggerChildren = 0;
  }
  if (staggerDirection === void 0) {
    staggerDirection = 1;
  }
  var animations2 = [];
  var maxStaggerDuration = (visualElement2.variantChildren.size - 1) * staggerChildren;
  var generateStaggerDuration = staggerDirection === 1 ? function(i2) {
    if (i2 === void 0) {
      i2 = 0;
    }
    return i2 * staggerChildren;
  } : function(i2) {
    if (i2 === void 0) {
      i2 = 0;
    }
    return maxStaggerDuration - i2 * staggerChildren;
  };
  Array.from(visualElement2.variantChildren).sort(sortByTreeOrder).forEach(function(child, i2) {
    animations2.push(animateVariant(child, variant, __assign(__assign({}, options), { delay: delayChildren + generateStaggerDuration(i2) })).then(function() {
      return child.notifyAnimationComplete(variant);
    }));
  });
  return Promise.all(animations2);
}
function sortByTreeOrder(a2, b2) {
  return a2.sortNodePosition(b2);
}
function shouldBlockAnimation(_a2, key) {
  var protectedKeys = _a2.protectedKeys, needsAnimating = _a2.needsAnimating;
  var shouldBlock = protectedKeys.hasOwnProperty(key) && needsAnimating[key] !== true;
  needsAnimating[key] = false;
  return shouldBlock;
}
var variantPriorityOrder = [
  AnimationType.Animate,
  AnimationType.InView,
  AnimationType.Focus,
  AnimationType.Hover,
  AnimationType.Tap,
  AnimationType.Drag,
  AnimationType.Exit
];
var reversePriorityOrder = __spreadArray([], __read(variantPriorityOrder), false).reverse();
var numAnimationTypes = variantPriorityOrder.length;
function animateList(visualElement2) {
  return function(animations2) {
    return Promise.all(animations2.map(function(_a2) {
      var animation = _a2.animation, options = _a2.options;
      return animateVisualElement(visualElement2, animation, options);
    }));
  };
}
function createAnimationState(visualElement2) {
  var animate2 = animateList(visualElement2);
  var state2 = createState();
  var allAnimatedKeys = {};
  var isInitialRender = true;
  var buildResolvedTypeValues = function(acc, definition) {
    var resolved = resolveVariant(visualElement2, definition);
    if (resolved) {
      resolved.transition;
      var transitionEnd2 = resolved.transitionEnd, target = __rest(resolved, ["transition", "transitionEnd"]);
      acc = __assign(__assign(__assign({}, acc), target), transitionEnd2);
    }
    return acc;
  };
  function isAnimated(key) {
    return allAnimatedKeys[key] !== void 0;
  }
  function setAnimateFunction(makeAnimator) {
    animate2 = makeAnimator(visualElement2);
  }
  function animateChanges(options, changedActiveType) {
    var _a2;
    var props2 = visualElement2.getProps();
    var context = visualElement2.getVariantContext(true) || {};
    var animations2 = [];
    var removedKeys = /* @__PURE__ */ new Set();
    var encounteredKeys = {};
    var removedVariantIndex = Infinity;
    var _loop_1 = function(i3) {
      var type = reversePriorityOrder[i3];
      var typeState = state2[type];
      var prop = (_a2 = props2[type]) !== null && _a2 !== void 0 ? _a2 : context[type];
      var propIsVariant = isVariantLabel(prop);
      var activeDelta = type === changedActiveType ? typeState.isActive : null;
      if (activeDelta === false)
        removedVariantIndex = i3;
      var isInherited = prop === context[type] && prop !== props2[type] && propIsVariant;
      if (isInherited && isInitialRender && visualElement2.manuallyAnimateOnMount) {
        isInherited = false;
      }
      typeState.protectedKeys = __assign({}, encounteredKeys);
      if (!typeState.isActive && activeDelta === null || !prop && !typeState.prevProp || isAnimationControls(prop) || typeof prop === "boolean") {
        return "continue";
      }
      var variantDidChange = checkVariantsDidChange(typeState.prevProp, prop);
      var shouldAnimateType = variantDidChange || type === changedActiveType && typeState.isActive && !isInherited && propIsVariant || i3 > removedVariantIndex && propIsVariant;
      var definitionList = Array.isArray(prop) ? prop : [prop];
      var resolvedValues = definitionList.reduce(buildResolvedTypeValues, {});
      if (activeDelta === false)
        resolvedValues = {};
      var _b = typeState.prevResolvedValues, prevResolvedValues = _b === void 0 ? {} : _b;
      var allKeys = __assign(__assign({}, prevResolvedValues), resolvedValues);
      var markToAnimate = function(key2) {
        shouldAnimateType = true;
        removedKeys.delete(key2);
        typeState.needsAnimating[key2] = true;
      };
      for (var key in allKeys) {
        var next = resolvedValues[key];
        var prev = prevResolvedValues[key];
        if (encounteredKeys.hasOwnProperty(key))
          continue;
        if (next !== prev) {
          if (isKeyframesTarget(next) && isKeyframesTarget(prev)) {
            if (!shallowCompare(next, prev) || variantDidChange) {
              markToAnimate(key);
            } else {
              typeState.protectedKeys[key] = true;
            }
          } else if (next !== void 0) {
            markToAnimate(key);
          } else {
            removedKeys.add(key);
          }
        } else if (next !== void 0 && removedKeys.has(key)) {
          markToAnimate(key);
        } else {
          typeState.protectedKeys[key] = true;
        }
      }
      typeState.prevProp = prop;
      typeState.prevResolvedValues = resolvedValues;
      if (typeState.isActive) {
        encounteredKeys = __assign(__assign({}, encounteredKeys), resolvedValues);
      }
      if (isInitialRender && visualElement2.blockInitialAnimation) {
        shouldAnimateType = false;
      }
      if (shouldAnimateType && !isInherited) {
        animations2.push.apply(animations2, __spreadArray([], __read(definitionList.map(function(animation) {
          return {
            animation,
            options: __assign({ type }, options)
          };
        })), false));
      }
    };
    for (var i2 = 0; i2 < numAnimationTypes; i2++) {
      _loop_1(i2);
    }
    allAnimatedKeys = __assign({}, encounteredKeys);
    if (removedKeys.size) {
      var fallbackAnimation_1 = {};
      removedKeys.forEach(function(key) {
        var fallbackTarget = visualElement2.getBaseTarget(key);
        if (fallbackTarget !== void 0) {
          fallbackAnimation_1[key] = fallbackTarget;
        }
      });
      animations2.push({ animation: fallbackAnimation_1 });
    }
    var shouldAnimate = Boolean(animations2.length);
    if (isInitialRender && props2.initial === false && !visualElement2.manuallyAnimateOnMount) {
      shouldAnimate = false;
    }
    isInitialRender = false;
    return shouldAnimate ? animate2(animations2) : Promise.resolve();
  }
  function setActive(type, isActive, options) {
    var _a2;
    if (state2[type].isActive === isActive)
      return Promise.resolve();
    (_a2 = visualElement2.variantChildren) === null || _a2 === void 0 ? void 0 : _a2.forEach(function(child) {
      var _a3;
      return (_a3 = child.animationState) === null || _a3 === void 0 ? void 0 : _a3.setActive(type, isActive);
    });
    state2[type].isActive = isActive;
    return animateChanges(options, type);
  }
  return {
    isAnimated,
    animateChanges,
    setActive,
    setAnimateFunction,
    getState: function() {
      return state2;
    }
  };
}
function checkVariantsDidChange(prev, next) {
  if (typeof next === "string") {
    return next !== prev;
  } else if (isVariantLabels(next)) {
    return !shallowCompare(next, prev);
  }
  return false;
}
function createTypeState(isActive) {
  if (isActive === void 0) {
    isActive = false;
  }
  return {
    isActive,
    protectedKeys: {},
    needsAnimating: {},
    prevResolvedValues: {}
  };
}
function createState() {
  var _a2;
  return _a2 = {}, _a2[AnimationType.Animate] = createTypeState(true), _a2[AnimationType.InView] = createTypeState(), _a2[AnimationType.Hover] = createTypeState(), _a2[AnimationType.Tap] = createTypeState(), _a2[AnimationType.Drag] = createTypeState(), _a2[AnimationType.Focus] = createTypeState(), _a2[AnimationType.Exit] = createTypeState(), _a2;
}
var animations = {
  animation: makeRenderlessComponent(function(_a2) {
    var visualElement2 = _a2.visualElement, animate2 = _a2.animate;
    visualElement2.animationState || (visualElement2.animationState = createAnimationState(visualElement2));
    if (isAnimationControls(animate2)) {
      useEffect(function() {
        return animate2.subscribe(visualElement2);
      }, [animate2]);
    }
  }),
  exit: makeRenderlessComponent(function(props2) {
    var custom = props2.custom, visualElement2 = props2.visualElement;
    var _a2 = __read(usePresence(), 2), isPresent = _a2[0], safeToRemove = _a2[1];
    var presenceContext = useContext(PresenceContext);
    useEffect(function() {
      var _a3, _b;
      visualElement2.isPresent = isPresent;
      var animation = (_a3 = visualElement2.animationState) === null || _a3 === void 0 ? void 0 : _a3.setActive(AnimationType.Exit, !isPresent, { custom: (_b = presenceContext === null || presenceContext === void 0 ? void 0 : presenceContext.custom) !== null && _b !== void 0 ? _b : custom });
      !isPresent && (animation === null || animation === void 0 ? void 0 : animation.then(safeToRemove));
    }, [isPresent]);
  })
};
function convertBoundingBoxToBox(_a2) {
  var top = _a2.top, left = _a2.left, right = _a2.right, bottom = _a2.bottom;
  return {
    x: { min: left, max: right },
    y: { min: top, max: bottom }
  };
}
function transformBoxPoints(point, transformPoint) {
  if (!transformPoint)
    return point;
  var topLeft = transformPoint({ x: point.left, y: point.top });
  var bottomRight = transformPoint({ x: point.right, y: point.bottom });
  return {
    top: topLeft.y,
    left: topLeft.x,
    bottom: bottomRight.y,
    right: bottomRight.x
  };
}
function measureViewportBox(instance, transformPoint) {
  return convertBoundingBoxToBox(transformBoxPoints(instance.getBoundingClientRect(), transformPoint));
}
var names = [
  "LayoutMeasure",
  "BeforeLayoutMeasure",
  "LayoutUpdate",
  "ViewportBoxUpdate",
  "Update",
  "Render",
  "AnimationComplete",
  "LayoutAnimationComplete",
  "AnimationStart",
  "SetAxisTarget",
  "Unmount"
];
function createLifecycles() {
  var managers = names.map(function() {
    return new SubscriptionManager();
  });
  var propSubscriptions = {};
  var lifecycles = {
    clearAllListeners: function() {
      return managers.forEach(function(manager) {
        return manager.clear();
      });
    },
    updatePropListeners: function(props2) {
      names.forEach(function(name) {
        var _a2;
        var on2 = "on" + name;
        var propListener = props2[on2];
        (_a2 = propSubscriptions[name]) === null || _a2 === void 0 ? void 0 : _a2.call(propSubscriptions);
        if (propListener) {
          propSubscriptions[name] = lifecycles[on2](propListener);
        }
      });
    }
  };
  managers.forEach(function(manager, i2) {
    lifecycles["on" + names[i2]] = function(handler) {
      return manager.add(handler);
    };
    lifecycles["notify" + names[i2]] = function() {
      var args = [];
      for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
      }
      manager.notify.apply(manager, __spreadArray([], __read(args), false));
    };
  });
  return lifecycles;
}
function updateMotionValuesFromProps(element, next, prev) {
  var _a2;
  for (var key in next) {
    var nextValue = next[key];
    var prevValue = prev[key];
    if (isMotionValue(nextValue)) {
      element.addValue(key, nextValue);
    } else if (isMotionValue(prevValue)) {
      element.addValue(key, motionValue(nextValue));
    } else if (prevValue !== nextValue) {
      if (element.hasValue(key)) {
        var existingValue = element.getValue(key);
        !existingValue.hasAnimated && existingValue.set(nextValue);
      } else {
        element.addValue(key, motionValue((_a2 = element.getStaticValue(key)) !== null && _a2 !== void 0 ? _a2 : nextValue));
      }
    }
  }
  for (var key in prev) {
    if (next[key] === void 0)
      element.removeValue(key);
  }
  return next;
}
var visualElement = function(_a2) {
  var _b = _a2.treeType, treeType = _b === void 0 ? "" : _b, build = _a2.build, getBaseTarget = _a2.getBaseTarget, makeTargetAnimatable = _a2.makeTargetAnimatable, measureViewportBox2 = _a2.measureViewportBox, renderInstance = _a2.render, readValueFromInstance = _a2.readValueFromInstance, removeValueFromRenderState = _a2.removeValueFromRenderState, sortNodePosition = _a2.sortNodePosition, scrapeMotionValuesFromProps2 = _a2.scrapeMotionValuesFromProps;
  return function(_a3, options) {
    var parent = _a3.parent, props2 = _a3.props, presenceId2 = _a3.presenceId, blockInitialAnimation = _a3.blockInitialAnimation, visualState = _a3.visualState;
    if (options === void 0) {
      options = {};
    }
    var isMounted = false;
    var latestValues = visualState.latestValues, renderState = visualState.renderState;
    var instance;
    var lifecycles = createLifecycles();
    var values = /* @__PURE__ */ new Map();
    var valueSubscriptions = /* @__PURE__ */ new Map();
    var prevMotionValues = {};
    var baseTarget = __assign({}, latestValues);
    var removeFromVariantTree;
    function render() {
      if (!instance || !isMounted)
        return;
      triggerBuild();
      renderInstance(instance, renderState, props2.style, element.projection);
    }
    function triggerBuild() {
      build(element, renderState, latestValues, options, props2);
    }
    function update() {
      lifecycles.notifyUpdate(latestValues);
    }
    function bindToMotionValue(key2, value2) {
      var removeOnChange = value2.onChange(function(latestValue) {
        latestValues[key2] = latestValue;
        props2.onUpdate && sync.update(update, false, true);
      });
      var removeOnRenderRequest = value2.onRenderRequest(element.scheduleRender);
      valueSubscriptions.set(key2, function() {
        removeOnChange();
        removeOnRenderRequest();
      });
    }
    var initialMotionValues = scrapeMotionValuesFromProps2(props2);
    for (var key in initialMotionValues) {
      var value = initialMotionValues[key];
      if (latestValues[key] !== void 0 && isMotionValue(value)) {
        value.set(latestValues[key], false);
      }
    }
    var isControllingVariants = checkIfControllingVariants(props2);
    var isVariantNode = checkIfVariantNode(props2);
    var element = __assign(__assign({
      treeType,
      current: null,
      depth: parent ? parent.depth + 1 : 0,
      parent,
      children: /* @__PURE__ */ new Set(),
      presenceId: presenceId2,
      variantChildren: isVariantNode ? /* @__PURE__ */ new Set() : void 0,
      isVisible: void 0,
      manuallyAnimateOnMount: Boolean(parent === null || parent === void 0 ? void 0 : parent.isMounted()),
      blockInitialAnimation,
      isMounted: function() {
        return Boolean(instance);
      },
      mount: function(newInstance) {
        isMounted = true;
        instance = element.current = newInstance;
        if (element.projection) {
          element.projection.mount(newInstance);
        }
        if (isVariantNode && parent && !isControllingVariants) {
          removeFromVariantTree = parent === null || parent === void 0 ? void 0 : parent.addVariantChild(element);
        }
        parent === null || parent === void 0 ? void 0 : parent.children.add(element);
        element.setProps(props2);
      },
      unmount: function() {
        var _a4;
        (_a4 = element.projection) === null || _a4 === void 0 ? void 0 : _a4.unmount();
        cancelSync.update(update);
        cancelSync.render(render);
        valueSubscriptions.forEach(function(remove) {
          return remove();
        });
        removeFromVariantTree === null || removeFromVariantTree === void 0 ? void 0 : removeFromVariantTree();
        parent === null || parent === void 0 ? void 0 : parent.children.delete(element);
        lifecycles.clearAllListeners();
        instance = void 0;
        isMounted = false;
      },
      addVariantChild: function(child) {
        var _a4;
        var closestVariantNode = element.getClosestVariantNode();
        if (closestVariantNode) {
          (_a4 = closestVariantNode.variantChildren) === null || _a4 === void 0 ? void 0 : _a4.add(child);
          return function() {
            return closestVariantNode.variantChildren.delete(child);
          };
        }
      },
      sortNodePosition: function(other) {
        if (!sortNodePosition || treeType !== other.treeType)
          return 0;
        return sortNodePosition(element.getInstance(), other.getInstance());
      },
      getClosestVariantNode: function() {
        return isVariantNode ? element : parent === null || parent === void 0 ? void 0 : parent.getClosestVariantNode();
      },
      getLayoutId: function() {
        return props2.layoutId;
      },
      getInstance: function() {
        return instance;
      },
      getStaticValue: function(key2) {
        return latestValues[key2];
      },
      setStaticValue: function(key2, value2) {
        return latestValues[key2] = value2;
      },
      getLatestValues: function() {
        return latestValues;
      },
      setVisibility: function(visibility) {
        if (element.isVisible === visibility)
          return;
        element.isVisible = visibility;
        element.scheduleRender();
      },
      makeTargetAnimatable: function(target, canMutate) {
        if (canMutate === void 0) {
          canMutate = true;
        }
        return makeTargetAnimatable(element, target, props2, canMutate);
      },
      measureViewportBox: function() {
        return measureViewportBox2(instance, props2);
      },
      addValue: function(key2, value2) {
        if (element.hasValue(key2))
          element.removeValue(key2);
        values.set(key2, value2);
        latestValues[key2] = value2.get();
        bindToMotionValue(key2, value2);
      },
      removeValue: function(key2) {
        var _a4;
        values.delete(key2);
        (_a4 = valueSubscriptions.get(key2)) === null || _a4 === void 0 ? void 0 : _a4();
        valueSubscriptions.delete(key2);
        delete latestValues[key2];
        removeValueFromRenderState(key2, renderState);
      },
      hasValue: function(key2) {
        return values.has(key2);
      },
      getValue: function(key2, defaultValue) {
        var value2 = values.get(key2);
        if (value2 === void 0 && defaultValue !== void 0) {
          value2 = motionValue(defaultValue);
          element.addValue(key2, value2);
        }
        return value2;
      },
      forEachValue: function(callback) {
        return values.forEach(callback);
      },
      readValue: function(key2) {
        var _a4;
        return (_a4 = latestValues[key2]) !== null && _a4 !== void 0 ? _a4 : readValueFromInstance(instance, key2, options);
      },
      setBaseTarget: function(key2, value2) {
        baseTarget[key2] = value2;
      },
      getBaseTarget: function(key2) {
        if (getBaseTarget) {
          var target = getBaseTarget(props2, key2);
          if (target !== void 0 && !isMotionValue(target))
            return target;
        }
        return baseTarget[key2];
      }
    }, lifecycles), {
      build: function() {
        triggerBuild();
        return renderState;
      },
      scheduleRender: function() {
        sync.render(render, false, true);
      },
      syncRender: render,
      setProps: function(newProps) {
        if (newProps.transformTemplate || props2.transformTemplate) {
          element.scheduleRender();
        }
        props2 = newProps;
        lifecycles.updatePropListeners(newProps);
        prevMotionValues = updateMotionValuesFromProps(element, scrapeMotionValuesFromProps2(props2), prevMotionValues);
      },
      getProps: function() {
        return props2;
      },
      getVariant: function(name) {
        var _a4;
        return (_a4 = props2.variants) === null || _a4 === void 0 ? void 0 : _a4[name];
      },
      getDefaultTransition: function() {
        return props2.transition;
      },
      getTransformPagePoint: function() {
        return props2.transformPagePoint;
      },
      getVariantContext: function(startAtParent) {
        if (startAtParent === void 0) {
          startAtParent = false;
        }
        if (startAtParent)
          return parent === null || parent === void 0 ? void 0 : parent.getVariantContext();
        if (!isControllingVariants) {
          var context_1 = (parent === null || parent === void 0 ? void 0 : parent.getVariantContext()) || {};
          if (props2.initial !== void 0) {
            context_1.initial = props2.initial;
          }
          return context_1;
        }
        var context = {};
        for (var i2 = 0; i2 < numVariantProps; i2++) {
          var name_1 = variantProps[i2];
          var prop = props2[name_1];
          if (isVariantLabel(prop) || prop === false) {
            context[name_1] = prop;
          }
        }
        return context;
      }
    });
    return element;
  };
};
var variantProps = __spreadArray(["initial"], __read(variantPriorityOrder), false);
var numVariantProps = variantProps.length;
function isCSSVariable(value) {
  return typeof value === "string" && value.startsWith("var(--");
}
var cssVariableRegex = /var\((--[a-zA-Z0-9-_]+),? ?([a-zA-Z0-9 ()%#.,-]+)?\)/;
function parseCSSVariable(current) {
  var match = cssVariableRegex.exec(current);
  if (!match)
    return [,];
  var _a2 = __read(match, 3), token = _a2[1], fallback = _a2[2];
  return [token, fallback];
}
function getVariableValue(current, element, depth) {
  var _a2 = __read(parseCSSVariable(current), 2), token = _a2[0], fallback = _a2[1];
  if (!token)
    return;
  var resolved = window.getComputedStyle(element).getPropertyValue(token);
  if (resolved) {
    return resolved.trim();
  } else if (isCSSVariable(fallback)) {
    return getVariableValue(fallback, element);
  } else {
    return fallback;
  }
}
function resolveCSSVariables(visualElement2, _a2, transitionEnd2) {
  var _b;
  var target = __rest(_a2, []);
  var element = visualElement2.getInstance();
  if (!(element instanceof Element))
    return { target, transitionEnd: transitionEnd2 };
  if (transitionEnd2) {
    transitionEnd2 = __assign({}, transitionEnd2);
  }
  visualElement2.forEachValue(function(value) {
    var current2 = value.get();
    if (!isCSSVariable(current2))
      return;
    var resolved2 = getVariableValue(current2, element);
    if (resolved2)
      value.set(resolved2);
  });
  for (var key in target) {
    var current = target[key];
    if (!isCSSVariable(current))
      continue;
    var resolved = getVariableValue(current, element);
    if (!resolved)
      continue;
    target[key] = resolved;
    if (transitionEnd2)
      (_b = transitionEnd2[key]) !== null && _b !== void 0 ? _b : transitionEnd2[key] = current;
  }
  return { target, transitionEnd: transitionEnd2 };
}
var positionalKeys = /* @__PURE__ */ new Set([
  "width",
  "height",
  "top",
  "left",
  "right",
  "bottom",
  "x",
  "y"
]);
var isPositionalKey = function(key) {
  return positionalKeys.has(key);
};
var hasPositionalKey = function(target) {
  return Object.keys(target).some(isPositionalKey);
};
var setAndResetVelocity = function(value, to) {
  value.set(to, false);
  value.set(to);
};
var isNumOrPxType = function(v2) {
  return v2 === number || v2 === px;
};
var BoundingBoxDimension;
(function(BoundingBoxDimension2) {
  BoundingBoxDimension2["width"] = "width";
  BoundingBoxDimension2["height"] = "height";
  BoundingBoxDimension2["left"] = "left";
  BoundingBoxDimension2["right"] = "right";
  BoundingBoxDimension2["top"] = "top";
  BoundingBoxDimension2["bottom"] = "bottom";
})(BoundingBoxDimension || (BoundingBoxDimension = {}));
var getPosFromMatrix = function(matrix, pos) {
  return parseFloat(matrix.split(", ")[pos]);
};
var getTranslateFromMatrix = function(pos2, pos3) {
  return function(_bbox, _a2) {
    var transform2 = _a2.transform;
    if (transform2 === "none" || !transform2)
      return 0;
    var matrix3d = transform2.match(/^matrix3d\((.+)\)$/);
    if (matrix3d) {
      return getPosFromMatrix(matrix3d[1], pos3);
    } else {
      var matrix = transform2.match(/^matrix\((.+)\)$/);
      if (matrix) {
        return getPosFromMatrix(matrix[1], pos2);
      } else {
        return 0;
      }
    }
  };
};
var transformKeys = /* @__PURE__ */ new Set(["x", "y", "z"]);
var nonTranslationalTransformKeys = transformProps.filter(function(key) {
  return !transformKeys.has(key);
});
function removeNonTranslationalTransform(visualElement2) {
  var removedTransforms = [];
  nonTranslationalTransformKeys.forEach(function(key) {
    var value = visualElement2.getValue(key);
    if (value !== void 0) {
      removedTransforms.push([key, value.get()]);
      value.set(key.startsWith("scale") ? 1 : 0);
    }
  });
  if (removedTransforms.length)
    visualElement2.syncRender();
  return removedTransforms;
}
var positionalValues = {
  width: function(_a2, _b) {
    var x2 = _a2.x;
    var _c = _b.paddingLeft, paddingLeft = _c === void 0 ? "0" : _c, _d = _b.paddingRight, paddingRight = _d === void 0 ? "0" : _d;
    return x2.max - x2.min - parseFloat(paddingLeft) - parseFloat(paddingRight);
  },
  height: function(_a2, _b) {
    var y2 = _a2.y;
    var _c = _b.paddingTop, paddingTop = _c === void 0 ? "0" : _c, _d = _b.paddingBottom, paddingBottom = _d === void 0 ? "0" : _d;
    return y2.max - y2.min - parseFloat(paddingTop) - parseFloat(paddingBottom);
  },
  top: function(_bbox, _a2) {
    var top = _a2.top;
    return parseFloat(top);
  },
  left: function(_bbox, _a2) {
    var left = _a2.left;
    return parseFloat(left);
  },
  bottom: function(_a2, _b) {
    var y2 = _a2.y;
    var top = _b.top;
    return parseFloat(top) + (y2.max - y2.min);
  },
  right: function(_a2, _b) {
    var x2 = _a2.x;
    var left = _b.left;
    return parseFloat(left) + (x2.max - x2.min);
  },
  x: getTranslateFromMatrix(4, 13),
  y: getTranslateFromMatrix(5, 14)
};
var convertChangedValueTypes = function(target, visualElement2, changedKeys) {
  var originBbox = visualElement2.measureViewportBox();
  var element = visualElement2.getInstance();
  var elementComputedStyle = getComputedStyle(element);
  var display = elementComputedStyle.display;
  var origin = {};
  if (display === "none") {
    visualElement2.setStaticValue("display", target.display || "block");
  }
  changedKeys.forEach(function(key) {
    origin[key] = positionalValues[key](originBbox, elementComputedStyle);
  });
  visualElement2.syncRender();
  var targetBbox = visualElement2.measureViewportBox();
  changedKeys.forEach(function(key) {
    var value = visualElement2.getValue(key);
    setAndResetVelocity(value, origin[key]);
    target[key] = positionalValues[key](targetBbox, elementComputedStyle);
  });
  return target;
};
var checkAndConvertChangedValueTypes = function(visualElement2, target, origin, transitionEnd2) {
  if (origin === void 0) {
    origin = {};
  }
  if (transitionEnd2 === void 0) {
    transitionEnd2 = {};
  }
  target = __assign({}, target);
  transitionEnd2 = __assign({}, transitionEnd2);
  var targetPositionalKeys = Object.keys(target).filter(isPositionalKey);
  var removedTransformValues = [];
  var hasAttemptedToRemoveTransformValues = false;
  var changedValueTypeKeys = [];
  targetPositionalKeys.forEach(function(key) {
    var value = visualElement2.getValue(key);
    if (!visualElement2.hasValue(key))
      return;
    var from = origin[key];
    var fromType = findDimensionValueType(from);
    var to = target[key];
    var toType;
    if (isKeyframesTarget(to)) {
      var numKeyframes = to.length;
      var fromIndex = to[0] === null ? 1 : 0;
      from = to[fromIndex];
      fromType = findDimensionValueType(from);
      for (var i2 = fromIndex; i2 < numKeyframes; i2++) {
        if (!toType) {
          toType = findDimensionValueType(to[i2]);
        } else {
          invariant(findDimensionValueType(to[i2]) === toType);
        }
      }
    } else {
      toType = findDimensionValueType(to);
    }
    if (fromType !== toType) {
      if (isNumOrPxType(fromType) && isNumOrPxType(toType)) {
        var current = value.get();
        if (typeof current === "string") {
          value.set(parseFloat(current));
        }
        if (typeof to === "string") {
          target[key] = parseFloat(to);
        } else if (Array.isArray(to) && toType === px) {
          target[key] = to.map(parseFloat);
        }
      } else if ((fromType === null || fromType === void 0 ? void 0 : fromType.transform) && (toType === null || toType === void 0 ? void 0 : toType.transform) && (from === 0 || to === 0)) {
        if (from === 0) {
          value.set(toType.transform(from));
        } else {
          target[key] = fromType.transform(to);
        }
      } else {
        if (!hasAttemptedToRemoveTransformValues) {
          removedTransformValues = removeNonTranslationalTransform(visualElement2);
          hasAttemptedToRemoveTransformValues = true;
        }
        changedValueTypeKeys.push(key);
        transitionEnd2[key] = transitionEnd2[key] !== void 0 ? transitionEnd2[key] : target[key];
        setAndResetVelocity(value, to);
      }
    }
  });
  if (changedValueTypeKeys.length) {
    var convertedTarget = convertChangedValueTypes(target, visualElement2, changedValueTypeKeys);
    if (removedTransformValues.length) {
      removedTransformValues.forEach(function(_a2) {
        var _b = __read(_a2, 2), key = _b[0], value = _b[1];
        visualElement2.getValue(key).set(value);
      });
    }
    visualElement2.syncRender();
    return { target: convertedTarget, transitionEnd: transitionEnd2 };
  } else {
    return { target, transitionEnd: transitionEnd2 };
  }
};
function unitConversion(visualElement2, target, origin, transitionEnd2) {
  return hasPositionalKey(target) ? checkAndConvertChangedValueTypes(visualElement2, target, origin, transitionEnd2) : { target, transitionEnd: transitionEnd2 };
}
var parseDomVariant = function(visualElement2, target, origin, transitionEnd2) {
  var resolved = resolveCSSVariables(visualElement2, target, transitionEnd2);
  target = resolved.target;
  transitionEnd2 = resolved.transitionEnd;
  return unitConversion(visualElement2, target, origin, transitionEnd2);
};
function getComputedStyle$2(element) {
  return window.getComputedStyle(element);
}
var htmlConfig = {
  treeType: "dom",
  readValueFromInstance: function(domElement, key) {
    if (isTransformProp(key)) {
      var defaultType = getDefaultValueType(key);
      return defaultType ? defaultType.default || 0 : 0;
    } else {
      var computedStyle = getComputedStyle$2(domElement);
      return (isCSSVariable$1(key) ? computedStyle.getPropertyValue(key) : computedStyle[key]) || 0;
    }
  },
  sortNodePosition: function(a2, b2) {
    return a2.compareDocumentPosition(b2) & 2 ? 1 : -1;
  },
  getBaseTarget: function(props2, key) {
    var _a2;
    return (_a2 = props2.style) === null || _a2 === void 0 ? void 0 : _a2[key];
  },
  measureViewportBox: function(element, _a2) {
    var transformPagePoint = _a2.transformPagePoint;
    return measureViewportBox(element, transformPagePoint);
  },
  resetTransform: function(element, domElement, props2) {
    var transformTemplate = props2.transformTemplate;
    domElement.style.transform = transformTemplate ? transformTemplate({}, "") : "none";
    element.scheduleRender();
  },
  restoreTransform: function(instance, mutableState) {
    instance.style.transform = mutableState.style.transform;
  },
  removeValueFromRenderState: function(key, _a2) {
    var vars = _a2.vars, style2 = _a2.style;
    delete vars[key];
    delete style2[key];
  },
  makeTargetAnimatable: function(element, _a2, _b, isMounted) {
    var transformValues = _b.transformValues;
    if (isMounted === void 0) {
      isMounted = true;
    }
    var transition = _a2.transition, transitionEnd2 = _a2.transitionEnd, target = __rest(_a2, ["transition", "transitionEnd"]);
    var origin = getOrigin(target, transition || {}, element);
    if (transformValues) {
      if (transitionEnd2)
        transitionEnd2 = transformValues(transitionEnd2);
      if (target)
        target = transformValues(target);
      if (origin)
        origin = transformValues(origin);
    }
    if (isMounted) {
      checkTargetForNewValues(element, target, origin);
      var parsed = parseDomVariant(element, target, origin, transitionEnd2);
      transitionEnd2 = parsed.transitionEnd;
      target = parsed.target;
    }
    return __assign({ transition, transitionEnd: transitionEnd2 }, target);
  },
  scrapeMotionValuesFromProps: scrapeMotionValuesFromProps$1,
  build: function(element, renderState, latestValues, options, props2) {
    if (element.isVisible !== void 0) {
      renderState.style.visibility = element.isVisible ? "visible" : "hidden";
    }
    buildHTMLStyles(renderState, latestValues, options, props2.transformTemplate);
  },
  render: renderHTML
};
var htmlVisualElement = visualElement(htmlConfig);
var svgVisualElement = visualElement(__assign(__assign({}, htmlConfig), { getBaseTarget: function(props2, key) {
  return props2[key];
}, readValueFromInstance: function(domElement, key) {
  var _a2;
  if (isTransformProp(key)) {
    return ((_a2 = getDefaultValueType(key)) === null || _a2 === void 0 ? void 0 : _a2.default) || 0;
  }
  key = !camelCaseAttributes.has(key) ? camelToDash(key) : key;
  return domElement.getAttribute(key);
}, scrapeMotionValuesFromProps, build: function(_element, renderState, latestValues, options, props2) {
  buildSVGAttrs(renderState, latestValues, options, props2.transformTemplate);
}, render: renderSVG }));
var createDomVisualElement = function(Component, options) {
  return isSVGComponent(Component) ? svgVisualElement(options, { enableHardwareAcceleration: false }) : htmlVisualElement(options, { enableHardwareAcceleration: true });
};
var m$2 = createMotionProxy(createDomMotionConfig);
function useForceUpdate() {
  var isUnmountingRef = useRef(false);
  var _a2 = __read(useState(0), 2), forcedRenderCount = _a2[0], setForcedRenderCount = _a2[1];
  useUnmountEffect(function() {
    return isUnmountingRef.current = true;
  });
  var forceRender = useCallback(function() {
    !isUnmountingRef.current && setForcedRenderCount(forcedRenderCount + 1);
  }, [forcedRenderCount]);
  var deferredForceRender = useCallback(function() {
    return sync.postRender(forceRender);
  }, [forceRender]);
  return [deferredForceRender, forcedRenderCount];
}
var presenceId = 0;
function getPresenceId() {
  var id2 = presenceId;
  presenceId++;
  return id2;
}
var PresenceChild = function(_a2) {
  var children = _a2.children, initial = _a2.initial, isPresent = _a2.isPresent, onExitComplete = _a2.onExitComplete, custom = _a2.custom, presenceAffectsLayout = _a2.presenceAffectsLayout;
  var presenceChildren = useConstant(newChildrenMap);
  var id2 = useConstant(getPresenceId);
  var context = useMemo(function() {
    return {
      id: id2,
      initial,
      isPresent,
      custom,
      onExitComplete: function(childId) {
        var e_1, _a3;
        presenceChildren.set(childId, true);
        try {
          for (var _b = __values(presenceChildren.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
            var isComplete = _c.value;
            if (!isComplete)
              return;
          }
        } catch (e_1_1) {
          e_1 = { error: e_1_1 };
        } finally {
          try {
            if (_c && !_c.done && (_a3 = _b.return))
              _a3.call(_b);
          } finally {
            if (e_1)
              throw e_1.error;
          }
        }
        onExitComplete === null || onExitComplete === void 0 ? void 0 : onExitComplete();
      },
      register: function(childId) {
        presenceChildren.set(childId, false);
        return function() {
          return presenceChildren.delete(childId);
        };
      }
    };
  }, presenceAffectsLayout ? void 0 : [isPresent]);
  useMemo(function() {
    presenceChildren.forEach(function(_2, key) {
      return presenceChildren.set(key, false);
    });
  }, [isPresent]);
  React.useEffect(function() {
    !isPresent && !presenceChildren.size && (onExitComplete === null || onExitComplete === void 0 ? void 0 : onExitComplete());
  }, [isPresent]);
  return React__default.createElement(PresenceContext.Provider, { value: context }, children);
};
function newChildrenMap() {
  return /* @__PURE__ */ new Map();
}
function getChildKey(child) {
  return child.key || "";
}
function updateChildLookup(children, allChildren) {
  children.forEach(function(child) {
    var key = getChildKey(child);
    allChildren.set(key, child);
  });
}
function onlyElements(children) {
  var filtered = [];
  Children.forEach(children, function(child) {
    if (isValidElement(child))
      filtered.push(child);
  });
  return filtered;
}
var AnimatePresence = function(_a2) {
  var children = _a2.children, custom = _a2.custom, _b = _a2.initial, initial = _b === void 0 ? true : _b, onExitComplete = _a2.onExitComplete, exitBeforeEnter = _a2.exitBeforeEnter, _c = _a2.presenceAffectsLayout, presenceAffectsLayout = _c === void 0 ? true : _c;
  var _d = __read(useForceUpdate(), 1), forceRender = _d[0];
  var forceRenderLayoutGroup = useContext(LayoutGroupContext).forceRender;
  if (forceRenderLayoutGroup)
    forceRender = forceRenderLayoutGroup;
  var isInitialRender = useRef(true);
  var isMounted = useRef(true);
  useEffect(function() {
    return function() {
      isMounted.current = false;
    };
  }, []);
  var filteredChildren = onlyElements(children);
  var presentChildren = useRef(filteredChildren);
  var allChildren = useRef(/* @__PURE__ */ new Map()).current;
  var exiting = useRef(/* @__PURE__ */ new Set()).current;
  updateChildLookup(filteredChildren, allChildren);
  if (isInitialRender.current) {
    isInitialRender.current = false;
    return React__default.createElement(React__default.Fragment, null, filteredChildren.map(function(child) {
      return React__default.createElement(PresenceChild, { key: getChildKey(child), isPresent: true, initial: initial ? void 0 : false, presenceAffectsLayout }, child);
    }));
  }
  var childrenToRender = __spreadArray([], __read(filteredChildren), false);
  var presentKeys = presentChildren.current.map(getChildKey);
  var targetKeys = filteredChildren.map(getChildKey);
  var numPresent = presentKeys.length;
  for (var i2 = 0; i2 < numPresent; i2++) {
    var key = presentKeys[i2];
    if (targetKeys.indexOf(key) === -1) {
      exiting.add(key);
    } else {
      exiting.delete(key);
    }
  }
  if (exitBeforeEnter && exiting.size) {
    childrenToRender = [];
  }
  exiting.forEach(function(key2) {
    if (targetKeys.indexOf(key2) !== -1)
      return;
    var child = allChildren.get(key2);
    if (!child)
      return;
    var insertionIndex = presentKeys.indexOf(key2);
    var onExit = function() {
      allChildren.delete(key2);
      exiting.delete(key2);
      var removeIndex = presentChildren.current.findIndex(function(presentChild) {
        return presentChild.key === key2;
      });
      presentChildren.current.splice(removeIndex, 1);
      if (!exiting.size) {
        presentChildren.current = filteredChildren;
        if (isMounted.current === false) {
          return;
        }
        forceRender();
        onExitComplete && onExitComplete();
      }
    };
    childrenToRender.splice(insertionIndex, 0, React__default.createElement(PresenceChild, { key: getChildKey(child), isPresent: false, onExitComplete: onExit, custom, presenceAffectsLayout }, child));
  });
  childrenToRender = childrenToRender.map(function(child) {
    var key2 = child.key;
    return exiting.has(key2) ? child : React__default.createElement(PresenceChild, { key: getChildKey(child), isPresent: true, presenceAffectsLayout }, child);
  });
  presentChildren.current = childrenToRender;
  return React__default.createElement(React__default.Fragment, null, exiting.size ? childrenToRender : childrenToRender.map(function(child) {
    return cloneElement(child);
  }));
};
function LazyMotion(_a2) {
  var children = _a2.children, features = _a2.features, _b = _a2.strict, strict = _b === void 0 ? false : _b;
  var _c = __read(useState(!isLazyBundle(features)), 2), setIsLoaded = _c[1];
  var loadedRenderer = useRef(void 0);
  if (!isLazyBundle(features)) {
    var renderer = features.renderer, loadedFeatures = __rest(features, ["renderer"]);
    loadedRenderer.current = renderer;
    loadFeatures(loadedFeatures);
  }
  useEffect(function() {
    if (isLazyBundle(features)) {
      features().then(function(_a3) {
        var renderer2 = _a3.renderer, loadedFeatures2 = __rest(_a3, ["renderer"]);
        loadFeatures(loadedFeatures2);
        loadedRenderer.current = renderer2;
        setIsLoaded(true);
      });
    }
  }, []);
  return React__default.createElement(LazyContext.Provider, { value: { renderer: loadedRenderer.current, strict } }, children);
}
function isLazyBundle(features) {
  return typeof features === "function";
}
var domAnimation = __assign(__assign({ renderer: createDomVisualElement }, animations), gestureAnimations);
var propTypes = { exports: {} };
var ReactPropTypesSecret$1 = "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";
var ReactPropTypesSecret_1 = ReactPropTypesSecret$1;
var ReactPropTypesSecret = ReactPropTypesSecret_1;
function emptyFunction() {
}
function emptyFunctionWithReset() {
}
emptyFunctionWithReset.resetWarningCache = emptyFunction;
var factoryWithThrowingShims = function() {
  function shim(props2, propName, componentName, location2, propFullName, secret) {
    if (secret === ReactPropTypesSecret) {
      return;
    }
    var err = new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");
    err.name = "Invariant Violation";
    throw err;
  }
  shim.isRequired = shim;
  function getShim() {
    return shim;
  }
  var ReactPropTypes = {
    array: shim,
    bigint: shim,
    bool: shim,
    func: shim,
    number: shim,
    object: shim,
    string: shim,
    symbol: shim,
    any: shim,
    arrayOf: getShim,
    element: shim,
    elementType: shim,
    instanceOf: getShim,
    node: shim,
    objectOf: getShim,
    oneOf: getShim,
    oneOfType: getShim,
    shape: getShim,
    exact: getShim,
    checkPropTypes: emptyFunctionWithReset,
    resetWarningCache: emptyFunction
  };
  ReactPropTypes.PropTypes = ReactPropTypes;
  return ReactPropTypes;
};
{
  propTypes.exports = factoryWithThrowingShims();
}
var PropTypes = propTypes.exports;
var COMMON_MIME_TYPES = /* @__PURE__ */ new Map([
  ["aac", "audio/aac"],
  ["abw", "application/x-abiword"],
  ["arc", "application/x-freearc"],
  ["avif", "image/avif"],
  ["avi", "video/x-msvideo"],
  ["azw", "application/vnd.amazon.ebook"],
  ["bin", "application/octet-stream"],
  ["bmp", "image/bmp"],
  ["bz", "application/x-bzip"],
  ["bz2", "application/x-bzip2"],
  ["cda", "application/x-cdf"],
  ["csh", "application/x-csh"],
  ["css", "text/css"],
  ["csv", "text/csv"],
  ["doc", "application/msword"],
  ["docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"],
  ["eot", "application/vnd.ms-fontobject"],
  ["epub", "application/epub+zip"],
  ["gz", "application/gzip"],
  ["gif", "image/gif"],
  ["htm", "text/html"],
  ["html", "text/html"],
  ["ico", "image/vnd.microsoft.icon"],
  ["ics", "text/calendar"],
  ["jar", "application/java-archive"],
  ["jpeg", "image/jpeg"],
  ["jpg", "image/jpeg"],
  ["js", "text/javascript"],
  ["json", "application/json"],
  ["jsonld", "application/ld+json"],
  ["mid", "audio/midi"],
  ["midi", "audio/midi"],
  ["mjs", "text/javascript"],
  ["mp3", "audio/mpeg"],
  ["mp4", "video/mp4"],
  ["mpeg", "video/mpeg"],
  ["mpkg", "application/vnd.apple.installer+xml"],
  ["odp", "application/vnd.oasis.opendocument.presentation"],
  ["ods", "application/vnd.oasis.opendocument.spreadsheet"],
  ["odt", "application/vnd.oasis.opendocument.text"],
  ["oga", "audio/ogg"],
  ["ogv", "video/ogg"],
  ["ogx", "application/ogg"],
  ["opus", "audio/opus"],
  ["otf", "font/otf"],
  ["png", "image/png"],
  ["pdf", "application/pdf"],
  ["php", "application/x-httpd-php"],
  ["ppt", "application/vnd.ms-powerpoint"],
  ["pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"],
  ["rar", "application/vnd.rar"],
  ["rtf", "application/rtf"],
  ["sh", "application/x-sh"],
  ["svg", "image/svg+xml"],
  ["swf", "application/x-shockwave-flash"],
  ["tar", "application/x-tar"],
  ["tif", "image/tiff"],
  ["tiff", "image/tiff"],
  ["ts", "video/mp2t"],
  ["ttf", "font/ttf"],
  ["txt", "text/plain"],
  ["vsd", "application/vnd.visio"],
  ["wav", "audio/wav"],
  ["weba", "audio/webm"],
  ["webm", "video/webm"],
  ["webp", "image/webp"],
  ["woff", "font/woff"],
  ["woff2", "font/woff2"],
  ["xhtml", "application/xhtml+xml"],
  ["xls", "application/vnd.ms-excel"],
  ["xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],
  ["xml", "application/xml"],
  ["xul", "application/vnd.mozilla.xul+xml"],
  ["zip", "application/zip"],
  ["7z", "application/x-7z-compressed"],
  ["mkv", "video/x-matroska"],
  ["mov", "video/quicktime"],
  ["msg", "application/vnd.ms-outlook"]
]);
function toFileWithPath(file, path) {
  var f2 = withMimeType(file);
  if (typeof f2.path !== "string") {
    var webkitRelativePath = file.webkitRelativePath;
    Object.defineProperty(f2, "path", {
      value: typeof path === "string" ? path : typeof webkitRelativePath === "string" && webkitRelativePath.length > 0 ? webkitRelativePath : file.name,
      writable: false,
      configurable: false,
      enumerable: true
    });
  }
  return f2;
}
function withMimeType(file) {
  var name = file.name;
  var hasExtension = name && name.lastIndexOf(".") !== -1;
  if (hasExtension && !file.type) {
    var ext = name.split(".").pop().toLowerCase();
    var type = COMMON_MIME_TYPES.get(ext);
    if (type) {
      Object.defineProperty(file, "type", {
        value: type,
        writable: false,
        configurable: false,
        enumerable: true
      });
    }
  }
  return file;
}
var FILES_TO_IGNORE = [
  ".DS_Store",
  "Thumbs.db"
];
function fromEvent(evt) {
  return __awaiter(this, void 0, void 0, function() {
    return __generator(this, function(_a2) {
      if (isObject(evt) && isDataTransfer(evt)) {
        return [2, getDataTransferFiles(evt.dataTransfer, evt.type)];
      } else if (isChangeEvt(evt)) {
        return [2, getInputFiles(evt)];
      } else if (Array.isArray(evt) && evt.every(function(item) {
        return "getFile" in item && typeof item.getFile === "function";
      })) {
        return [2, getFsHandleFiles(evt)];
      }
      return [2, []];
    });
  });
}
function isDataTransfer(value) {
  return isObject(value.dataTransfer);
}
function isChangeEvt(value) {
  return isObject(value) && isObject(value.target);
}
function isObject(v2) {
  return typeof v2 === "object" && v2 !== null;
}
function getInputFiles(evt) {
  return fromList(evt.target.files).map(function(file) {
    return toFileWithPath(file);
  });
}
function getFsHandleFiles(handles) {
  return __awaiter(this, void 0, void 0, function() {
    var files2;
    return __generator(this, function(_a2) {
      switch (_a2.label) {
        case 0:
          return [4, Promise.all(handles.map(function(h2) {
            return h2.getFile();
          }))];
        case 1:
          files2 = _a2.sent();
          return [2, files2.map(function(file) {
            return toFileWithPath(file);
          })];
      }
    });
  });
}
function getDataTransferFiles(dt, type) {
  return __awaiter(this, void 0, void 0, function() {
    var items, files2;
    return __generator(this, function(_a2) {
      switch (_a2.label) {
        case 0:
          if (dt === null) {
            return [2, []];
          }
          if (!dt.items)
            return [3, 2];
          items = fromList(dt.items).filter(function(item) {
            return item.kind === "file";
          });
          if (type !== "drop") {
            return [2, items];
          }
          return [4, Promise.all(items.map(toFilePromises))];
        case 1:
          files2 = _a2.sent();
          return [2, noIgnoredFiles(flatten(files2))];
        case 2:
          return [2, noIgnoredFiles(fromList(dt.files).map(function(file) {
            return toFileWithPath(file);
          }))];
      }
    });
  });
}
function noIgnoredFiles(files2) {
  return files2.filter(function(file) {
    return FILES_TO_IGNORE.indexOf(file.name) === -1;
  });
}
function fromList(items) {
  if (items === null) {
    return [];
  }
  var files2 = [];
  for (var i2 = 0; i2 < items.length; i2++) {
    var file = items[i2];
    files2.push(file);
  }
  return files2;
}
function toFilePromises(item) {
  if (typeof item.webkitGetAsEntry !== "function") {
    return fromDataTransferItem(item);
  }
  var entry = item.webkitGetAsEntry();
  if (entry && entry.isDirectory) {
    return fromDirEntry(entry);
  }
  return fromDataTransferItem(item);
}
function flatten(items) {
  return items.reduce(function(acc, files2) {
    return __spread(acc, Array.isArray(files2) ? flatten(files2) : [files2]);
  }, []);
}
function fromDataTransferItem(item) {
  var file = item.getAsFile();
  if (!file) {
    return Promise.reject(item + " is not a File");
  }
  var fwp = toFileWithPath(file);
  return Promise.resolve(fwp);
}
function fromEntry(entry) {
  return __awaiter(this, void 0, void 0, function() {
    return __generator(this, function(_a2) {
      return [2, entry.isDirectory ? fromDirEntry(entry) : fromFileEntry(entry)];
    });
  });
}
function fromDirEntry(entry) {
  var reader = entry.createReader();
  return new Promise(function(resolve, reject) {
    var entries = [];
    function readEntries() {
      var _this = this;
      reader.readEntries(function(batch) {
        return __awaiter(_this, void 0, void 0, function() {
          var files2, err_1, items;
          return __generator(this, function(_a2) {
            switch (_a2.label) {
              case 0:
                if (!!batch.length)
                  return [3, 5];
                _a2.label = 1;
              case 1:
                _a2.trys.push([1, 3, , 4]);
                return [4, Promise.all(entries)];
              case 2:
                files2 = _a2.sent();
                resolve(files2);
                return [3, 4];
              case 3:
                err_1 = _a2.sent();
                reject(err_1);
                return [3, 4];
              case 4:
                return [3, 6];
              case 5:
                items = Promise.all(batch.map(fromEntry));
                entries.push(items);
                readEntries();
                _a2.label = 6;
              case 6:
                return [2];
            }
          });
        });
      }, function(err) {
        reject(err);
      });
    }
    readEntries();
  });
}
function fromFileEntry(entry) {
  return __awaiter(this, void 0, void 0, function() {
    return __generator(this, function(_a2) {
      return [2, new Promise(function(resolve, reject) {
        entry.file(function(file) {
          var fwp = toFileWithPath(file, entry.fullPath);
          resolve(fwp);
        }, function(err) {
          reject(err);
        });
      })];
    });
  });
}
var _default$1 = function(file, acceptedFiles) {
  if (file && acceptedFiles) {
    var acceptedFilesArray = Array.isArray(acceptedFiles) ? acceptedFiles : acceptedFiles.split(",");
    var fileName = file.name || "";
    var mimeType = (file.type || "").toLowerCase();
    var baseMimeType = mimeType.replace(/\/.*$/, "");
    return acceptedFilesArray.some(function(type) {
      var validType = type.trim().toLowerCase();
      if (validType.charAt(0) === ".") {
        return fileName.toLowerCase().endsWith(validType);
      } else if (validType.endsWith("/*")) {
        return baseMimeType === validType.replace(/\/.*$/, "");
      }
      return mimeType === validType;
    });
  }
  return true;
};
function ownKeys$2(object, enumerableOnly) {
  var keys = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    enumerableOnly && (symbols = symbols.filter(function(sym) {
      return Object.getOwnPropertyDescriptor(object, sym).enumerable;
    })), keys.push.apply(keys, symbols);
  }
  return keys;
}
function _objectSpread$1(target) {
  for (var i2 = 1; i2 < arguments.length; i2++) {
    var source = arguments[i2] != null ? arguments[i2] : {};
    i2 % 2 ? ownKeys$2(Object(source), true).forEach(function(key) {
      _defineProperty$2(target, key, source[key]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$2(Object(source)).forEach(function(key) {
      Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
    });
  }
  return target;
}
function _defineProperty$2(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
function _slicedToArray$1(arr, i2) {
  return _arrayWithHoles$1(arr) || _iterableToArrayLimit$1(arr, i2) || _unsupportedIterableToArray$1(arr, i2) || _nonIterableRest$1();
}
function _nonIterableRest$1() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray$1(o2, minLen) {
  if (!o2)
    return;
  if (typeof o2 === "string")
    return _arrayLikeToArray$1(o2, minLen);
  var n2 = Object.prototype.toString.call(o2).slice(8, -1);
  if (n2 === "Object" && o2.constructor)
    n2 = o2.constructor.name;
  if (n2 === "Map" || n2 === "Set")
    return Array.from(o2);
  if (n2 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n2))
    return _arrayLikeToArray$1(o2, minLen);
}
function _arrayLikeToArray$1(arr, len) {
  if (len == null || len > arr.length)
    len = arr.length;
  for (var i2 = 0, arr2 = new Array(len); i2 < len; i2++) {
    arr2[i2] = arr[i2];
  }
  return arr2;
}
function _iterableToArrayLimit$1(arr, i2) {
  var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
  if (_i == null)
    return;
  var _arr = [];
  var _n = true;
  var _d = false;
  var _s, _e2;
  try {
    for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
      _arr.push(_s.value);
      if (i2 && _arr.length === i2)
        break;
    }
  } catch (err) {
    _d = true;
    _e2 = err;
  } finally {
    try {
      if (!_n && _i["return"] != null)
        _i["return"]();
    } finally {
      if (_d)
        throw _e2;
    }
  }
  return _arr;
}
function _arrayWithHoles$1(arr) {
  if (Array.isArray(arr))
    return arr;
}
var FILE_INVALID_TYPE = "file-invalid-type";
var FILE_TOO_LARGE = "file-too-large";
var FILE_TOO_SMALL = "file-too-small";
var TOO_MANY_FILES = "too-many-files";
var getInvalidTypeRejectionErr = function getInvalidTypeRejectionErr2(accept) {
  accept = Array.isArray(accept) && accept.length === 1 ? accept[0] : accept;
  var messageSuffix = Array.isArray(accept) ? "one of ".concat(accept.join(", ")) : accept;
  return {
    code: FILE_INVALID_TYPE,
    message: "File type must be ".concat(messageSuffix)
  };
};
var getTooLargeRejectionErr = function getTooLargeRejectionErr2(maxSize) {
  return {
    code: FILE_TOO_LARGE,
    message: "File is larger than ".concat(maxSize, " ").concat(maxSize === 1 ? "byte" : "bytes")
  };
};
var getTooSmallRejectionErr = function getTooSmallRejectionErr2(minSize) {
  return {
    code: FILE_TOO_SMALL,
    message: "File is smaller than ".concat(minSize, " ").concat(minSize === 1 ? "byte" : "bytes")
  };
};
var TOO_MANY_FILES_REJECTION = {
  code: TOO_MANY_FILES,
  message: "Too many files"
};
function fileAccepted(file, accept) {
  var isAcceptable = file.type === "application/x-moz-file" || _default$1(file, accept);
  return [isAcceptable, isAcceptable ? null : getInvalidTypeRejectionErr(accept)];
}
function fileMatchSize(file, minSize, maxSize) {
  if (isDefined(file.size)) {
    if (isDefined(minSize) && isDefined(maxSize)) {
      if (file.size > maxSize)
        return [false, getTooLargeRejectionErr(maxSize)];
      if (file.size < minSize)
        return [false, getTooSmallRejectionErr(minSize)];
    } else if (isDefined(minSize) && file.size < minSize)
      return [false, getTooSmallRejectionErr(minSize)];
    else if (isDefined(maxSize) && file.size > maxSize)
      return [false, getTooLargeRejectionErr(maxSize)];
  }
  return [true, null];
}
function isDefined(value) {
  return value !== void 0 && value !== null;
}
function allFilesAccepted(_ref) {
  var files2 = _ref.files, accept = _ref.accept, minSize = _ref.minSize, maxSize = _ref.maxSize, multiple = _ref.multiple, maxFiles = _ref.maxFiles;
  if (!multiple && files2.length > 1 || multiple && maxFiles >= 1 && files2.length > maxFiles) {
    return false;
  }
  return files2.every(function(file) {
    var _fileAccepted = fileAccepted(file, accept), _fileAccepted2 = _slicedToArray$1(_fileAccepted, 1), accepted = _fileAccepted2[0];
    var _fileMatchSize = fileMatchSize(file, minSize, maxSize), _fileMatchSize2 = _slicedToArray$1(_fileMatchSize, 1), sizeMatch = _fileMatchSize2[0];
    return accepted && sizeMatch;
  });
}
function isPropagationStopped(event) {
  if (typeof event.isPropagationStopped === "function") {
    return event.isPropagationStopped();
  } else if (typeof event.cancelBubble !== "undefined") {
    return event.cancelBubble;
  }
  return false;
}
function isEvtWithFiles(event) {
  if (!event.dataTransfer) {
    return !!event.target && !!event.target.files;
  }
  return Array.prototype.some.call(event.dataTransfer.types, function(type) {
    return type === "Files" || type === "application/x-moz-file";
  });
}
function onDocumentDragOver(event) {
  event.preventDefault();
}
function isIe(userAgent) {
  return userAgent.indexOf("MSIE") !== -1 || userAgent.indexOf("Trident/") !== -1;
}
function isEdge(userAgent) {
  return userAgent.indexOf("Edge/") !== -1;
}
function isIeOrEdge() {
  var userAgent = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : window.navigator.userAgent;
  return isIe(userAgent) || isEdge(userAgent);
}
function composeEventHandlers() {
  for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) {
    fns[_key] = arguments[_key];
  }
  return function(event) {
    for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
      args[_key2 - 1] = arguments[_key2];
    }
    return fns.some(function(fn2) {
      if (!isPropagationStopped(event) && fn2) {
        fn2.apply(void 0, [event].concat(args));
      }
      return isPropagationStopped(event);
    });
  };
}
function canUseFileSystemAccessAPI() {
  return "showOpenFilePicker" in window;
}
function filePickerOptionsTypes(accept) {
  accept = typeof accept === "string" ? accept.split(",") : accept;
  return [{
    description: "everything",
    accept: Array.isArray(accept) ? accept.filter(function(item) {
      return item === "audio/*" || item === "video/*" || item === "image/*" || item === "text/*" || /\w+\/[-+.\w]+/g.test(item);
    }).reduce(function(a2, b2) {
      return _objectSpread$1(_objectSpread$1({}, a2), {}, _defineProperty$2({}, b2, []));
    }, {}) : {}
  }];
}
var _excluded$1 = ["children"], _excluded2 = ["open"], _excluded3 = ["refKey", "role", "onKeyDown", "onFocus", "onBlur", "onClick", "onDragEnter", "onDragOver", "onDragLeave", "onDrop"], _excluded4 = ["refKey", "onChange", "onClick"];
function _toConsumableArray(arr) {
  return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _iterableToArray(iter) {
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null)
    return Array.from(iter);
}
function _arrayWithoutHoles(arr) {
  if (Array.isArray(arr))
    return _arrayLikeToArray(arr);
}
function _slicedToArray(arr, i2) {
  return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i2) || _unsupportedIterableToArray(arr, i2) || _nonIterableRest();
}
function _nonIterableRest() {
  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _unsupportedIterableToArray(o2, minLen) {
  if (!o2)
    return;
  if (typeof o2 === "string")
    return _arrayLikeToArray(o2, minLen);
  var n2 = Object.prototype.toString.call(o2).slice(8, -1);
  if (n2 === "Object" && o2.constructor)
    n2 = o2.constructor.name;
  if (n2 === "Map" || n2 === "Set")
    return Array.from(o2);
  if (n2 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n2))
    return _arrayLikeToArray(o2, minLen);
}
function _arrayLikeToArray(arr, len) {
  if (len == null || len > arr.length)
    len = arr.length;
  for (var i2 = 0, arr2 = new Array(len); i2 < len; i2++) {
    arr2[i2] = arr[i2];
  }
  return arr2;
}
function _iterableToArrayLimit(arr, i2) {
  var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
  if (_i == null)
    return;
  var _arr = [];
  var _n = true;
  var _d = false;
  var _s, _e2;
  try {
    for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
      _arr.push(_s.value);
      if (i2 && _arr.length === i2)
        break;
    }
  } catch (err) {
    _d = true;
    _e2 = err;
  } finally {
    try {
      if (!_n && _i["return"] != null)
        _i["return"]();
    } finally {
      if (_d)
        throw _e2;
    }
  }
  return _arr;
}
function _arrayWithHoles(arr) {
  if (Array.isArray(arr))
    return arr;
}
function ownKeys$1(object, enumerableOnly) {
  var keys = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    enumerableOnly && (symbols = symbols.filter(function(sym) {
      return Object.getOwnPropertyDescriptor(object, sym).enumerable;
    })), keys.push.apply(keys, symbols);
  }
  return keys;
}
function _objectSpread(target) {
  for (var i2 = 1; i2 < arguments.length; i2++) {
    var source = arguments[i2] != null ? arguments[i2] : {};
    i2 % 2 ? ownKeys$1(Object(source), true).forEach(function(key) {
      _defineProperty$1(target, key, source[key]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$1(Object(source)).forEach(function(key) {
      Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
    });
  }
  return target;
}
function _defineProperty$1(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }
  return obj;
}
function _objectWithoutProperties$1(source, excluded) {
  if (source == null)
    return {};
  var target = _objectWithoutPropertiesLoose$2(source, excluded);
  var key, i2;
  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
    for (i2 = 0; i2 < sourceSymbolKeys.length; i2++) {
      key = sourceSymbolKeys[i2];
      if (excluded.indexOf(key) >= 0)
        continue;
      if (!Object.prototype.propertyIsEnumerable.call(source, key))
        continue;
      target[key] = source[key];
    }
  }
  return target;
}
function _objectWithoutPropertiesLoose$2(source, excluded) {
  if (source == null)
    return {};
  var target = {};
  var sourceKeys = Object.keys(source);
  var key, i2;
  for (i2 = 0; i2 < sourceKeys.length; i2++) {
    key = sourceKeys[i2];
    if (excluded.indexOf(key) >= 0)
      continue;
    target[key] = source[key];
  }
  return target;
}
var Dropzone = /* @__PURE__ */ forwardRef(function(_ref, ref) {
  var children = _ref.children, params = _objectWithoutProperties$1(_ref, _excluded$1);
  var _useDropzone = useDropzone(params), open2 = _useDropzone.open, props2 = _objectWithoutProperties$1(_useDropzone, _excluded2);
  useImperativeHandle(ref, function() {
    return {
      open: open2
    };
  }, [open2]);
  return /* @__PURE__ */ jsx(Fragment, {
    children: children(_objectSpread(_objectSpread({}, props2), {}, {
      open: open2
    }))
  });
});
Dropzone.displayName = "Dropzone";
var defaultProps = {
  disabled: false,
  getFilesFromEvent: fromEvent,
  maxSize: Infinity,
  minSize: 0,
  multiple: true,
  maxFiles: 0,
  preventDropOnDocument: true,
  noClick: false,
  noKeyboard: false,
  noDrag: false,
  noDragEventsBubbling: false,
  validator: null,
  useFsAccessApi: false
};
Dropzone.defaultProps = defaultProps;
Dropzone.propTypes = {
  children: PropTypes.func,
  accept: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
  multiple: PropTypes.bool,
  preventDropOnDocument: PropTypes.bool,
  noClick: PropTypes.bool,
  noKeyboard: PropTypes.bool,
  noDrag: PropTypes.bool,
  noDragEventsBubbling: PropTypes.bool,
  minSize: PropTypes.number,
  maxSize: PropTypes.number,
  maxFiles: PropTypes.number,
  disabled: PropTypes.bool,
  getFilesFromEvent: PropTypes.func,
  onFileDialogCancel: PropTypes.func,
  onFileDialogOpen: PropTypes.func,
  useFsAccessApi: PropTypes.bool,
  onDragEnter: PropTypes.func,
  onDragLeave: PropTypes.func,
  onDragOver: PropTypes.func,
  onDrop: PropTypes.func,
  onDropAccepted: PropTypes.func,
  onDropRejected: PropTypes.func,
  validator: PropTypes.func
};
var initialState = {
  isFocused: false,
  isFileDialogActive: false,
  isDragActive: false,
  isDragAccept: false,
  isDragReject: false,
  draggedFiles: [],
  acceptedFiles: [],
  fileRejections: []
};
function useDropzone() {
  var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
  var _defaultProps$options = _objectSpread(_objectSpread({}, defaultProps), options), accept = _defaultProps$options.accept, disabled = _defaultProps$options.disabled, getFilesFromEvent = _defaultProps$options.getFilesFromEvent, maxSize = _defaultProps$options.maxSize, minSize = _defaultProps$options.minSize, multiple = _defaultProps$options.multiple, maxFiles = _defaultProps$options.maxFiles, onDragEnter = _defaultProps$options.onDragEnter, onDragLeave = _defaultProps$options.onDragLeave, onDragOver = _defaultProps$options.onDragOver, onDrop = _defaultProps$options.onDrop, onDropAccepted = _defaultProps$options.onDropAccepted, onDropRejected = _defaultProps$options.onDropRejected, onFileDialogCancel = _defaultProps$options.onFileDialogCancel, onFileDialogOpen = _defaultProps$options.onFileDialogOpen, useFsAccessApi = _defaultProps$options.useFsAccessApi, preventDropOnDocument = _defaultProps$options.preventDropOnDocument, noClick = _defaultProps$options.noClick, noKeyboard = _defaultProps$options.noKeyboard, noDrag = _defaultProps$options.noDrag, noDragEventsBubbling = _defaultProps$options.noDragEventsBubbling, validator = _defaultProps$options.validator;
  var onFileDialogOpenCb = useMemo(function() {
    return typeof onFileDialogOpen === "function" ? onFileDialogOpen : noop$1;
  }, [onFileDialogOpen]);
  var onFileDialogCancelCb = useMemo(function() {
    return typeof onFileDialogCancel === "function" ? onFileDialogCancel : noop$1;
  }, [onFileDialogCancel]);
  var rootRef = useRef(null);
  var inputRef = useRef(null);
  var _useReducer = useReducer(reducer$1, initialState), _useReducer2 = _slicedToArray(_useReducer, 2), state2 = _useReducer2[0], dispatch3 = _useReducer2[1];
  var isFocused = state2.isFocused, isFileDialogActive = state2.isFileDialogActive, draggedFiles = state2.draggedFiles;
  var onWindowFocus = function onWindowFocus2() {
    if (isFileDialogActive) {
      setTimeout(function() {
        if (inputRef.current) {
          var files2 = inputRef.current.files;
          if (!files2.length) {
            dispatch3({
              type: "closeDialog"
            });
            onFileDialogCancelCb();
          }
        }
      }, 300);
    }
  };
  useEffect(function() {
    if (useFsAccessApi && canUseFileSystemAccessAPI()) {
      return function() {
      };
    }
    window.addEventListener("focus", onWindowFocus, false);
    return function() {
      window.removeEventListener("focus", onWindowFocus, false);
    };
  }, [inputRef, isFileDialogActive, onFileDialogCancelCb, useFsAccessApi]);
  var dragTargetsRef = useRef([]);
  var onDocumentDrop = function onDocumentDrop2(event) {
    if (rootRef.current && rootRef.current.contains(event.target)) {
      return;
    }
    event.preventDefault();
    dragTargetsRef.current = [];
  };
  useEffect(function() {
    if (preventDropOnDocument) {
      document.addEventListener("dragover", onDocumentDragOver, false);
      document.addEventListener("drop", onDocumentDrop, false);
    }
    return function() {
      if (preventDropOnDocument) {
        document.removeEventListener("dragover", onDocumentDragOver);
        document.removeEventListener("drop", onDocumentDrop);
      }
    };
  }, [rootRef, preventDropOnDocument]);
  var onDragEnterCb = useCallback(function(event) {
    event.preventDefault();
    event.persist();
    stopPropagation(event);
    dragTargetsRef.current = [].concat(_toConsumableArray(dragTargetsRef.current), [event.target]);
    if (isEvtWithFiles(event)) {
      Promise.resolve(getFilesFromEvent(event)).then(function(draggedFiles2) {
        if (isPropagationStopped(event) && !noDragEventsBubbling) {
          return;
        }
        dispatch3({
          draggedFiles: draggedFiles2,
          isDragActive: true,
          type: "setDraggedFiles"
        });
        if (onDragEnter) {
          onDragEnter(event);
        }
      });
    }
  }, [getFilesFromEvent, onDragEnter, noDragEventsBubbling]);
  var onDragOverCb = useCallback(function(event) {
    event.preventDefault();
    event.persist();
    stopPropagation(event);
    var hasFiles = isEvtWithFiles(event);
    if (hasFiles && event.dataTransfer) {
      try {
        event.dataTransfer.dropEffect = "copy";
      } catch (_unused) {
      }
    }
    if (hasFiles && onDragOver) {
      onDragOver(event);
    }
    return false;
  }, [onDragOver, noDragEventsBubbling]);
  var onDragLeaveCb = useCallback(function(event) {
    event.preventDefault();
    event.persist();
    stopPropagation(event);
    var targets = dragTargetsRef.current.filter(function(target) {
      return rootRef.current && rootRef.current.contains(target);
    });
    var targetIdx = targets.indexOf(event.target);
    if (targetIdx !== -1) {
      targets.splice(targetIdx, 1);
    }
    dragTargetsRef.current = targets;
    if (targets.length > 0) {
      return;
    }
    dispatch3({
      isDragActive: false,
      type: "setDraggedFiles",
      draggedFiles: []
    });
    if (isEvtWithFiles(event) && onDragLeave) {
      onDragLeave(event);
    }
  }, [rootRef, onDragLeave, noDragEventsBubbling]);
  var setFiles = useCallback(function(files2, event) {
    var acceptedFiles = [];
    var fileRejections = [];
    files2.forEach(function(file) {
      var _fileAccepted = fileAccepted(file, accept), _fileAccepted2 = _slicedToArray(_fileAccepted, 2), accepted = _fileAccepted2[0], acceptError = _fileAccepted2[1];
      var _fileMatchSize = fileMatchSize(file, minSize, maxSize), _fileMatchSize2 = _slicedToArray(_fileMatchSize, 2), sizeMatch = _fileMatchSize2[0], sizeError = _fileMatchSize2[1];
      var customErrors = validator ? validator(file) : null;
      if (accepted && sizeMatch && !customErrors) {
        acceptedFiles.push(file);
      } else {
        var errors = [acceptError, sizeError];
        if (customErrors) {
          errors = errors.concat(customErrors);
        }
        fileRejections.push({
          file,
          errors: errors.filter(function(e2) {
            return e2;
          })
        });
      }
    });
    if (!multiple && acceptedFiles.length > 1 || multiple && maxFiles >= 1 && acceptedFiles.length > maxFiles) {
      acceptedFiles.forEach(function(file) {
        fileRejections.push({
          file,
          errors: [TOO_MANY_FILES_REJECTION]
        });
      });
      acceptedFiles.splice(0);
    }
    dispatch3({
      acceptedFiles,
      fileRejections,
      type: "setFiles"
    });
    if (onDrop) {
      onDrop(acceptedFiles, fileRejections, event);
    }
    if (fileRejections.length > 0 && onDropRejected) {
      onDropRejected(fileRejections, event);
    }
    if (acceptedFiles.length > 0 && onDropAccepted) {
      onDropAccepted(acceptedFiles, event);
    }
  }, [dispatch3, multiple, accept, minSize, maxSize, maxFiles, onDrop, onDropAccepted, onDropRejected, validator]);
  var onDropCb = useCallback(function(event) {
    event.preventDefault();
    event.persist();
    stopPropagation(event);
    dragTargetsRef.current = [];
    if (isEvtWithFiles(event)) {
      Promise.resolve(getFilesFromEvent(event)).then(function(files2) {
        if (isPropagationStopped(event) && !noDragEventsBubbling) {
          return;
        }
        setFiles(files2, event);
      });
    }
    dispatch3({
      type: "reset"
    });
  }, [getFilesFromEvent, setFiles, noDragEventsBubbling]);
  var openFileDialog = useCallback(function() {
    if (useFsAccessApi && canUseFileSystemAccessAPI()) {
      dispatch3({
        type: "openDialog"
      });
      onFileDialogOpenCb();
      var opts = {
        multiple,
        types: filePickerOptionsTypes(accept)
      };
      window.showOpenFilePicker(opts).then(function(handles) {
        return getFilesFromEvent(handles);
      }).then(function(files2) {
        return setFiles(files2, null);
      }).catch(function(e2) {
        return onFileDialogCancelCb(e2);
      }).finally(function() {
        return dispatch3({
          type: "closeDialog"
        });
      });
      return;
    }
    if (inputRef.current) {
      dispatch3({
        type: "openDialog"
      });
      onFileDialogOpenCb();
      inputRef.current.value = null;
      inputRef.current.click();
    }
  }, [dispatch3, onFileDialogOpenCb, onFileDialogCancelCb, useFsAccessApi, setFiles, accept, multiple]);
  var onKeyDownCb = useCallback(function(event) {
    if (!rootRef.current || !rootRef.current.isEqualNode(event.target)) {
      return;
    }
    if (event.keyCode === 32 || event.keyCode === 13) {
      event.preventDefault();
      openFileDialog();
    }
  }, [rootRef, inputRef, openFileDialog]);
  var onFocusCb = useCallback(function() {
    dispatch3({
      type: "focus"
    });
  }, []);
  var onBlurCb = useCallback(function() {
    dispatch3({
      type: "blur"
    });
  }, []);
  var onClickCb = useCallback(function() {
    if (noClick) {
      return;
    }
    if (isIeOrEdge()) {
      setTimeout(openFileDialog, 0);
    } else {
      openFileDialog();
    }
  }, [inputRef, noClick, openFileDialog]);
  var composeHandler = function composeHandler2(fn2) {
    return disabled ? null : fn2;
  };
  var composeKeyboardHandler = function composeKeyboardHandler2(fn2) {
    return noKeyboard ? null : composeHandler(fn2);
  };
  var composeDragHandler = function composeDragHandler2(fn2) {
    return noDrag ? null : composeHandler(fn2);
  };
  var stopPropagation = function stopPropagation2(event) {
    if (noDragEventsBubbling) {
      event.stopPropagation();
    }
  };
  var getRootProps = useMemo(function() {
    return function() {
      var _ref2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}, _ref2$refKey = _ref2.refKey, refKey = _ref2$refKey === void 0 ? "ref" : _ref2$refKey, role = _ref2.role, onKeyDown = _ref2.onKeyDown, onFocus = _ref2.onFocus, onBlur = _ref2.onBlur, onClick = _ref2.onClick, onDragEnter2 = _ref2.onDragEnter, onDragOver2 = _ref2.onDragOver, onDragLeave2 = _ref2.onDragLeave, onDrop2 = _ref2.onDrop, rest = _objectWithoutProperties$1(_ref2, _excluded3);
      return _objectSpread(_objectSpread(_defineProperty$1({
        onKeyDown: composeKeyboardHandler(composeEventHandlers(onKeyDown, onKeyDownCb)),
        onFocus: composeKeyboardHandler(composeEventHandlers(onFocus, onFocusCb)),
        onBlur: composeKeyboardHandler(composeEventHandlers(onBlur, onBlurCb)),
        onClick: composeHandler(composeEventHandlers(onClick, onClickCb)),
        onDragEnter: composeDragHandler(composeEventHandlers(onDragEnter2, onDragEnterCb)),
        onDragOver: composeDragHandler(composeEventHandlers(onDragOver2, onDragOverCb)),
        onDragLeave: composeDragHandler(composeEventHandlers(onDragLeave2, onDragLeaveCb)),
        onDrop: composeDragHandler(composeEventHandlers(onDrop2, onDropCb)),
        role: typeof role === "string" && role !== "" ? role : "button"
      }, refKey, rootRef), !disabled && !noKeyboard ? {
        tabIndex: 0
      } : {}), rest);
    };
  }, [rootRef, onKeyDownCb, onFocusCb, onBlurCb, onClickCb, onDragEnterCb, onDragOverCb, onDragLeaveCb, onDropCb, noKeyboard, noDrag, disabled]);
  var onInputElementClick = useCallback(function(event) {
    event.stopPropagation();
  }, []);
  var getInputProps = useMemo(function() {
    return function() {
      var _ref3 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}, _ref3$refKey = _ref3.refKey, refKey = _ref3$refKey === void 0 ? "ref" : _ref3$refKey, onChange = _ref3.onChange, onClick = _ref3.onClick, rest = _objectWithoutProperties$1(_ref3, _excluded4);
      var inputProps = _defineProperty$1({
        accept,
        multiple,
        type: "file",
        style: {
          display: "none"
        },
        onChange: composeHandler(composeEventHandlers(onChange, onDropCb)),
        onClick: composeHandler(composeEventHandlers(onClick, onInputElementClick)),
        autoComplete: "off",
        tabIndex: -1
      }, refKey, inputRef);
      return _objectSpread(_objectSpread({}, inputProps), rest);
    };
  }, [inputRef, accept, multiple, onDropCb, disabled]);
  var fileCount = draggedFiles.length;
  var isDragAccept = fileCount > 0 && allFilesAccepted({
    files: draggedFiles,
    accept,
    minSize,
    maxSize,
    multiple,
    maxFiles
  });
  var isDragReject = fileCount > 0 && !isDragAccept;
  return _objectSpread(_objectSpread({}, state2), {}, {
    isDragAccept,
    isDragReject,
    isFocused: isFocused && !disabled,
    getRootProps,
    getInputProps,
    rootRef,
    inputRef,
    open: composeHandler(openFileDialog)
  });
}
function reducer$1(state2, action) {
  switch (action.type) {
    case "focus":
      return _objectSpread(_objectSpread({}, state2), {}, {
        isFocused: true
      });
    case "blur":
      return _objectSpread(_objectSpread({}, state2), {}, {
        isFocused: false
      });
    case "openDialog":
      return _objectSpread(_objectSpread({}, initialState), {}, {
        isFileDialogActive: true
      });
    case "closeDialog":
      return _objectSpread(_objectSpread({}, state2), {}, {
        isFileDialogActive: false
      });
    case "setDraggedFiles":
      var isDragActive2 = action.isDragActive, draggedFiles = action.draggedFiles;
      return _objectSpread(_objectSpread({}, state2), {}, {
        draggedFiles,
        isDragActive: isDragActive2
      });
    case "setFiles":
      return _objectSpread(_objectSpread({}, state2), {}, {
        acceptedFiles: action.acceptedFiles,
        fileRejections: action.fileRejections
      });
    case "reset":
      return _objectSpread({}, initialState);
    default:
      return state2;
  }
}
function noop$1() {
}
function toVal(mix2) {
  var k2, y2, str = "";
  if (typeof mix2 === "string" || typeof mix2 === "number") {
    str += mix2;
  } else if (typeof mix2 === "object") {
    if (Array.isArray(mix2)) {
      for (k2 = 0; k2 < mix2.length; k2++) {
        if (mix2[k2]) {
          if (y2 = toVal(mix2[k2])) {
            str && (str += " ");
            str += y2;
          }
        }
      }
    } else {
      for (k2 in mix2) {
        if (mix2[k2]) {
          str && (str += " ");
          str += k2;
        }
      }
    }
  }
  return str;
}
function clsx() {
  var i2 = 0, tmp2, x2, str = "";
  while (i2 < arguments.length) {
    if (tmp2 = arguments[i2++]) {
      if (x2 = toVal(tmp2)) {
        str && (str += " ");
        str += x2;
      }
    }
  }
  return str;
}
function $parcel$export$B(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $9d939cbc98267846$exports = {};
$parcel$export$B($9d939cbc98267846$exports, "SSRProvider", () => $9d939cbc98267846$export$9f8ac96af4b1b2ae);
$parcel$export$B($9d939cbc98267846$exports, "useSSRSafeId", () => $9d939cbc98267846$export$619500959fc48b26);
$parcel$export$B($9d939cbc98267846$exports, "useIsSSR", () => $9d939cbc98267846$export$535bd6ca7f90a273);
const $9d939cbc98267846$var$defaultContext = {
  prefix: String(Math.round(Math.random() * 1e10)),
  current: 0
};
const $9d939cbc98267846$var$SSRContext = /* @__PURE__ */ React__default.createContext($9d939cbc98267846$var$defaultContext);
function $9d939cbc98267846$export$9f8ac96af4b1b2ae(props2) {
  let cur = useContext($9d939cbc98267846$var$SSRContext);
  let value = useMemo(() => ({
    prefix: cur === $9d939cbc98267846$var$defaultContext ? "" : `${cur.prefix}-${++cur.current}`,
    current: 0
  }), [
    cur
  ]);
  return /* @__PURE__ */ React__default.createElement($9d939cbc98267846$var$SSRContext.Provider, {
    value
  }, props2.children);
}
let $9d939cbc98267846$var$canUseDOM = Boolean(typeof window !== "undefined" && window.document && window.document.createElement);
function $9d939cbc98267846$export$619500959fc48b26(defaultId) {
  let ctx = useContext($9d939cbc98267846$var$SSRContext);
  if (ctx === $9d939cbc98267846$var$defaultContext && !$9d939cbc98267846$var$canUseDOM)
    console.warn("When server rendering, you must wrap your application in an <SSRProvider> to ensure consistent ids are generated between the client and server.");
  return useMemo(() => defaultId || `react-aria${ctx.prefix}-${++ctx.current}`, [
    defaultId
  ]);
}
function $9d939cbc98267846$export$535bd6ca7f90a273() {
  let cur = useContext($9d939cbc98267846$var$SSRContext);
  let isInSSRContext = cur !== $9d939cbc98267846$var$defaultContext;
  let [isSSR2, setIsSSR] = useState(isInSSRContext);
  if (typeof window !== "undefined" && isInSSRContext)
    useLayoutEffect(() => {
      setIsSSR(false);
    }, []);
  return isSSR2;
}
function $parcel$export$A(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $bfee1151ccb0650f$exports = {};
$parcel$export$A($bfee1151ccb0650f$exports, "useControlledState", () => $bfee1151ccb0650f$export$40bfa8c7b0832715);
function $bfee1151ccb0650f$export$40bfa8c7b0832715(value1, defaultValue, onChange) {
  let [stateValue, setStateValue] = useState(value1 || defaultValue);
  let ref = useRef(value1 !== void 0);
  let wasControlled = ref.current;
  let isControlled = value1 !== void 0;
  let stateRef = useRef(stateValue);
  if (wasControlled !== isControlled)
    console.warn(`WARN: A component changed from ${wasControlled ? "controlled" : "uncontrolled"} to ${isControlled ? "controlled" : "uncontrolled"}.`);
  ref.current = isControlled;
  let setValue = useCallback((value2, ...args) => {
    let onChangeCaller = (value, ...onChangeArgs) => {
      if (onChange) {
        if (!Object.is(stateRef.current, value))
          onChange(value, ...onChangeArgs);
      }
      if (!isControlled)
        stateRef.current = value;
    };
    if (typeof value2 === "function") {
      console.warn("We can not support a function callback. See Github Issues for details https://github.com/adobe/react-spectrum/issues/2320");
      let updateFunction = (oldValue, ...functionArgs) => {
        let interceptedValue = value2(isControlled ? stateRef.current : oldValue, ...functionArgs);
        onChangeCaller(interceptedValue, ...args);
        if (!isControlled)
          return interceptedValue;
        return oldValue;
      };
      setStateValue(updateFunction);
    } else {
      if (!isControlled)
        setStateValue(value2);
      onChangeCaller(value2, ...args);
    }
  }, [
    isControlled,
    onChange
  ]);
  if (isControlled)
    stateRef.current = value1;
  else
    value1 = stateValue;
  return [
    value1,
    setValue
  ];
}
var $48d9f1d165180307$exports = {};
$parcel$export$A($48d9f1d165180307$exports, "clamp", () => $48d9f1d165180307$export$7d15b64cf5a3a4c4);
$parcel$export$A($48d9f1d165180307$exports, "snapValueToStep", () => $48d9f1d165180307$export$cb6e0bb50bc19463);
$parcel$export$A($48d9f1d165180307$exports, "toFixedNumber", () => $48d9f1d165180307$export$b6268554fba451f);
function $48d9f1d165180307$export$7d15b64cf5a3a4c4(value, min = -Infinity, max = Infinity) {
  let newValue = Math.min(Math.max(value, min), max);
  return newValue;
}
function $48d9f1d165180307$export$cb6e0bb50bc19463(value, min, max, step) {
  let remainder = (value - (isNaN(min) ? 0 : min)) % step;
  let snappedValue = Math.abs(remainder) * 2 >= step ? value + Math.sign(remainder) * (step - Math.abs(remainder)) : value - remainder;
  if (!isNaN(min)) {
    if (snappedValue < min)
      snappedValue = min;
    else if (!isNaN(max) && snappedValue > max)
      snappedValue = min + Math.floor((max - min) / step) * step;
  } else if (!isNaN(max) && snappedValue > max)
    snappedValue = Math.floor(max / step) * step;
  let string = step.toString();
  let index2 = string.indexOf(".");
  let precision = index2 >= 0 ? string.length - index2 : 0;
  if (precision > 0) {
    let pow = Math.pow(10, precision);
    snappedValue = Math.round(snappedValue * pow) / pow;
  }
  return snappedValue;
}
function $48d9f1d165180307$export$b6268554fba451f(value, digits, base = 10) {
  const pow = Math.pow(base, digits);
  return Math.round(value * pow) / pow;
}
function $parcel$export$z(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $bdb11010cef70236$exports = {};
$parcel$export$z($bdb11010cef70236$exports, "useId", () => $bdb11010cef70236$export$f680877a34711e37);
$parcel$export$z($bdb11010cef70236$exports, "mergeIds", () => $bdb11010cef70236$export$cd8c9cb68f842629);
$parcel$export$z($bdb11010cef70236$exports, "useSlotId", () => $bdb11010cef70236$export$b4cc09c592e8fdb8);
var $f0a04ccd8dbdd83b$exports = {};
$parcel$export$z($f0a04ccd8dbdd83b$exports, "useLayoutEffect", () => $f0a04ccd8dbdd83b$export$e5c5a5f917a5871c);
const $f0a04ccd8dbdd83b$export$e5c5a5f917a5871c = typeof window !== "undefined" ? React__default.useLayoutEffect : () => {
};
let $bdb11010cef70236$var$idsUpdaterMap = /* @__PURE__ */ new Map();
function $bdb11010cef70236$export$f680877a34711e37(defaultId) {
  let isRendering = useRef(true);
  isRendering.current = true;
  let [value, setValue] = useState(defaultId);
  let nextId = useRef(null);
  let res = $9d939cbc98267846$export$619500959fc48b26(value);
  let updateValue = (val) => {
    if (!isRendering.current)
      setValue(val);
    else
      nextId.current = val;
  };
  $bdb11010cef70236$var$idsUpdaterMap.set(res, updateValue);
  $f0a04ccd8dbdd83b$export$e5c5a5f917a5871c(() => {
    isRendering.current = false;
  }, [
    updateValue
  ]);
  $f0a04ccd8dbdd83b$export$e5c5a5f917a5871c(() => {
    let r2 = res;
    return () => {
      $bdb11010cef70236$var$idsUpdaterMap.delete(r2);
    };
  }, [
    res
  ]);
  useEffect(() => {
    let newId = nextId.current;
    if (newId) {
      setValue(newId);
      nextId.current = null;
    }
  }, [
    setValue,
    updateValue
  ]);
  return res;
}
function $bdb11010cef70236$export$cd8c9cb68f842629(idA, idB) {
  if (idA === idB)
    return idA;
  let setIdA = $bdb11010cef70236$var$idsUpdaterMap.get(idA);
  if (setIdA) {
    setIdA(idB);
    return idB;
  }
  let setIdB = $bdb11010cef70236$var$idsUpdaterMap.get(idB);
  if (setIdB) {
    setIdB(idA);
    return idA;
  }
  return idB;
}
function $bdb11010cef70236$export$b4cc09c592e8fdb8(depArray = []) {
  let id2 = $bdb11010cef70236$export$f680877a34711e37();
  let [resolvedId, setResolvedId] = $1dbecbe27a04f9af$export$14d238f342723f25(id2);
  let updateId = useCallback(() => {
    setResolvedId(function* () {
      yield id2;
      yield document.getElementById(id2) ? id2 : null;
    });
  }, [
    id2,
    setResolvedId
  ]);
  $f0a04ccd8dbdd83b$export$e5c5a5f917a5871c(updateId, [
    id2,
    updateId,
    ...depArray
  ]);
  return resolvedId;
}
var $ff5963eb1fccf552$exports = {};
$parcel$export$z($ff5963eb1fccf552$exports, "chain", () => $ff5963eb1fccf552$export$e08e3b67e392101e);
function $ff5963eb1fccf552$export$e08e3b67e392101e(...callbacks) {
  return (...args) => {
    for (let callback of callbacks)
      if (typeof callback === "function")
        callback(...args);
  };
}
var $3ef42575df84b30b$exports = {};
$parcel$export$z($3ef42575df84b30b$exports, "mergeProps", () => $3ef42575df84b30b$export$9d1611c77c2fe928);
function $3ef42575df84b30b$export$9d1611c77c2fe928(...args) {
  let result = __spreadValues({}, args[0]);
  for (let i2 = 1; i2 < args.length; i2++) {
    let props2 = args[i2];
    for (let key in props2) {
      let a2 = result[key];
      let b2 = props2[key];
      if (typeof a2 === "function" && typeof b2 === "function" && key[0] === "o" && key[1] === "n" && key.charCodeAt(2) >= 65 && key.charCodeAt(2) <= 90)
        result[key] = $ff5963eb1fccf552$export$e08e3b67e392101e(a2, b2);
      else if ((key === "className" || key === "UNSAFE_className") && typeof a2 === "string" && typeof b2 === "string")
        result[key] = clsx(a2, b2);
      else if (key === "id" && a2 && b2)
        result.id = $bdb11010cef70236$export$cd8c9cb68f842629(a2, b2);
      else
        result[key] = b2 !== void 0 ? b2 : a2;
    }
  }
  return result;
}
var $65484d02dcb7eb3e$exports = {};
$parcel$export$z($65484d02dcb7eb3e$exports, "filterDOMProps", () => $65484d02dcb7eb3e$export$457c3d6518dd4c6f);
const $65484d02dcb7eb3e$var$DOMPropNames = /* @__PURE__ */ new Set([
  "id"
]);
const $65484d02dcb7eb3e$var$labelablePropNames = /* @__PURE__ */ new Set([
  "aria-label",
  "aria-labelledby",
  "aria-describedby",
  "aria-details"
]);
const $65484d02dcb7eb3e$var$propRe = /^(data-.*)$/;
function $65484d02dcb7eb3e$export$457c3d6518dd4c6f(props2, opts = {}) {
  let { labelable, propNames } = opts;
  let filteredProps = {};
  for (const prop in props2)
    if (Object.prototype.hasOwnProperty.call(props2, prop) && ($65484d02dcb7eb3e$var$DOMPropNames.has(prop) || labelable && $65484d02dcb7eb3e$var$labelablePropNames.has(prop) || (propNames === null || propNames === void 0 ? void 0 : propNames.has(prop)) || $65484d02dcb7eb3e$var$propRe.test(prop)))
      filteredProps[prop] = props2[prop];
  return filteredProps;
}
var $7215afc6de606d6b$exports = {};
$parcel$export$z($7215afc6de606d6b$exports, "focusWithoutScrolling", () => $7215afc6de606d6b$export$de79e2c695e052f3);
function $7215afc6de606d6b$export$de79e2c695e052f3(element) {
  if ($7215afc6de606d6b$var$supportsPreventScroll())
    element.focus({
      preventScroll: true
    });
  else {
    let scrollableElements = $7215afc6de606d6b$var$getScrollableElements(element);
    element.focus();
    $7215afc6de606d6b$var$restoreScrollPosition(scrollableElements);
  }
}
let $7215afc6de606d6b$var$supportsPreventScrollCached = null;
function $7215afc6de606d6b$var$supportsPreventScroll() {
  if ($7215afc6de606d6b$var$supportsPreventScrollCached == null) {
    $7215afc6de606d6b$var$supportsPreventScrollCached = false;
    try {
      var focusElem = document.createElement("div");
      focusElem.focus({
        get preventScroll() {
          $7215afc6de606d6b$var$supportsPreventScrollCached = true;
          return true;
        }
      });
    } catch (e2) {
    }
  }
  return $7215afc6de606d6b$var$supportsPreventScrollCached;
}
function $7215afc6de606d6b$var$getScrollableElements(element) {
  var parent = element.parentNode;
  var scrollableElements = [];
  var rootScrollingElement = document.scrollingElement || document.documentElement;
  while (parent instanceof HTMLElement && parent !== rootScrollingElement) {
    if (parent.offsetHeight < parent.scrollHeight || parent.offsetWidth < parent.scrollWidth)
      scrollableElements.push({
        element: parent,
        scrollTop: parent.scrollTop,
        scrollLeft: parent.scrollLeft
      });
    parent = parent.parentNode;
  }
  if (rootScrollingElement instanceof HTMLElement)
    scrollableElements.push({
      element: rootScrollingElement,
      scrollTop: rootScrollingElement.scrollTop,
      scrollLeft: rootScrollingElement.scrollLeft
    });
  return scrollableElements;
}
function $7215afc6de606d6b$var$restoreScrollPosition(scrollableElements) {
  for (let { element, scrollTop: scrollTop2, scrollLeft: scrollLeft2 } of scrollableElements) {
    element.scrollTop = scrollTop2;
    element.scrollLeft = scrollLeft2;
  }
}
var $ab71dadb03a6fb2e$exports = {};
$parcel$export$z($ab71dadb03a6fb2e$exports, "getOffset", () => $ab71dadb03a6fb2e$export$622cea445a1c5b7d);
function $ab71dadb03a6fb2e$export$622cea445a1c5b7d(element, reverse, orientation = "horizontal") {
  let rect = element.getBoundingClientRect();
  if (reverse)
    return orientation === "horizontal" ? rect.right : rect.bottom;
  return orientation === "horizontal" ? rect.left : rect.top;
}
var $103b0e103f1b5952$exports = {};
$parcel$export$z($103b0e103f1b5952$exports, "clamp", () => $48d9f1d165180307$export$7d15b64cf5a3a4c4);
$parcel$export$z($103b0e103f1b5952$exports, "snapValueToStep", () => $48d9f1d165180307$export$cb6e0bb50bc19463);
var $bbed8b41f857bcc0$exports = {};
$parcel$export$z($bbed8b41f857bcc0$exports, "runAfterTransition", () => $bbed8b41f857bcc0$export$24490316f764c430);
let $bbed8b41f857bcc0$var$transitionsByElement = /* @__PURE__ */ new Map();
let $bbed8b41f857bcc0$var$transitionCallbacks = /* @__PURE__ */ new Set();
function $bbed8b41f857bcc0$var$setupGlobalEvents() {
  if (typeof window === "undefined")
    return;
  let onTransitionStart = (e2) => {
    let transitions = $bbed8b41f857bcc0$var$transitionsByElement.get(e2.target);
    if (!transitions) {
      transitions = /* @__PURE__ */ new Set();
      $bbed8b41f857bcc0$var$transitionsByElement.set(e2.target, transitions);
      e2.target.addEventListener("transitioncancel", onTransitionEnd);
    }
    transitions.add(e2.propertyName);
  };
  let onTransitionEnd = (e2) => {
    let properties2 = $bbed8b41f857bcc0$var$transitionsByElement.get(e2.target);
    if (!properties2)
      return;
    properties2.delete(e2.propertyName);
    if (properties2.size === 0) {
      e2.target.removeEventListener("transitioncancel", onTransitionEnd);
      $bbed8b41f857bcc0$var$transitionsByElement.delete(e2.target);
    }
    if ($bbed8b41f857bcc0$var$transitionsByElement.size === 0) {
      for (let cb2 of $bbed8b41f857bcc0$var$transitionCallbacks)
        cb2();
      $bbed8b41f857bcc0$var$transitionCallbacks.clear();
    }
  };
  document.body.addEventListener("transitionrun", onTransitionStart);
  document.body.addEventListener("transitionend", onTransitionEnd);
}
if (typeof document !== "undefined") {
  if (document.readyState !== "loading")
    $bbed8b41f857bcc0$var$setupGlobalEvents();
  else
    document.addEventListener("DOMContentLoaded", $bbed8b41f857bcc0$var$setupGlobalEvents);
}
function $bbed8b41f857bcc0$export$24490316f764c430(fn2) {
  requestAnimationFrame(() => {
    if ($bbed8b41f857bcc0$var$transitionsByElement.size === 0)
      fn2();
    else
      $bbed8b41f857bcc0$var$transitionCallbacks.add(fn2);
  });
}
var $9cc09df9fd7676be$exports = {};
$parcel$export$z($9cc09df9fd7676be$exports, "useDrag1D", () => $9cc09df9fd7676be$export$7bbed75feba39706);
const $9cc09df9fd7676be$var$draggingElements = [];
function $9cc09df9fd7676be$export$7bbed75feba39706(props2) {
  console.warn("useDrag1D is deprecated, please use `useMove` instead https://react-spectrum.adobe.com/react-aria/useMove.html");
  let { containerRef, reverse, orientation, onHover, onDrag, onPositionChange, onIncrement, onDecrement, onIncrementToMax, onDecrementToMin, onCollapseToggle } = props2;
  let getPosition = (e2) => orientation === "horizontal" ? e2.clientX : e2.clientY;
  let getNextOffset = (e2) => {
    let containerOffset = $ab71dadb03a6fb2e$export$622cea445a1c5b7d(containerRef.current, reverse, orientation);
    let mouseOffset = getPosition(e2);
    let nextOffset = reverse ? containerOffset - mouseOffset : mouseOffset - containerOffset;
    return nextOffset;
  };
  let dragging = useRef(false);
  let prevPosition = useRef(0);
  let handlers2 = useRef({
    onPositionChange,
    onDrag
  });
  handlers2.current.onDrag = onDrag;
  handlers2.current.onPositionChange = onPositionChange;
  let onMouseDragged = (e2) => {
    e2.preventDefault();
    let nextOffset = getNextOffset(e2);
    if (!dragging.current) {
      dragging.current = true;
      if (handlers2.current.onDrag)
        handlers2.current.onDrag(true);
      if (handlers2.current.onPositionChange)
        handlers2.current.onPositionChange(nextOffset);
    }
    if (prevPosition.current === nextOffset)
      return;
    prevPosition.current = nextOffset;
    if (onPositionChange)
      onPositionChange(nextOffset);
  };
  let onMouseUp = (e2) => {
    const target = e2.target;
    dragging.current = false;
    let nextOffset = getNextOffset(e2);
    if (handlers2.current.onDrag)
      handlers2.current.onDrag(false);
    if (handlers2.current.onPositionChange)
      handlers2.current.onPositionChange(nextOffset);
    $9cc09df9fd7676be$var$draggingElements.splice($9cc09df9fd7676be$var$draggingElements.indexOf(target), 1);
    window.removeEventListener("mouseup", onMouseUp, false);
    window.removeEventListener("mousemove", onMouseDragged, false);
  };
  let onMouseDown = (e2) => {
    const target = e2.currentTarget;
    if ($9cc09df9fd7676be$var$draggingElements.some((elt) => target.contains(elt)))
      return;
    $9cc09df9fd7676be$var$draggingElements.push(target);
    window.addEventListener("mousemove", onMouseDragged, false);
    window.addEventListener("mouseup", onMouseUp, false);
  };
  let onMouseEnter = () => {
    if (onHover)
      onHover(true);
  };
  let onMouseOut = () => {
    if (onHover)
      onHover(false);
  };
  let onKeyDown = (e2) => {
    switch (e2.key) {
      case "Left":
      case "ArrowLeft":
        if (orientation === "horizontal") {
          e2.preventDefault();
          if (onDecrement && !reverse)
            onDecrement();
          else if (onIncrement && reverse)
            onIncrement();
        }
        break;
      case "Up":
      case "ArrowUp":
        if (orientation === "vertical") {
          e2.preventDefault();
          if (onDecrement && !reverse)
            onDecrement();
          else if (onIncrement && reverse)
            onIncrement();
        }
        break;
      case "Right":
      case "ArrowRight":
        if (orientation === "horizontal") {
          e2.preventDefault();
          if (onIncrement && !reverse)
            onIncrement();
          else if (onDecrement && reverse)
            onDecrement();
        }
        break;
      case "Down":
      case "ArrowDown":
        if (orientation === "vertical") {
          e2.preventDefault();
          if (onIncrement && !reverse)
            onIncrement();
          else if (onDecrement && reverse)
            onDecrement();
        }
        break;
      case "Home":
        e2.preventDefault();
        if (onDecrementToMin)
          onDecrementToMin();
        break;
      case "End":
        e2.preventDefault();
        if (onIncrementToMax)
          onIncrementToMax();
        break;
      case "Enter":
        e2.preventDefault();
        if (onCollapseToggle)
          onCollapseToggle();
        break;
    }
  };
  return {
    onMouseDown,
    onMouseEnter,
    onMouseOut,
    onKeyDown
  };
}
var $03deb23ff14920c4$exports = {};
$parcel$export$z($03deb23ff14920c4$exports, "useGlobalListeners", () => $03deb23ff14920c4$export$4eaf04e54aa8eed6);
function $03deb23ff14920c4$export$4eaf04e54aa8eed6() {
  let globalListeners = useRef(/* @__PURE__ */ new Map());
  let addGlobalListener = useCallback((eventTarget, type, listener, options) => {
    let fn2 = (options === null || options === void 0 ? void 0 : options.once) ? (...args) => {
      globalListeners.current.delete(listener);
      listener(...args);
    } : listener;
    globalListeners.current.set(listener, {
      type,
      eventTarget,
      fn: fn2,
      options
    });
    eventTarget.addEventListener(type, listener, options);
  }, []);
  let removeGlobalListener = useCallback((eventTarget, type, listener, options) => {
    var ref;
    let fn2 = ((ref = globalListeners.current.get(listener)) === null || ref === void 0 ? void 0 : ref.fn) || listener;
    eventTarget.removeEventListener(type, fn2, options);
    globalListeners.current.delete(listener);
  }, []);
  let removeAllGlobalListeners = useCallback(() => {
    globalListeners.current.forEach((value, key) => {
      removeGlobalListener(value.eventTarget, value.type, key, value.options);
    });
  }, [
    removeGlobalListener
  ]);
  useEffect(() => {
    return removeAllGlobalListeners;
  }, [
    removeAllGlobalListeners
  ]);
  return {
    addGlobalListener,
    removeGlobalListener,
    removeAllGlobalListeners
  };
}
var $313b98861ee5dd6c$exports = {};
$parcel$export$z($313b98861ee5dd6c$exports, "useLabels", () => $313b98861ee5dd6c$export$d6875122194c7b44);
function $313b98861ee5dd6c$export$d6875122194c7b44(props2, defaultLabel) {
  let { id: id2, "aria-label": label, "aria-labelledby": labelledBy } = props2;
  id2 = $bdb11010cef70236$export$f680877a34711e37(id2);
  if (labelledBy && label) {
    let ids = /* @__PURE__ */ new Set([
      ...labelledBy.trim().split(/\s+/),
      id2
    ]);
    labelledBy = [
      ...ids
    ].join(" ");
  } else if (labelledBy)
    labelledBy = labelledBy.trim().split(/\s+/).join(" ");
  if (!label && !labelledBy && defaultLabel)
    label = defaultLabel;
  return {
    id: id2,
    "aria-label": label,
    "aria-labelledby": labelledBy
  };
}
var $df56164dff5785e2$exports = {};
$parcel$export$z($df56164dff5785e2$exports, "useObjectRef", () => $df56164dff5785e2$export$4338b53315abf666);
function $df56164dff5785e2$export$4338b53315abf666(forwardedRef) {
  const objRef = useRef();
  $f0a04ccd8dbdd83b$export$e5c5a5f917a5871c(() => {
    if (!forwardedRef)
      return;
    if (typeof forwardedRef === "function")
      forwardedRef(objRef.current);
    else
      forwardedRef.current = objRef.current;
  }, [
    forwardedRef
  ]);
  return objRef;
}
var $4f58c5f72bcf79f7$exports = {};
$parcel$export$z($4f58c5f72bcf79f7$exports, "useUpdateEffect", () => $4f58c5f72bcf79f7$export$496315a1608d9602);
function $4f58c5f72bcf79f7$export$496315a1608d9602(effect, dependencies2) {
  const isInitialMount = useRef(true);
  useEffect(() => {
    if (isInitialMount.current)
      isInitialMount.current = false;
    else
      effect();
  }, dependencies2);
}
var $9daab02d461809db$exports = {};
$parcel$export$z($9daab02d461809db$exports, "useResizeObserver", () => $9daab02d461809db$export$683480f191c0e3ea);
function $9daab02d461809db$var$hasResizeObserver() {
  return typeof window.ResizeObserver !== "undefined";
}
function $9daab02d461809db$export$683480f191c0e3ea(options) {
  const { ref, onResize } = options;
  useEffect(() => {
    let element = ref === null || ref === void 0 ? void 0 : ref.current;
    if (!element)
      return;
    if (!$9daab02d461809db$var$hasResizeObserver()) {
      window.addEventListener("resize", onResize, false);
      return () => {
        window.removeEventListener("resize", onResize, false);
      };
    } else {
      const resizeObserverInstance = new window.ResizeObserver((entries) => {
        if (!entries.length)
          return;
        onResize();
      });
      resizeObserverInstance.observe(element);
      return () => {
        if (element)
          resizeObserverInstance.unobserve(element);
      };
    }
  }, [
    onResize,
    ref
  ]);
}
var $e7801be82b4b2a53$exports = {};
$parcel$export$z($e7801be82b4b2a53$exports, "useSyncRef", () => $e7801be82b4b2a53$export$4debdb1a3f0fa79e);
function $e7801be82b4b2a53$export$4debdb1a3f0fa79e(context, ref) {
  $f0a04ccd8dbdd83b$export$e5c5a5f917a5871c(() => {
    if (context && context.ref && ref) {
      context.ref.current = ref.current;
      return () => {
        context.ref.current = null;
      };
    }
  }, [
    context,
    ref
  ]);
}
var $62d8ded9296f3872$exports = {};
$parcel$export$z($62d8ded9296f3872$exports, "getScrollParent", () => $62d8ded9296f3872$export$cfa2225e87938781);
function $62d8ded9296f3872$export$cfa2225e87938781(node) {
  while (node && !$62d8ded9296f3872$var$isScrollable(node))
    node = node.parentElement;
  return node || document.scrollingElement || document.documentElement;
}
function $62d8ded9296f3872$var$isScrollable(node) {
  let style2 = window.getComputedStyle(node);
  return /(auto|scroll)/.test(style2.overflow + style2.overflowX + style2.overflowY);
}
var $5df64b3807dc15ee$exports = {};
$parcel$export$z($5df64b3807dc15ee$exports, "useViewportSize", () => $5df64b3807dc15ee$export$d699905dd57c73ca);
let $5df64b3807dc15ee$var$visualViewport = typeof window !== "undefined" && window.visualViewport;
function $5df64b3807dc15ee$export$d699905dd57c73ca() {
  let [size1, setSize] = useState(() => $5df64b3807dc15ee$var$getViewportSize());
  useEffect(() => {
    let onResize = () => {
      setSize((size) => {
        let newSize = $5df64b3807dc15ee$var$getViewportSize();
        if (newSize.width === size.width && newSize.height === size.height)
          return size;
        return newSize;
      });
    };
    if (!$5df64b3807dc15ee$var$visualViewport)
      window.addEventListener("resize", onResize);
    else
      $5df64b3807dc15ee$var$visualViewport.addEventListener("resize", onResize);
    return () => {
      if (!$5df64b3807dc15ee$var$visualViewport)
        window.removeEventListener("resize", onResize);
      else
        $5df64b3807dc15ee$var$visualViewport.removeEventListener("resize", onResize);
    };
  }, []);
  return size1;
}
function $5df64b3807dc15ee$var$getViewportSize() {
  return {
    width: ($5df64b3807dc15ee$var$visualViewport === null || $5df64b3807dc15ee$var$visualViewport === void 0 ? void 0 : $5df64b3807dc15ee$var$visualViewport.width) || window.innerWidth,
    height: ($5df64b3807dc15ee$var$visualViewport === null || $5df64b3807dc15ee$var$visualViewport === void 0 ? void 0 : $5df64b3807dc15ee$var$visualViewport.height) || window.innerHeight
  };
}
var $ef06256079686ba0$exports = {};
$parcel$export$z($ef06256079686ba0$exports, "useDescription", () => $ef06256079686ba0$export$f8aeda7b10753fa1);
let $ef06256079686ba0$var$descriptionId = 0;
const $ef06256079686ba0$var$descriptionNodes = /* @__PURE__ */ new Map();
function $ef06256079686ba0$export$f8aeda7b10753fa1(description) {
  let [id1, setId] = useState(null);
  $f0a04ccd8dbdd83b$export$e5c5a5f917a5871c(() => {
    if (!description)
      return;
    let desc = $ef06256079686ba0$var$descriptionNodes.get(description);
    if (!desc) {
      let id2 = `react-aria-description-${$ef06256079686ba0$var$descriptionId++}`;
      setId(id2);
      let node = document.createElement("div");
      node.id = id2;
      node.style.display = "none";
      node.textContent = description;
      document.body.appendChild(node);
      desc = {
        refCount: 0,
        element: node
      };
      $ef06256079686ba0$var$descriptionNodes.set(description, desc);
    } else
      setId(desc.element.id);
    desc.refCount++;
    return () => {
      if (--desc.refCount === 0) {
        desc.element.remove();
        $ef06256079686ba0$var$descriptionNodes.delete(description);
      }
    };
  }, [
    description
  ]);
  return {
    "aria-describedby": description ? id1 : void 0
  };
}
var $c87311424ea30a05$exports = {};
$parcel$export$z($c87311424ea30a05$exports, "isMac", () => $c87311424ea30a05$export$9ac100e40613ea10);
$parcel$export$z($c87311424ea30a05$exports, "isIPhone", () => $c87311424ea30a05$export$186c6964ca17d99);
$parcel$export$z($c87311424ea30a05$exports, "isIPad", () => $c87311424ea30a05$export$7bef049ce92e4224);
$parcel$export$z($c87311424ea30a05$exports, "isIOS", () => $c87311424ea30a05$export$fedb369cb70207f1);
$parcel$export$z($c87311424ea30a05$exports, "isAppleDevice", () => $c87311424ea30a05$export$e1865c3bedcd822b);
$parcel$export$z($c87311424ea30a05$exports, "isWebKit", () => $c87311424ea30a05$export$78551043582a6a98);
$parcel$export$z($c87311424ea30a05$exports, "isChrome", () => $c87311424ea30a05$export$6446a186d09e379e);
$parcel$export$z($c87311424ea30a05$exports, "isAndroid", () => $c87311424ea30a05$export$a11b0059900ceec8);
function $c87311424ea30a05$var$testUserAgent(re) {
  var ref;
  if (typeof window === "undefined" || window.navigator == null)
    return false;
  return ((ref = window.navigator["userAgentData"]) === null || ref === void 0 ? void 0 : ref.brands.some((brand) => re.test(brand.brand))) || re.test(window.navigator.userAgent);
}
function $c87311424ea30a05$var$testPlatform(re) {
  return typeof window !== "undefined" && window.navigator != null ? re.test((window.navigator["userAgentData"] || window.navigator).platform) : false;
}
function $c87311424ea30a05$export$9ac100e40613ea10() {
  return $c87311424ea30a05$var$testPlatform(/^Mac/i);
}
function $c87311424ea30a05$export$186c6964ca17d99() {
  return $c87311424ea30a05$var$testPlatform(/^iPhone/i);
}
function $c87311424ea30a05$export$7bef049ce92e4224() {
  return $c87311424ea30a05$var$testPlatform(/^iPad/i) || $c87311424ea30a05$export$9ac100e40613ea10() && navigator.maxTouchPoints > 1;
}
function $c87311424ea30a05$export$fedb369cb70207f1() {
  return $c87311424ea30a05$export$186c6964ca17d99() || $c87311424ea30a05$export$7bef049ce92e4224();
}
function $c87311424ea30a05$export$e1865c3bedcd822b() {
  return $c87311424ea30a05$export$9ac100e40613ea10() || $c87311424ea30a05$export$fedb369cb70207f1();
}
function $c87311424ea30a05$export$78551043582a6a98() {
  return $c87311424ea30a05$var$testUserAgent(/AppleWebKit/i) && !$c87311424ea30a05$export$6446a186d09e379e();
}
function $c87311424ea30a05$export$6446a186d09e379e() {
  return $c87311424ea30a05$var$testUserAgent(/Chrome/i);
}
function $c87311424ea30a05$export$a11b0059900ceec8() {
  return $c87311424ea30a05$var$testUserAgent(/Android/i);
}
var $e9faafb641e167db$exports = {};
$parcel$export$z($e9faafb641e167db$exports, "useEvent", () => $e9faafb641e167db$export$90fc3a17d93f704c);
function $e9faafb641e167db$export$90fc3a17d93f704c(ref, event, handler1, options) {
  let handlerRef = useRef(handler1);
  handlerRef.current = handler1;
  let isDisabled = handler1 == null;
  useEffect(() => {
    if (isDisabled)
      return;
    let element = ref.current;
    let handler = (e2) => handlerRef.current.call(this, e2);
    element.addEventListener(event, handler, options);
    return () => {
      element.removeEventListener(event, handler, options);
    };
  }, [
    ref,
    event,
    options,
    isDisabled
  ]);
}
var $1dbecbe27a04f9af$exports = {};
$parcel$export$z($1dbecbe27a04f9af$exports, "useValueEffect", () => $1dbecbe27a04f9af$export$14d238f342723f25);
function $1dbecbe27a04f9af$export$14d238f342723f25(defaultValue) {
  let [value, setValue] = useState(defaultValue);
  let valueRef = useRef(value);
  let effect = useRef(null);
  valueRef.current = value;
  let nextRef = useRef(null);
  nextRef.current = () => {
    let newValue = effect.current.next();
    if (newValue.done) {
      effect.current = null;
      return;
    }
    if (value === newValue.value)
      nextRef.current();
    else
      setValue(newValue.value);
  };
  $f0a04ccd8dbdd83b$export$e5c5a5f917a5871c(() => {
    if (effect.current)
      nextRef.current();
  });
  let queue = useCallback((fn2) => {
    effect.current = fn2(valueRef.current);
    nextRef.current();
  }, [
    effect,
    nextRef
  ]);
  return [
    value,
    queue
  ];
}
var $2f04cbc44ee30ce0$exports = {};
$parcel$export$z($2f04cbc44ee30ce0$exports, "scrollIntoView", () => $2f04cbc44ee30ce0$export$53a0910f038337bd);
function $2f04cbc44ee30ce0$export$53a0910f038337bd(scrollView, element) {
  let offsetX = $2f04cbc44ee30ce0$var$relativeOffset(scrollView, element, "left");
  let offsetY = $2f04cbc44ee30ce0$var$relativeOffset(scrollView, element, "top");
  let width = element.offsetWidth;
  let height = element.offsetHeight;
  let x2 = scrollView.scrollLeft;
  let y2 = scrollView.scrollTop;
  let maxX = x2 + scrollView.offsetWidth;
  let maxY = y2 + scrollView.offsetHeight;
  if (offsetX <= x2)
    x2 = offsetX;
  else if (offsetX + width > maxX)
    x2 += offsetX + width - maxX;
  if (offsetY <= y2)
    y2 = offsetY;
  else if (offsetY + height > maxY)
    y2 += offsetY + height - maxY;
  scrollView.scrollLeft = x2;
  scrollView.scrollTop = y2;
}
function $2f04cbc44ee30ce0$var$relativeOffset(ancestor, child, axis) {
  const prop = axis === "left" ? "offsetLeft" : "offsetTop";
  let sum = 0;
  while (child.offsetParent) {
    sum += child[prop];
    if (child.offsetParent === ancestor)
      break;
    else if (child.offsetParent.contains(ancestor)) {
      sum -= ancestor[prop];
      break;
    }
    child = child.offsetParent;
  }
  return sum;
}
function $parcel$export$y(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $3b117e43dc0ca95d$exports = {};
$parcel$export$y($3b117e43dc0ca95d$exports, "Pressable", () => $3b117e43dc0ca95d$export$27c701ed9e449e99);
var $f6c31cce2adf654f$exports = {};
$parcel$export$y($f6c31cce2adf654f$exports, "usePress", () => $f6c31cce2adf654f$export$45712eceda6fad21);
let $14c0b72509d70225$var$state = "default";
let $14c0b72509d70225$var$savedUserSelect = "";
let $14c0b72509d70225$var$modifiedElementMap = /* @__PURE__ */ new WeakMap();
function $14c0b72509d70225$export$16a4697467175487(target) {
  if ($c87311424ea30a05$export$fedb369cb70207f1()) {
    if ($14c0b72509d70225$var$state === "default") {
      $14c0b72509d70225$var$savedUserSelect = document.documentElement.style.webkitUserSelect;
      document.documentElement.style.webkitUserSelect = "none";
    }
    $14c0b72509d70225$var$state = "disabled";
  } else if (target) {
    $14c0b72509d70225$var$modifiedElementMap.set(target, target.style.userSelect);
    target.style.userSelect = "none";
  }
}
function $14c0b72509d70225$export$b0d6fa1ab32e3295(target) {
  if ($c87311424ea30a05$export$fedb369cb70207f1()) {
    if ($14c0b72509d70225$var$state !== "disabled")
      return;
    $14c0b72509d70225$var$state = "restoring";
    setTimeout(() => {
      $bbed8b41f857bcc0$export$24490316f764c430(() => {
        if ($14c0b72509d70225$var$state === "restoring") {
          if (document.documentElement.style.webkitUserSelect === "none")
            document.documentElement.style.webkitUserSelect = $14c0b72509d70225$var$savedUserSelect || "";
          $14c0b72509d70225$var$savedUserSelect = "";
          $14c0b72509d70225$var$state = "default";
        }
      });
    }, 300);
  } else if (target && $14c0b72509d70225$var$modifiedElementMap.has(target)) {
    let targetOldUserSelect = $14c0b72509d70225$var$modifiedElementMap.get(target);
    if (target.style.userSelect === "none")
      target.style.userSelect = targetOldUserSelect;
    if (target.getAttribute("style") === "")
      target.removeAttribute("style");
    $14c0b72509d70225$var$modifiedElementMap.delete(target);
  }
}
function $8a9cb279dc87e130$export$60278871457622de(event) {
  if (event.mozInputSource === 0 && event.isTrusted)
    return true;
  return event.detail === 0 && !event.pointerType;
}
const $ae1eeba8b9eafd08$export$5165eccb35aaadb5 = React__default.createContext(null);
$ae1eeba8b9eafd08$export$5165eccb35aaadb5.displayName = "PressResponderContext";
function $f6c31cce2adf654f$var$usePressResponderContext(props2) {
  let context = useContext($ae1eeba8b9eafd08$export$5165eccb35aaadb5);
  if (context) {
    let _a2 = context, { register } = _a2, contextProps = __objRest(_a2, ["register"]);
    props2 = $3ef42575df84b30b$export$9d1611c77c2fe928(contextProps, props2);
    register();
  }
  $e7801be82b4b2a53$export$4debdb1a3f0fa79e(context, props2.ref);
  return props2;
}
function $f6c31cce2adf654f$export$45712eceda6fad21(props2) {
  let _a2 = $f6c31cce2adf654f$var$usePressResponderContext(props2), {
    onPress: onPress1,
    onPressChange: onPressChange1,
    onPressStart: onPressStart1,
    onPressEnd: onPressEnd1,
    onPressUp: onPressUp1,
    isDisabled: isDisabled1,
    isPressed: isPressedProp,
    preventFocusOnPress,
    shouldCancelOnPointerExit,
    allowTextSelectionOnPress,
    ref: _2
  } = _a2, domProps = __objRest(_a2, [
    "onPress",
    "onPressChange",
    "onPressStart",
    "onPressEnd",
    "onPressUp",
    "isDisabled",
    "isPressed",
    "preventFocusOnPress",
    "shouldCancelOnPointerExit",
    "allowTextSelectionOnPress",
    "ref"
  ]);
  let propsRef = useRef(null);
  propsRef.current = {
    onPress: onPress1,
    onPressChange: onPressChange1,
    onPressStart: onPressStart1,
    onPressEnd: onPressEnd1,
    onPressUp: onPressUp1,
    isDisabled: isDisabled1,
    shouldCancelOnPointerExit
  };
  let [isPressed, setPressed] = useState(false);
  let ref = useRef({
    isPressed: false,
    ignoreEmulatedMouseEvents: false,
    ignoreClickAfterPress: false,
    didFirePressStart: false,
    activePointerId: null,
    target: null,
    isOverTarget: false,
    pointerType: null
  });
  let { addGlobalListener, removeAllGlobalListeners } = $03deb23ff14920c4$export$4eaf04e54aa8eed6();
  let pressProps1 = useMemo(() => {
    let state2 = ref.current;
    let triggerPressStart = (originalEvent, pointerType) => {
      let { onPressStart, onPressChange, isDisabled } = propsRef.current;
      if (isDisabled || state2.didFirePressStart)
        return;
      if (onPressStart)
        onPressStart({
          type: "pressstart",
          pointerType,
          target: originalEvent.currentTarget,
          shiftKey: originalEvent.shiftKey,
          metaKey: originalEvent.metaKey,
          ctrlKey: originalEvent.ctrlKey,
          altKey: originalEvent.altKey
        });
      if (onPressChange)
        onPressChange(true);
      state2.didFirePressStart = true;
      setPressed(true);
    };
    let triggerPressEnd = (originalEvent, pointerType, wasPressed = true) => {
      let { onPressEnd, onPressChange, onPress, isDisabled } = propsRef.current;
      if (!state2.didFirePressStart)
        return;
      state2.ignoreClickAfterPress = true;
      state2.didFirePressStart = false;
      if (onPressEnd)
        onPressEnd({
          type: "pressend",
          pointerType,
          target: originalEvent.currentTarget,
          shiftKey: originalEvent.shiftKey,
          metaKey: originalEvent.metaKey,
          ctrlKey: originalEvent.ctrlKey,
          altKey: originalEvent.altKey
        });
      if (onPressChange)
        onPressChange(false);
      setPressed(false);
      if (onPress && wasPressed && !isDisabled)
        onPress({
          type: "press",
          pointerType,
          target: originalEvent.currentTarget,
          shiftKey: originalEvent.shiftKey,
          metaKey: originalEvent.metaKey,
          ctrlKey: originalEvent.ctrlKey,
          altKey: originalEvent.altKey
        });
    };
    let triggerPressUp = (originalEvent, pointerType) => {
      let { onPressUp, isDisabled } = propsRef.current;
      if (isDisabled)
        return;
      if (onPressUp)
        onPressUp({
          type: "pressup",
          pointerType,
          target: originalEvent.currentTarget,
          shiftKey: originalEvent.shiftKey,
          metaKey: originalEvent.metaKey,
          ctrlKey: originalEvent.ctrlKey,
          altKey: originalEvent.altKey
        });
    };
    let cancel = (e2) => {
      if (state2.isPressed) {
        if (state2.isOverTarget)
          triggerPressEnd($f6c31cce2adf654f$var$createEvent(state2.target, e2), state2.pointerType, false);
        state2.isPressed = false;
        state2.isOverTarget = false;
        state2.activePointerId = null;
        state2.pointerType = null;
        removeAllGlobalListeners();
        if (!allowTextSelectionOnPress)
          $14c0b72509d70225$export$b0d6fa1ab32e3295(state2.target);
      }
    };
    let pressProps = {
      onKeyDown(e2) {
        if ($f6c31cce2adf654f$var$isValidKeyboardEvent(e2.nativeEvent) && e2.currentTarget.contains(e2.target)) {
          if ($f6c31cce2adf654f$var$shouldPreventDefaultKeyboard(e2.target))
            e2.preventDefault();
          e2.stopPropagation();
          if (!state2.isPressed && !e2.repeat) {
            state2.target = e2.currentTarget;
            state2.isPressed = true;
            triggerPressStart(e2, "keyboard");
            addGlobalListener(document, "keyup", onKeyUp, false);
          }
        }
      },
      onKeyUp(e2) {
        if ($f6c31cce2adf654f$var$isValidKeyboardEvent(e2.nativeEvent) && !e2.repeat && e2.currentTarget.contains(e2.target))
          triggerPressUp($f6c31cce2adf654f$var$createEvent(state2.target, e2), "keyboard");
      },
      onClick(e2) {
        if (e2 && !e2.currentTarget.contains(e2.target))
          return;
        if (e2 && e2.button === 0) {
          e2.stopPropagation();
          if (isDisabled1)
            e2.preventDefault();
          if (!state2.ignoreClickAfterPress && !state2.ignoreEmulatedMouseEvents && (state2.pointerType === "virtual" || $8a9cb279dc87e130$export$60278871457622de(e2.nativeEvent))) {
            if (!isDisabled1 && !preventFocusOnPress)
              $7215afc6de606d6b$export$de79e2c695e052f3(e2.currentTarget);
            triggerPressStart(e2, "virtual");
            triggerPressUp(e2, "virtual");
            triggerPressEnd(e2, "virtual");
          }
          state2.ignoreEmulatedMouseEvents = false;
          state2.ignoreClickAfterPress = false;
        }
      }
    };
    let onKeyUp = (e2) => {
      if (state2.isPressed && $f6c31cce2adf654f$var$isValidKeyboardEvent(e2)) {
        if ($f6c31cce2adf654f$var$shouldPreventDefaultKeyboard(e2.target))
          e2.preventDefault();
        e2.stopPropagation();
        state2.isPressed = false;
        let target = e2.target;
        triggerPressEnd($f6c31cce2adf654f$var$createEvent(state2.target, e2), "keyboard", state2.target.contains(target));
        removeAllGlobalListeners();
        if (state2.target.contains(target) && $f6c31cce2adf654f$var$isHTMLAnchorLink(state2.target) || state2.target.getAttribute("role") === "link")
          state2.target.click();
      }
    };
    if (typeof PointerEvent !== "undefined") {
      pressProps.onPointerDown = (e2) => {
        if (e2.button !== 0 || !e2.currentTarget.contains(e2.target))
          return;
        if ($f6c31cce2adf654f$var$isVirtualPointerEvent(e2.nativeEvent)) {
          state2.pointerType = "virtual";
          return;
        }
        if ($f6c31cce2adf654f$var$shouldPreventDefault(e2.currentTarget))
          e2.preventDefault();
        state2.pointerType = e2.pointerType;
        e2.stopPropagation();
        if (!state2.isPressed) {
          state2.isPressed = true;
          state2.isOverTarget = true;
          state2.activePointerId = e2.pointerId;
          state2.target = e2.currentTarget;
          if (!isDisabled1 && !preventFocusOnPress)
            $7215afc6de606d6b$export$de79e2c695e052f3(e2.currentTarget);
          if (!allowTextSelectionOnPress)
            $14c0b72509d70225$export$16a4697467175487(state2.target);
          triggerPressStart(e2, state2.pointerType);
          addGlobalListener(document, "pointermove", onPointerMove, false);
          addGlobalListener(document, "pointerup", onPointerUp, false);
          addGlobalListener(document, "pointercancel", onPointerCancel, false);
        }
      };
      pressProps.onMouseDown = (e2) => {
        if (!e2.currentTarget.contains(e2.target))
          return;
        if (e2.button === 0) {
          if ($f6c31cce2adf654f$var$shouldPreventDefault(e2.currentTarget))
            e2.preventDefault();
          e2.stopPropagation();
        }
      };
      pressProps.onPointerUp = (e2) => {
        if (!e2.currentTarget.contains(e2.target) || state2.pointerType === "virtual")
          return;
        if (e2.button === 0 && $f6c31cce2adf654f$var$isOverTarget(e2, e2.currentTarget))
          triggerPressUp(e2, state2.pointerType || e2.pointerType);
      };
      let onPointerMove = (e2) => {
        if (e2.pointerId !== state2.activePointerId)
          return;
        if ($f6c31cce2adf654f$var$isOverTarget(e2, state2.target)) {
          if (!state2.isOverTarget) {
            state2.isOverTarget = true;
            triggerPressStart($f6c31cce2adf654f$var$createEvent(state2.target, e2), state2.pointerType);
          }
        } else if (state2.isOverTarget) {
          state2.isOverTarget = false;
          triggerPressEnd($f6c31cce2adf654f$var$createEvent(state2.target, e2), state2.pointerType, false);
          if (propsRef.current.shouldCancelOnPointerExit)
            cancel(e2);
        }
      };
      let onPointerUp = (e2) => {
        if (e2.pointerId === state2.activePointerId && state2.isPressed && e2.button === 0) {
          if ($f6c31cce2adf654f$var$isOverTarget(e2, state2.target))
            triggerPressEnd($f6c31cce2adf654f$var$createEvent(state2.target, e2), state2.pointerType);
          else if (state2.isOverTarget)
            triggerPressEnd($f6c31cce2adf654f$var$createEvent(state2.target, e2), state2.pointerType, false);
          state2.isPressed = false;
          state2.isOverTarget = false;
          state2.activePointerId = null;
          state2.pointerType = null;
          removeAllGlobalListeners();
          if (!allowTextSelectionOnPress)
            $14c0b72509d70225$export$b0d6fa1ab32e3295(state2.target);
        }
      };
      let onPointerCancel = (e2) => {
        cancel(e2);
      };
      pressProps.onDragStart = (e2) => {
        if (!e2.currentTarget.contains(e2.target))
          return;
        cancel(e2);
      };
    } else {
      pressProps.onMouseDown = (e2) => {
        if (e2.button !== 0 || !e2.currentTarget.contains(e2.target))
          return;
        if ($f6c31cce2adf654f$var$shouldPreventDefault(e2.currentTarget))
          e2.preventDefault();
        e2.stopPropagation();
        if (state2.ignoreEmulatedMouseEvents)
          return;
        state2.isPressed = true;
        state2.isOverTarget = true;
        state2.target = e2.currentTarget;
        state2.pointerType = $8a9cb279dc87e130$export$60278871457622de(e2.nativeEvent) ? "virtual" : "mouse";
        if (!isDisabled1 && !preventFocusOnPress)
          $7215afc6de606d6b$export$de79e2c695e052f3(e2.currentTarget);
        triggerPressStart(e2, state2.pointerType);
        addGlobalListener(document, "mouseup", onMouseUp, false);
      };
      pressProps.onMouseEnter = (e2) => {
        if (!e2.currentTarget.contains(e2.target))
          return;
        e2.stopPropagation();
        if (state2.isPressed && !state2.ignoreEmulatedMouseEvents) {
          state2.isOverTarget = true;
          triggerPressStart(e2, state2.pointerType);
        }
      };
      pressProps.onMouseLeave = (e2) => {
        if (!e2.currentTarget.contains(e2.target))
          return;
        e2.stopPropagation();
        if (state2.isPressed && !state2.ignoreEmulatedMouseEvents) {
          state2.isOverTarget = false;
          triggerPressEnd(e2, state2.pointerType, false);
          if (propsRef.current.shouldCancelOnPointerExit)
            cancel(e2);
        }
      };
      pressProps.onMouseUp = (e2) => {
        if (!e2.currentTarget.contains(e2.target))
          return;
        if (!state2.ignoreEmulatedMouseEvents && e2.button === 0)
          triggerPressUp(e2, state2.pointerType);
      };
      let onMouseUp = (e2) => {
        if (e2.button !== 0)
          return;
        state2.isPressed = false;
        removeAllGlobalListeners();
        if (state2.ignoreEmulatedMouseEvents) {
          state2.ignoreEmulatedMouseEvents = false;
          return;
        }
        if ($f6c31cce2adf654f$var$isOverTarget(e2, state2.target))
          triggerPressEnd($f6c31cce2adf654f$var$createEvent(state2.target, e2), state2.pointerType);
        else if (state2.isOverTarget)
          triggerPressEnd($f6c31cce2adf654f$var$createEvent(state2.target, e2), state2.pointerType, false);
        state2.isOverTarget = false;
      };
      pressProps.onTouchStart = (e2) => {
        if (!e2.currentTarget.contains(e2.target))
          return;
        e2.stopPropagation();
        let touch = $f6c31cce2adf654f$var$getTouchFromEvent(e2.nativeEvent);
        if (!touch)
          return;
        state2.activePointerId = touch.identifier;
        state2.ignoreEmulatedMouseEvents = true;
        state2.isOverTarget = true;
        state2.isPressed = true;
        state2.target = e2.currentTarget;
        state2.pointerType = "touch";
        if (!isDisabled1 && !preventFocusOnPress)
          $7215afc6de606d6b$export$de79e2c695e052f3(e2.currentTarget);
        if (!allowTextSelectionOnPress)
          $14c0b72509d70225$export$16a4697467175487(state2.target);
        triggerPressStart(e2, state2.pointerType);
        addGlobalListener(window, "scroll", onScroll, true);
      };
      pressProps.onTouchMove = (e2) => {
        if (!e2.currentTarget.contains(e2.target))
          return;
        e2.stopPropagation();
        if (!state2.isPressed)
          return;
        let touch = $f6c31cce2adf654f$var$getTouchById(e2.nativeEvent, state2.activePointerId);
        if (touch && $f6c31cce2adf654f$var$isOverTarget(touch, e2.currentTarget)) {
          if (!state2.isOverTarget) {
            state2.isOverTarget = true;
            triggerPressStart(e2, state2.pointerType);
          }
        } else if (state2.isOverTarget) {
          state2.isOverTarget = false;
          triggerPressEnd(e2, state2.pointerType, false);
          if (propsRef.current.shouldCancelOnPointerExit)
            cancel(e2);
        }
      };
      pressProps.onTouchEnd = (e2) => {
        if (!e2.currentTarget.contains(e2.target))
          return;
        e2.stopPropagation();
        if (!state2.isPressed)
          return;
        let touch = $f6c31cce2adf654f$var$getTouchById(e2.nativeEvent, state2.activePointerId);
        if (touch && $f6c31cce2adf654f$var$isOverTarget(touch, e2.currentTarget)) {
          triggerPressUp(e2, state2.pointerType);
          triggerPressEnd(e2, state2.pointerType);
        } else if (state2.isOverTarget)
          triggerPressEnd(e2, state2.pointerType, false);
        state2.isPressed = false;
        state2.activePointerId = null;
        state2.isOverTarget = false;
        state2.ignoreEmulatedMouseEvents = true;
        if (!allowTextSelectionOnPress)
          $14c0b72509d70225$export$b0d6fa1ab32e3295(state2.target);
        removeAllGlobalListeners();
      };
      pressProps.onTouchCancel = (e2) => {
        if (!e2.currentTarget.contains(e2.target))
          return;
        e2.stopPropagation();
        if (state2.isPressed)
          cancel(e2);
      };
      let onScroll = (e2) => {
        if (state2.isPressed && e2.target.contains(state2.target))
          cancel({
            currentTarget: state2.target,
            shiftKey: false,
            ctrlKey: false,
            metaKey: false,
            altKey: false
          });
      };
      pressProps.onDragStart = (e2) => {
        if (!e2.currentTarget.contains(e2.target))
          return;
        cancel(e2);
      };
    }
    return pressProps;
  }, [
    addGlobalListener,
    isDisabled1,
    preventFocusOnPress,
    removeAllGlobalListeners,
    allowTextSelectionOnPress
  ]);
  useEffect(() => {
    return () => {
      if (!allowTextSelectionOnPress)
        $14c0b72509d70225$export$b0d6fa1ab32e3295(ref.current.target);
    };
  }, [
    allowTextSelectionOnPress
  ]);
  return {
    isPressed: isPressedProp || isPressed,
    pressProps: $3ef42575df84b30b$export$9d1611c77c2fe928(domProps, pressProps1)
  };
}
function $f6c31cce2adf654f$var$isHTMLAnchorLink(target) {
  return target.tagName === "A" && target.hasAttribute("href");
}
function $f6c31cce2adf654f$var$isValidKeyboardEvent(event) {
  const { key, code, target } = event;
  const element = target;
  const { tagName, isContentEditable } = element;
  const role = element.getAttribute("role");
  return (key === "Enter" || key === " " || key === "Spacebar" || code === "Space") && tagName !== "INPUT" && tagName !== "TEXTAREA" && isContentEditable !== true && (!$f6c31cce2adf654f$var$isHTMLAnchorLink(element) || role === "button" && key !== "Enter") && !(role === "link" && key !== "Enter");
}
function $f6c31cce2adf654f$var$getTouchFromEvent(event) {
  const { targetTouches } = event;
  if (targetTouches.length > 0)
    return targetTouches[0];
  return null;
}
function $f6c31cce2adf654f$var$getTouchById(event, pointerId2) {
  const changedTouches = event.changedTouches;
  for (let i2 = 0; i2 < changedTouches.length; i2++) {
    const touch = changedTouches[i2];
    if (touch.identifier === pointerId2)
      return touch;
  }
  return null;
}
function $f6c31cce2adf654f$var$createEvent(target, e2) {
  return {
    currentTarget: target,
    shiftKey: e2.shiftKey,
    ctrlKey: e2.ctrlKey,
    metaKey: e2.metaKey,
    altKey: e2.altKey
  };
}
function $f6c31cce2adf654f$var$getPointClientRect(point) {
  let offsetX = point.width / 2 || point.radiusX || 0;
  let offsetY = point.height / 2 || point.radiusY || 0;
  return {
    top: point.clientY - offsetY,
    right: point.clientX + offsetX,
    bottom: point.clientY + offsetY,
    left: point.clientX - offsetX
  };
}
function $f6c31cce2adf654f$var$areRectanglesOverlapping(a2, b2) {
  if (a2.left > b2.right || b2.left > a2.right)
    return false;
  if (a2.top > b2.bottom || b2.top > a2.bottom)
    return false;
  return true;
}
function $f6c31cce2adf654f$var$isOverTarget(point, target) {
  let rect = target.getBoundingClientRect();
  let pointRect = $f6c31cce2adf654f$var$getPointClientRect(point);
  return $f6c31cce2adf654f$var$areRectanglesOverlapping(rect, pointRect);
}
function $f6c31cce2adf654f$var$shouldPreventDefault(target) {
  return !target.draggable;
}
function $f6c31cce2adf654f$var$shouldPreventDefaultKeyboard(target) {
  return !((target.tagName === "INPUT" || target.tagName === "BUTTON") && target.type === "submit");
}
function $f6c31cce2adf654f$var$isVirtualPointerEvent(event) {
  return event.width === 0 && event.height === 0 || event.width === 1 && event.height === 1 && event.pressure === 0 && event.detail === 0;
}
const $3b117e43dc0ca95d$export$27c701ed9e449e99 = /* @__PURE__ */ React__default.forwardRef((_a2, ref) => {
  var _b = _a2, { children } = _b, props2 = __objRest(_b, ["children"]);
  let newRef = useRef();
  ref = ref !== null && ref !== void 0 ? ref : newRef;
  let { pressProps } = $f6c31cce2adf654f$export$45712eceda6fad21(__spreadProps(__spreadValues({}, props2), {
    ref
  }));
  let child = React__default.Children.only(children);
  return /* @__PURE__ */ React__default.cloneElement(child, __spreadValues({
    ref
  }, $3ef42575df84b30b$export$9d1611c77c2fe928(child.props, pressProps)));
});
var $f1ab8c75478c6f73$exports = {};
$parcel$export$y($f1ab8c75478c6f73$exports, "PressResponder", () => $f1ab8c75478c6f73$export$3351871ee4b288b8);
const $f1ab8c75478c6f73$export$3351871ee4b288b8 = /* @__PURE__ */ React__default.forwardRef((_c, ref) => {
  var _d = _c, { children } = _d, props2 = __objRest(_d, ["children"]);
  let isRegistered = useRef(false);
  let prevContext = useContext($ae1eeba8b9eafd08$export$5165eccb35aaadb5);
  let context = $3ef42575df84b30b$export$9d1611c77c2fe928(prevContext || {}, __spreadProps(__spreadValues({}, props2), {
    ref: ref || (prevContext === null || prevContext === void 0 ? void 0 : prevContext.ref),
    register() {
      isRegistered.current = true;
      if (prevContext)
        prevContext.register();
    }
  }));
  $e7801be82b4b2a53$export$4debdb1a3f0fa79e(prevContext, ref);
  useEffect(() => {
    if (!isRegistered.current)
      console.warn("A PressResponder was rendered without a pressable child. Either call the usePress hook, or wrap your DOM node with <Pressable> component.");
  }, []);
  return /* @__PURE__ */ React__default.createElement($ae1eeba8b9eafd08$export$5165eccb35aaadb5.Provider, {
    value: context
  }, children);
});
var $a1ea59d68270f0dd$exports = {};
$parcel$export$y($a1ea59d68270f0dd$exports, "useFocus", () => $a1ea59d68270f0dd$export$f8168d8dd8fd66e6);
function $a1ea59d68270f0dd$export$f8168d8dd8fd66e6(props2) {
  if (props2.isDisabled)
    return {
      focusProps: {}
    };
  let onFocus, onBlur;
  if (props2.onFocus || props2.onFocusChange)
    onFocus = (e2) => {
      if (e2.target === e2.currentTarget) {
        if (props2.onFocus)
          props2.onFocus(e2);
        if (props2.onFocusChange)
          props2.onFocusChange(true);
      }
    };
  if (props2.onBlur || props2.onFocusChange)
    onBlur = (e2) => {
      if (e2.target === e2.currentTarget) {
        if (props2.onBlur)
          props2.onBlur(e2);
        if (props2.onFocusChange)
          props2.onFocusChange(false);
      }
    };
  return {
    focusProps: {
      onFocus,
      onBlur
    }
  };
}
var $507fabe10e71c6fb$exports = {};
$parcel$export$y($507fabe10e71c6fb$exports, "isFocusVisible", () => $507fabe10e71c6fb$export$b9b3dfddab17db27);
$parcel$export$y($507fabe10e71c6fb$exports, "getInteractionModality", () => $507fabe10e71c6fb$export$630ff653c5ada6a9);
$parcel$export$y($507fabe10e71c6fb$exports, "setInteractionModality", () => $507fabe10e71c6fb$export$8397ddfc504fdb9a);
$parcel$export$y($507fabe10e71c6fb$exports, "useInteractionModality", () => $507fabe10e71c6fb$export$98e20ec92f614cfe);
$parcel$export$y($507fabe10e71c6fb$exports, "useFocusVisible", () => $507fabe10e71c6fb$export$ffd9e5021c1fb2d6);
$parcel$export$y($507fabe10e71c6fb$exports, "useFocusVisibleListener", () => $507fabe10e71c6fb$export$ec71b4b83ac08ec3);
let $507fabe10e71c6fb$var$currentModality = null;
let $507fabe10e71c6fb$var$changeHandlers = /* @__PURE__ */ new Set();
let $507fabe10e71c6fb$var$hasSetupGlobalListeners = false;
let $507fabe10e71c6fb$var$hasEventBeforeFocus = false;
let $507fabe10e71c6fb$var$hasBlurredWindowRecently = false;
const $507fabe10e71c6fb$var$FOCUS_VISIBLE_INPUT_KEYS = {
  Tab: true,
  Escape: true
};
function $507fabe10e71c6fb$var$triggerChangeHandlers(modality, e2) {
  for (let handler of $507fabe10e71c6fb$var$changeHandlers)
    handler(modality, e2);
}
function $507fabe10e71c6fb$var$isValidKey(e2) {
  return !(e2.metaKey || !$c87311424ea30a05$export$9ac100e40613ea10() && e2.altKey || e2.ctrlKey || e2.key === "Control" || e2.key === "Shift" || e2.key === "Meta");
}
function $507fabe10e71c6fb$var$handleKeyboardEvent(e2) {
  $507fabe10e71c6fb$var$hasEventBeforeFocus = true;
  if ($507fabe10e71c6fb$var$isValidKey(e2)) {
    $507fabe10e71c6fb$var$currentModality = "keyboard";
    $507fabe10e71c6fb$var$triggerChangeHandlers("keyboard", e2);
  }
}
function $507fabe10e71c6fb$var$handlePointerEvent(e2) {
  $507fabe10e71c6fb$var$currentModality = "pointer";
  if (e2.type === "mousedown" || e2.type === "pointerdown") {
    $507fabe10e71c6fb$var$hasEventBeforeFocus = true;
    $507fabe10e71c6fb$var$triggerChangeHandlers("pointer", e2);
  }
}
function $507fabe10e71c6fb$var$handleClickEvent(e2) {
  if ($8a9cb279dc87e130$export$60278871457622de(e2)) {
    $507fabe10e71c6fb$var$hasEventBeforeFocus = true;
    $507fabe10e71c6fb$var$currentModality = "virtual";
  }
}
function $507fabe10e71c6fb$var$handleFocusEvent(e2) {
  if (e2.target === window || e2.target === document)
    return;
  if (!$507fabe10e71c6fb$var$hasEventBeforeFocus && !$507fabe10e71c6fb$var$hasBlurredWindowRecently) {
    $507fabe10e71c6fb$var$currentModality = "virtual";
    $507fabe10e71c6fb$var$triggerChangeHandlers("virtual", e2);
  }
  $507fabe10e71c6fb$var$hasEventBeforeFocus = false;
  $507fabe10e71c6fb$var$hasBlurredWindowRecently = false;
}
function $507fabe10e71c6fb$var$handleWindowBlur() {
  $507fabe10e71c6fb$var$hasEventBeforeFocus = false;
  $507fabe10e71c6fb$var$hasBlurredWindowRecently = true;
}
function $507fabe10e71c6fb$var$setupGlobalFocusEvents() {
  if (typeof window === "undefined" || $507fabe10e71c6fb$var$hasSetupGlobalListeners)
    return;
  let focus = HTMLElement.prototype.focus;
  HTMLElement.prototype.focus = function() {
    $507fabe10e71c6fb$var$hasEventBeforeFocus = true;
    focus.apply(this, arguments);
  };
  document.addEventListener("keydown", $507fabe10e71c6fb$var$handleKeyboardEvent, true);
  document.addEventListener("keyup", $507fabe10e71c6fb$var$handleKeyboardEvent, true);
  document.addEventListener("click", $507fabe10e71c6fb$var$handleClickEvent, true);
  window.addEventListener("focus", $507fabe10e71c6fb$var$handleFocusEvent, true);
  window.addEventListener("blur", $507fabe10e71c6fb$var$handleWindowBlur, false);
  if (typeof PointerEvent !== "undefined") {
    document.addEventListener("pointerdown", $507fabe10e71c6fb$var$handlePointerEvent, true);
    document.addEventListener("pointermove", $507fabe10e71c6fb$var$handlePointerEvent, true);
    document.addEventListener("pointerup", $507fabe10e71c6fb$var$handlePointerEvent, true);
  } else {
    document.addEventListener("mousedown", $507fabe10e71c6fb$var$handlePointerEvent, true);
    document.addEventListener("mousemove", $507fabe10e71c6fb$var$handlePointerEvent, true);
    document.addEventListener("mouseup", $507fabe10e71c6fb$var$handlePointerEvent, true);
  }
  $507fabe10e71c6fb$var$hasSetupGlobalListeners = true;
}
if (typeof document !== "undefined") {
  if (document.readyState !== "loading")
    $507fabe10e71c6fb$var$setupGlobalFocusEvents();
  else
    document.addEventListener("DOMContentLoaded", $507fabe10e71c6fb$var$setupGlobalFocusEvents);
}
function $507fabe10e71c6fb$export$b9b3dfddab17db27() {
  return $507fabe10e71c6fb$var$currentModality !== "pointer";
}
function $507fabe10e71c6fb$export$630ff653c5ada6a9() {
  return $507fabe10e71c6fb$var$currentModality;
}
function $507fabe10e71c6fb$export$8397ddfc504fdb9a(modality) {
  $507fabe10e71c6fb$var$currentModality = modality;
  $507fabe10e71c6fb$var$triggerChangeHandlers(modality, null);
}
function $507fabe10e71c6fb$export$98e20ec92f614cfe() {
  $507fabe10e71c6fb$var$setupGlobalFocusEvents();
  let [modality, setModality] = useState($507fabe10e71c6fb$var$currentModality);
  useEffect(() => {
    let handler = () => {
      setModality($507fabe10e71c6fb$var$currentModality);
    };
    $507fabe10e71c6fb$var$changeHandlers.add(handler);
    return () => {
      $507fabe10e71c6fb$var$changeHandlers.delete(handler);
    };
  }, []);
  return modality;
}
function $507fabe10e71c6fb$var$isKeyboardFocusEvent(isTextInput, modality, e2) {
  return !(isTextInput && modality === "keyboard" && e2 instanceof KeyboardEvent && !$507fabe10e71c6fb$var$FOCUS_VISIBLE_INPUT_KEYS[e2.key]);
}
function $507fabe10e71c6fb$export$ffd9e5021c1fb2d6(props2 = {}) {
  let { isTextInput, autoFocus } = props2;
  let [isFocusVisibleState, setFocusVisible] = useState(autoFocus || $507fabe10e71c6fb$export$b9b3dfddab17db27());
  $507fabe10e71c6fb$export$ec71b4b83ac08ec3(($507fabe10e71c6fb$export$b9b3dfddab17db272) => {
    setFocusVisible($507fabe10e71c6fb$export$b9b3dfddab17db272);
  }, [
    isTextInput
  ], {
    isTextInput
  });
  return {
    isFocusVisible: isFocusVisibleState
  };
}
function $507fabe10e71c6fb$export$ec71b4b83ac08ec3(fn2, deps, opts) {
  $507fabe10e71c6fb$var$setupGlobalFocusEvents();
  useEffect(() => {
    let handler = (modality, e2) => {
      if (!$507fabe10e71c6fb$var$isKeyboardFocusEvent(opts === null || opts === void 0 ? void 0 : opts.isTextInput, modality, e2))
        return;
      fn2($507fabe10e71c6fb$export$b9b3dfddab17db27());
    };
    $507fabe10e71c6fb$var$changeHandlers.add(handler);
    return () => {
      $507fabe10e71c6fb$var$changeHandlers.delete(handler);
    };
  }, deps);
}
var $9ab94262bd0047c7$exports = {};
$parcel$export$y($9ab94262bd0047c7$exports, "useFocusWithin", () => $9ab94262bd0047c7$export$420e68273165f4ec);
function $9ab94262bd0047c7$export$420e68273165f4ec(props2) {
  let state2 = useRef({
    isFocusWithin: false
  }).current;
  if (props2.isDisabled)
    return {
      focusWithinProps: {}
    };
  let onFocus = (e2) => {
    if (!state2.isFocusWithin) {
      if (props2.onFocusWithin)
        props2.onFocusWithin(e2);
      if (props2.onFocusWithinChange)
        props2.onFocusWithinChange(true);
      state2.isFocusWithin = true;
    }
  };
  let onBlur = (e2) => {
    if (state2.isFocusWithin && !e2.currentTarget.contains(e2.relatedTarget)) {
      if (props2.onBlurWithin)
        props2.onBlurWithin(e2);
      if (props2.onFocusWithinChange)
        props2.onFocusWithinChange(false);
      state2.isFocusWithin = false;
    }
  };
  return {
    focusWithinProps: {
      onFocus,
      onBlur
    }
  };
}
var $6179b936705e76d3$exports = {};
$parcel$export$y($6179b936705e76d3$exports, "useHover", () => $6179b936705e76d3$export$ae780daf29e6d456);
let $6179b936705e76d3$var$globalIgnoreEmulatedMouseEvents = false;
let $6179b936705e76d3$var$hoverCount = 0;
function $6179b936705e76d3$var$setGlobalIgnoreEmulatedMouseEvents() {
  $6179b936705e76d3$var$globalIgnoreEmulatedMouseEvents = true;
  setTimeout(() => {
    $6179b936705e76d3$var$globalIgnoreEmulatedMouseEvents = false;
  }, 50);
}
function $6179b936705e76d3$var$handleGlobalPointerEvent(e2) {
  if (e2.pointerType === "touch")
    $6179b936705e76d3$var$setGlobalIgnoreEmulatedMouseEvents();
}
function $6179b936705e76d3$var$setupGlobalTouchEvents() {
  if (typeof document === "undefined")
    return;
  if (typeof PointerEvent !== "undefined")
    document.addEventListener("pointerup", $6179b936705e76d3$var$handleGlobalPointerEvent);
  else
    document.addEventListener("touchend", $6179b936705e76d3$var$setGlobalIgnoreEmulatedMouseEvents);
  $6179b936705e76d3$var$hoverCount++;
  return () => {
    $6179b936705e76d3$var$hoverCount--;
    if ($6179b936705e76d3$var$hoverCount > 0)
      return;
    if (typeof PointerEvent !== "undefined")
      document.removeEventListener("pointerup", $6179b936705e76d3$var$handleGlobalPointerEvent);
    else
      document.removeEventListener("touchend", $6179b936705e76d3$var$setGlobalIgnoreEmulatedMouseEvents);
  };
}
function $6179b936705e76d3$export$ae780daf29e6d456(props2) {
  let { onHoverStart, onHoverChange, onHoverEnd, isDisabled } = props2;
  let [isHovered, setHovered] = useState(false);
  let state2 = useRef({
    isHovered: false,
    ignoreEmulatedMouseEvents: false,
    pointerType: "",
    target: null
  }).current;
  useEffect($6179b936705e76d3$var$setupGlobalTouchEvents, []);
  let { hoverProps: hoverProps1, triggerHoverEnd: triggerHoverEnd1 } = useMemo(() => {
    let triggerHoverStart = (event, pointerType) => {
      state2.pointerType = pointerType;
      if (isDisabled || pointerType === "touch" || state2.isHovered || !event.currentTarget.contains(event.target))
        return;
      state2.isHovered = true;
      let target = event.currentTarget;
      state2.target = target;
      if (onHoverStart)
        onHoverStart({
          type: "hoverstart",
          target,
          pointerType
        });
      if (onHoverChange)
        onHoverChange(true);
      setHovered(true);
    };
    let triggerHoverEnd = (event, pointerType) => {
      state2.pointerType = "";
      state2.target = null;
      if (pointerType === "touch" || !state2.isHovered)
        return;
      state2.isHovered = false;
      let target = event.currentTarget;
      if (onHoverEnd)
        onHoverEnd({
          type: "hoverend",
          target,
          pointerType
        });
      if (onHoverChange)
        onHoverChange(false);
      setHovered(false);
    };
    let hoverProps = {};
    if (typeof PointerEvent !== "undefined") {
      hoverProps.onPointerEnter = (e2) => {
        if ($6179b936705e76d3$var$globalIgnoreEmulatedMouseEvents && e2.pointerType === "mouse")
          return;
        triggerHoverStart(e2, e2.pointerType);
      };
      hoverProps.onPointerLeave = (e2) => {
        if (!isDisabled && e2.currentTarget.contains(e2.target))
          triggerHoverEnd(e2, e2.pointerType);
      };
    } else {
      hoverProps.onTouchStart = () => {
        state2.ignoreEmulatedMouseEvents = true;
      };
      hoverProps.onMouseEnter = (e2) => {
        if (!state2.ignoreEmulatedMouseEvents && !$6179b936705e76d3$var$globalIgnoreEmulatedMouseEvents)
          triggerHoverStart(e2, "mouse");
        state2.ignoreEmulatedMouseEvents = false;
      };
      hoverProps.onMouseLeave = (e2) => {
        if (!isDisabled && e2.currentTarget.contains(e2.target))
          triggerHoverEnd(e2, "mouse");
      };
    }
    return {
      hoverProps,
      triggerHoverEnd
    };
  }, [
    onHoverStart,
    onHoverChange,
    onHoverEnd,
    isDisabled,
    state2
  ]);
  useEffect(() => {
    if (isDisabled)
      triggerHoverEnd1({
        currentTarget: state2.target
      }, state2.pointerType);
  }, [
    isDisabled
  ]);
  return {
    hoverProps: hoverProps1,
    isHovered
  };
}
var $e0b6e0b68ec7f50f$exports = {};
$parcel$export$y($e0b6e0b68ec7f50f$exports, "useInteractOutside", () => $e0b6e0b68ec7f50f$export$872b660ac5a1ff98);
function $e0b6e0b68ec7f50f$export$872b660ac5a1ff98(props2) {
  let { ref, onInteractOutside, isDisabled, onInteractOutsideStart } = props2;
  let stateRef = useRef({
    isPointerDown: false,
    ignoreEmulatedMouseEvents: false,
    onInteractOutside,
    onInteractOutsideStart
  });
  let state2 = stateRef.current;
  state2.onInteractOutside = onInteractOutside;
  state2.onInteractOutsideStart = onInteractOutsideStart;
  useEffect(() => {
    if (isDisabled)
      return;
    let onPointerDown = (e2) => {
      if ($e0b6e0b68ec7f50f$var$isValidEvent(e2, ref) && state2.onInteractOutside) {
        if (state2.onInteractOutsideStart)
          state2.onInteractOutsideStart(e2);
        state2.isPointerDown = true;
      }
    };
    if (typeof PointerEvent !== "undefined") {
      let onPointerUp = (e2) => {
        if (state2.isPointerDown && state2.onInteractOutside && $e0b6e0b68ec7f50f$var$isValidEvent(e2, ref)) {
          state2.isPointerDown = false;
          state2.onInteractOutside(e2);
        }
      };
      document.addEventListener("pointerdown", onPointerDown, true);
      document.addEventListener("pointerup", onPointerUp, true);
      return () => {
        document.removeEventListener("pointerdown", onPointerDown, true);
        document.removeEventListener("pointerup", onPointerUp, true);
      };
    } else {
      let onMouseUp = (e2) => {
        if (state2.ignoreEmulatedMouseEvents)
          state2.ignoreEmulatedMouseEvents = false;
        else if (state2.isPointerDown && state2.onInteractOutside && $e0b6e0b68ec7f50f$var$isValidEvent(e2, ref)) {
          state2.isPointerDown = false;
          state2.onInteractOutside(e2);
        }
      };
      let onTouchEnd = (e2) => {
        state2.ignoreEmulatedMouseEvents = true;
        if (state2.onInteractOutside && state2.isPointerDown && $e0b6e0b68ec7f50f$var$isValidEvent(e2, ref)) {
          state2.isPointerDown = false;
          state2.onInteractOutside(e2);
        }
      };
      document.addEventListener("mousedown", onPointerDown, true);
      document.addEventListener("mouseup", onMouseUp, true);
      document.addEventListener("touchstart", onPointerDown, true);
      document.addEventListener("touchend", onTouchEnd, true);
      return () => {
        document.removeEventListener("mousedown", onPointerDown, true);
        document.removeEventListener("mouseup", onMouseUp, true);
        document.removeEventListener("touchstart", onPointerDown, true);
        document.removeEventListener("touchend", onTouchEnd, true);
      };
    }
  }, [
    ref,
    state2,
    isDisabled
  ]);
}
function $e0b6e0b68ec7f50f$var$isValidEvent(event, ref) {
  if (event.button > 0)
    return false;
  if (event.target) {
    const ownerDocument2 = event.target.ownerDocument;
    if (!ownerDocument2 || !ownerDocument2.documentElement.contains(event.target))
      return false;
  }
  return ref.current && !ref.current.contains(event.target);
}
var $46d819fcbaf35654$exports = {};
$parcel$export$y($46d819fcbaf35654$exports, "useKeyboard", () => $46d819fcbaf35654$export$8f71654801c2f7cd);
function $93925083ecbb358c$export$48d1ea6320830260(handler) {
  if (!handler)
    return;
  let shouldStopPropagation = true;
  return (e2) => {
    let event = __spreadProps(__spreadValues({}, e2), {
      preventDefault() {
        e2.preventDefault();
      },
      isDefaultPrevented() {
        return e2.isDefaultPrevented();
      },
      stopPropagation() {
        console.error("stopPropagation is now the default behavior for events in React Spectrum. You can use continuePropagation() to revert this behavior.");
      },
      continuePropagation() {
        shouldStopPropagation = false;
      }
    });
    handler(event);
    if (shouldStopPropagation)
      e2.stopPropagation();
  };
}
function $46d819fcbaf35654$export$8f71654801c2f7cd(props2) {
  return {
    keyboardProps: props2.isDisabled ? {} : {
      onKeyDown: $93925083ecbb358c$export$48d1ea6320830260(props2.onKeyDown),
      onKeyUp: $93925083ecbb358c$export$48d1ea6320830260(props2.onKeyUp)
    }
  };
}
var $e8a7022cf87cba2a$exports = {};
$parcel$export$y($e8a7022cf87cba2a$exports, "useMove", () => $e8a7022cf87cba2a$export$36da96379f79f245);
function $e8a7022cf87cba2a$export$36da96379f79f245(props2) {
  let { onMoveStart, onMove, onMoveEnd } = props2;
  let state2 = useRef({
    didMove: false,
    lastPosition: null,
    id: null
  });
  let { addGlobalListener, removeGlobalListener } = $03deb23ff14920c4$export$4eaf04e54aa8eed6();
  let moveProps1 = useMemo(() => {
    let moveProps = {};
    let start = () => {
      $14c0b72509d70225$export$16a4697467175487();
      state2.current.didMove = false;
    };
    let move = (originalEvent, pointerType, deltaX, deltaY) => {
      if (deltaX === 0 && deltaY === 0)
        return;
      if (!state2.current.didMove) {
        state2.current.didMove = true;
        onMoveStart === null || onMoveStart === void 0 ? void 0 : onMoveStart({
          type: "movestart",
          pointerType,
          shiftKey: originalEvent.shiftKey,
          metaKey: originalEvent.metaKey,
          ctrlKey: originalEvent.ctrlKey,
          altKey: originalEvent.altKey
        });
      }
      onMove({
        type: "move",
        pointerType,
        deltaX,
        deltaY,
        shiftKey: originalEvent.shiftKey,
        metaKey: originalEvent.metaKey,
        ctrlKey: originalEvent.ctrlKey,
        altKey: originalEvent.altKey
      });
    };
    let end = (originalEvent, pointerType) => {
      $14c0b72509d70225$export$b0d6fa1ab32e3295();
      if (state2.current.didMove)
        onMoveEnd === null || onMoveEnd === void 0 ? void 0 : onMoveEnd({
          type: "moveend",
          pointerType,
          shiftKey: originalEvent.shiftKey,
          metaKey: originalEvent.metaKey,
          ctrlKey: originalEvent.ctrlKey,
          altKey: originalEvent.altKey
        });
    };
    if (typeof PointerEvent === "undefined") {
      let onMouseMove = (e2) => {
        if (e2.button === 0) {
          move(e2, "mouse", e2.pageX - state2.current.lastPosition.pageX, e2.pageY - state2.current.lastPosition.pageY);
          state2.current.lastPosition = {
            pageX: e2.pageX,
            pageY: e2.pageY
          };
        }
      };
      let onMouseUp = (e2) => {
        if (e2.button === 0) {
          end(e2, "mouse");
          removeGlobalListener(window, "mousemove", onMouseMove, false);
          removeGlobalListener(window, "mouseup", onMouseUp, false);
        }
      };
      moveProps.onMouseDown = (e2) => {
        if (e2.button === 0) {
          start();
          e2.stopPropagation();
          e2.preventDefault();
          state2.current.lastPosition = {
            pageX: e2.pageX,
            pageY: e2.pageY
          };
          addGlobalListener(window, "mousemove", onMouseMove, false);
          addGlobalListener(window, "mouseup", onMouseUp, false);
        }
      };
      let onTouchMove = (e2) => {
        let touch = [
          ...e2.changedTouches
        ].findIndex(({ identifier }) => identifier === state2.current.id);
        if (touch >= 0) {
          let { pageX, pageY } = e2.changedTouches[touch];
          move(e2, "touch", pageX - state2.current.lastPosition.pageX, pageY - state2.current.lastPosition.pageY);
          state2.current.lastPosition = {
            pageX,
            pageY
          };
        }
      };
      let onTouchEnd = (e2) => {
        let touch = [
          ...e2.changedTouches
        ].findIndex(({ identifier }) => identifier === state2.current.id);
        if (touch >= 0) {
          end(e2, "touch");
          state2.current.id = null;
          removeGlobalListener(window, "touchmove", onTouchMove);
          removeGlobalListener(window, "touchend", onTouchEnd);
          removeGlobalListener(window, "touchcancel", onTouchEnd);
        }
      };
      moveProps.onTouchStart = (e2) => {
        if (e2.changedTouches.length === 0 || state2.current.id != null)
          return;
        let { pageX, pageY, identifier } = e2.changedTouches[0];
        start();
        e2.stopPropagation();
        e2.preventDefault();
        state2.current.lastPosition = {
          pageX,
          pageY
        };
        state2.current.id = identifier;
        addGlobalListener(window, "touchmove", onTouchMove, false);
        addGlobalListener(window, "touchend", onTouchEnd, false);
        addGlobalListener(window, "touchcancel", onTouchEnd, false);
      };
    } else {
      let onPointerMove = (e2) => {
        if (e2.pointerId === state2.current.id) {
          let pointerType = e2.pointerType || "mouse";
          move(e2, pointerType, e2.pageX - state2.current.lastPosition.pageX, e2.pageY - state2.current.lastPosition.pageY);
          state2.current.lastPosition = {
            pageX: e2.pageX,
            pageY: e2.pageY
          };
        }
      };
      let onPointerUp = (e2) => {
        if (e2.pointerId === state2.current.id) {
          let pointerType = e2.pointerType || "mouse";
          end(e2, pointerType);
          state2.current.id = null;
          removeGlobalListener(window, "pointermove", onPointerMove, false);
          removeGlobalListener(window, "pointerup", onPointerUp, false);
          removeGlobalListener(window, "pointercancel", onPointerUp, false);
        }
      };
      moveProps.onPointerDown = (e2) => {
        if (e2.button === 0 && state2.current.id == null) {
          start();
          e2.stopPropagation();
          e2.preventDefault();
          state2.current.lastPosition = {
            pageX: e2.pageX,
            pageY: e2.pageY
          };
          state2.current.id = e2.pointerId;
          addGlobalListener(window, "pointermove", onPointerMove, false);
          addGlobalListener(window, "pointerup", onPointerUp, false);
          addGlobalListener(window, "pointercancel", onPointerUp, false);
        }
      };
    }
    let triggerKeyboardMove = (e2, deltaX, deltaY) => {
      start();
      move(e2, "keyboard", deltaX, deltaY);
      end(e2, "keyboard");
    };
    moveProps.onKeyDown = (e2) => {
      switch (e2.key) {
        case "Left":
        case "ArrowLeft":
          e2.preventDefault();
          e2.stopPropagation();
          triggerKeyboardMove(e2, -1, 0);
          break;
        case "Right":
        case "ArrowRight":
          e2.preventDefault();
          e2.stopPropagation();
          triggerKeyboardMove(e2, 1, 0);
          break;
        case "Up":
        case "ArrowUp":
          e2.preventDefault();
          e2.stopPropagation();
          triggerKeyboardMove(e2, 0, -1);
          break;
        case "Down":
        case "ArrowDown":
          e2.preventDefault();
          e2.stopPropagation();
          triggerKeyboardMove(e2, 0, 1);
          break;
      }
    };
    return moveProps;
  }, [
    state2,
    onMoveStart,
    onMove,
    onMoveEnd,
    addGlobalListener,
    removeGlobalListener
  ]);
  return {
    moveProps: moveProps1
  };
}
var $7d0a636d7a4dcefd$exports = {};
$parcel$export$y($7d0a636d7a4dcefd$exports, "useScrollWheel", () => $7d0a636d7a4dcefd$export$2123ff2b87c81ca);
function $7d0a636d7a4dcefd$export$2123ff2b87c81ca(props2, ref) {
  let { onScroll, isDisabled } = props2;
  let onScrollHandler = useCallback((e2) => {
    if (e2.ctrlKey)
      return;
    e2.preventDefault();
    e2.stopPropagation();
    if (onScroll)
      onScroll({
        deltaX: e2.deltaX,
        deltaY: e2.deltaY
      });
  }, [
    onScroll
  ]);
  $e9faafb641e167db$export$90fc3a17d93f704c(ref, "wheel", isDisabled ? null : onScrollHandler);
}
var $8a26561d2877236e$exports = {};
$parcel$export$y($8a26561d2877236e$exports, "useLongPress", () => $8a26561d2877236e$export$c24ed0104d07eab9);
const $8a26561d2877236e$var$DEFAULT_THRESHOLD = 500;
function $8a26561d2877236e$export$c24ed0104d07eab9(props2) {
  let { isDisabled, onLongPressStart, onLongPressEnd, onLongPress, threshold = $8a26561d2877236e$var$DEFAULT_THRESHOLD, accessibilityDescription } = props2;
  const timeRef = useRef(null);
  let { addGlobalListener, removeGlobalListener } = $03deb23ff14920c4$export$4eaf04e54aa8eed6();
  let { pressProps } = $f6c31cce2adf654f$export$45712eceda6fad21({
    isDisabled,
    onPressStart(e1) {
      if (e1.pointerType === "mouse" || e1.pointerType === "touch") {
        if (onLongPressStart)
          onLongPressStart(__spreadProps(__spreadValues({}, e1), {
            type: "longpressstart"
          }));
        timeRef.current = setTimeout(() => {
          e1.target.dispatchEvent(new PointerEvent("pointercancel", {
            bubbles: true
          }));
          if (onLongPress)
            onLongPress(__spreadProps(__spreadValues({}, e1), {
              type: "longpress"
            }));
          timeRef.current = null;
        }, threshold);
        if (e1.pointerType === "touch") {
          let onContextMenu = (e2) => {
            e2.preventDefault();
          };
          addGlobalListener(e1.target, "contextmenu", onContextMenu, {
            once: true
          });
          addGlobalListener(window, "pointerup", () => {
            setTimeout(() => {
              removeGlobalListener(e1.target, "contextmenu", onContextMenu);
            }, 30);
          }, {
            once: true
          });
        }
      }
    },
    onPressEnd(e2) {
      if (timeRef.current)
        clearTimeout(timeRef.current);
      if (onLongPressEnd && (e2.pointerType === "mouse" || e2.pointerType === "touch"))
        onLongPressEnd(__spreadProps(__spreadValues({}, e2), {
          type: "longpressend"
        }));
    }
  });
  let descriptionProps = $ef06256079686ba0$export$f8aeda7b10753fa1(onLongPress && !isDisabled ? accessibilityDescription : null);
  return {
    longPressProps: $3ef42575df84b30b$export$9d1611c77c2fe928(pressProps, descriptionProps)
  };
}
function $parcel$export$x(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $5c3e21d68f1c4674$exports = {};
$parcel$export$x($5c3e21d68f1c4674$exports, "useVisuallyHidden", () => $5c3e21d68f1c4674$export$a966af930f325cab);
$parcel$export$x($5c3e21d68f1c4674$exports, "VisuallyHidden", () => $5c3e21d68f1c4674$export$439d29a4e110a164);
const $5c3e21d68f1c4674$var$styles = {
  border: 0,
  clip: "rect(0 0 0 0)",
  clipPath: "inset(50%)",
  height: 1,
  margin: "0 -1px -1px 0",
  overflow: "hidden",
  padding: 0,
  position: "absolute",
  width: 1,
  whiteSpace: "nowrap"
};
function $5c3e21d68f1c4674$export$a966af930f325cab(props2 = {}) {
  let { style: style2, isFocusable } = props2;
  let [isFocused, setFocused] = useState(false);
  let { focusProps } = $a1ea59d68270f0dd$export$f8168d8dd8fd66e6({
    isDisabled: !isFocusable,
    onFocusChange: setFocused
  });
  let combinedStyles = useMemo(() => {
    if (isFocused)
      return style2;
    else if (style2)
      return __spreadValues(__spreadValues({}, $5c3e21d68f1c4674$var$styles), style2);
    else
      return $5c3e21d68f1c4674$var$styles;
  }, [
    isFocused
  ]);
  return {
    visuallyHiddenProps: __spreadProps(__spreadValues({}, focusProps), {
      style: combinedStyles
    })
  };
}
function $5c3e21d68f1c4674$export$439d29a4e110a164(props2) {
  let _a2 = props2, { children, elementType: Element2 = "div", isFocusable, style: style2 } = _a2, otherProps = __objRest(_a2, ["children", "elementType", "isFocusable", "style"]);
  let { visuallyHiddenProps } = $5c3e21d68f1c4674$export$a966af930f325cab(props2);
  return /* @__PURE__ */ React__default.createElement(Element2, $3ef42575df84b30b$export$9d1611c77c2fe928(otherProps, visuallyHiddenProps), children);
}
var fabric = {};
var __viteBrowserExternal = {};
var __viteBrowserExternal$1 = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  [Symbol.toStringTag]: "Module",
  "default": __viteBrowserExternal
});
var require$$2 = /* @__PURE__ */ getAugmentedNamespace(__viteBrowserExternal$1);
(function(exports2) {
  /*! Fabric.js Copyright 2008-2015, Printio (Juriy Zaytsev, Maxim Chernyak) */
  var fabric2 = fabric2 || { version: "4.6.0" };
  {
    exports2.fabric = fabric2;
  }
  if (typeof document !== "undefined" && typeof window !== "undefined") {
    if (document instanceof (typeof HTMLDocument !== "undefined" ? HTMLDocument : Document)) {
      fabric2.document = document;
    } else {
      fabric2.document = document.implementation.createHTMLDocument("");
    }
    fabric2.window = window;
  } else {
    var jsdom = require$$2;
    var virtualWindow = new jsdom.JSDOM(decodeURIComponent("%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E"), {
      features: {
        FetchExternalResources: ["img"]
      },
      resources: "usable"
    }).window;
    fabric2.document = virtualWindow.document;
    fabric2.jsdomImplForWrapper = require$$2.implForWrapper;
    fabric2.nodeCanvas = require$$2.Canvas;
    fabric2.window = virtualWindow;
    DOMParser = fabric2.window.DOMParser;
  }
  fabric2.isTouchSupported = "ontouchstart" in fabric2.window || "ontouchstart" in fabric2.document || fabric2.window && fabric2.window.navigator && fabric2.window.navigator.maxTouchPoints > 0;
  fabric2.isLikelyNode = typeof Buffer !== "undefined" && typeof window === "undefined";
  fabric2.SHARED_ATTRIBUTES = [
    "display",
    "transform",
    "fill",
    "fill-opacity",
    "fill-rule",
    "opacity",
    "stroke",
    "stroke-dasharray",
    "stroke-linecap",
    "stroke-dashoffset",
    "stroke-linejoin",
    "stroke-miterlimit",
    "stroke-opacity",
    "stroke-width",
    "id",
    "paint-order",
    "vector-effect",
    "instantiated_by_use",
    "clip-path"
  ];
  fabric2.DPI = 96;
  fabric2.reNum = "(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)";
  fabric2.commaWsp = "(?:\\s+,?\\s*|,\\s*)";
  fabric2.rePathCommand = /([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/ig;
  fabric2.reNonWord = /[ \n\.,;!\?\-]/;
  fabric2.fontPaths = {};
  fabric2.iMatrix = [1, 0, 0, 1, 0, 0];
  fabric2.svgNS = "http://www.w3.org/2000/svg";
  fabric2.perfLimitSizeTotal = 2097152;
  fabric2.maxCacheSideLimit = 4096;
  fabric2.minCacheSideLimit = 256;
  fabric2.charWidthsCache = {};
  fabric2.textureSize = 2048;
  fabric2.disableStyleCopyPaste = false;
  fabric2.enableGLFiltering = true;
  fabric2.devicePixelRatio = fabric2.window.devicePixelRatio || fabric2.window.webkitDevicePixelRatio || fabric2.window.mozDevicePixelRatio || 1;
  fabric2.browserShadowBlurConstant = 1;
  fabric2.arcToSegmentsCache = {};
  fabric2.boundsOfCurveCache = {};
  fabric2.cachesBoundsOfCurve = true;
  fabric2.forceGLPutImageData = false;
  fabric2.initFilterBackend = function() {
    if (fabric2.enableGLFiltering && fabric2.isWebglSupported && fabric2.isWebglSupported(fabric2.textureSize)) {
      console.log("max texture size: " + fabric2.maxTextureSize);
      return new fabric2.WebglFilterBackend({ tileSize: fabric2.textureSize });
    } else if (fabric2.Canvas2dFilterBackend) {
      return new fabric2.Canvas2dFilterBackend();
    }
  };
  if (typeof document !== "undefined" && typeof window !== "undefined") {
    window.fabric = fabric2;
  }
  (function() {
    function _removeEventListener(eventName, handler) {
      if (!this.__eventListeners[eventName]) {
        return;
      }
      var eventListener = this.__eventListeners[eventName];
      if (handler) {
        eventListener[eventListener.indexOf(handler)] = false;
      } else {
        fabric2.util.array.fill(eventListener, false);
      }
    }
    function on2(eventName, handler) {
      if (!this.__eventListeners) {
        this.__eventListeners = {};
      }
      if (arguments.length === 1) {
        for (var prop in eventName) {
          this.on(prop, eventName[prop]);
        }
      } else {
        if (!this.__eventListeners[eventName]) {
          this.__eventListeners[eventName] = [];
        }
        this.__eventListeners[eventName].push(handler);
      }
      return this;
    }
    function _once(eventName, handler) {
      var _handler2 = function() {
        handler.apply(this, arguments);
        this.off(eventName, _handler2);
      }.bind(this);
      this.on(eventName, _handler2);
    }
    function once(eventName, handler) {
      if (arguments.length === 1) {
        for (var prop in eventName) {
          _once.call(this, prop, eventName[prop]);
        }
      } else {
        _once.call(this, eventName, handler);
      }
      return this;
    }
    function off(eventName, handler) {
      if (!this.__eventListeners) {
        return this;
      }
      if (arguments.length === 0) {
        for (eventName in this.__eventListeners) {
          _removeEventListener.call(this, eventName);
        }
      } else if (arguments.length === 1 && typeof arguments[0] === "object") {
        for (var prop in eventName) {
          _removeEventListener.call(this, prop, eventName[prop]);
        }
      } else {
        _removeEventListener.call(this, eventName, handler);
      }
      return this;
    }
    function fire(eventName, options) {
      if (!this.__eventListeners) {
        return this;
      }
      var listenersForEvent = this.__eventListeners[eventName];
      if (!listenersForEvent) {
        return this;
      }
      for (var i2 = 0, len = listenersForEvent.length; i2 < len; i2++) {
        listenersForEvent[i2] && listenersForEvent[i2].call(this, options || {});
      }
      this.__eventListeners[eventName] = listenersForEvent.filter(function(value) {
        return value !== false;
      });
      return this;
    }
    fabric2.Observable = {
      fire,
      on: on2,
      once,
      off
    };
  })();
  fabric2.Collection = {
    _objects: [],
    add: function() {
      this._objects.push.apply(this._objects, arguments);
      if (this._onObjectAdded) {
        for (var i2 = 0, length = arguments.length; i2 < length; i2++) {
          this._onObjectAdded(arguments[i2]);
        }
      }
      this.renderOnAddRemove && this.requestRenderAll();
      return this;
    },
    insertAt: function(object, index2, nonSplicing) {
      var objects = this._objects;
      if (nonSplicing) {
        objects[index2] = object;
      } else {
        objects.splice(index2, 0, object);
      }
      this._onObjectAdded && this._onObjectAdded(object);
      this.renderOnAddRemove && this.requestRenderAll();
      return this;
    },
    remove: function() {
      var objects = this._objects, index2, somethingRemoved = false;
      for (var i2 = 0, length = arguments.length; i2 < length; i2++) {
        index2 = objects.indexOf(arguments[i2]);
        if (index2 !== -1) {
          somethingRemoved = true;
          objects.splice(index2, 1);
          this._onObjectRemoved && this._onObjectRemoved(arguments[i2]);
        }
      }
      this.renderOnAddRemove && somethingRemoved && this.requestRenderAll();
      return this;
    },
    forEachObject: function(callback, context) {
      var objects = this.getObjects();
      for (var i2 = 0, len = objects.length; i2 < len; i2++) {
        callback.call(context, objects[i2], i2, objects);
      }
      return this;
    },
    getObjects: function(type) {
      if (typeof type === "undefined") {
        return this._objects.concat();
      }
      return this._objects.filter(function(o2) {
        return o2.type === type;
      });
    },
    item: function(index2) {
      return this._objects[index2];
    },
    isEmpty: function() {
      return this._objects.length === 0;
    },
    size: function() {
      return this._objects.length;
    },
    contains: function(object, deep) {
      if (this._objects.indexOf(object) > -1) {
        return true;
      } else if (deep) {
        return this._objects.some(function(obj) {
          return typeof obj.contains === "function" && obj.contains(object, true);
        });
      }
      return false;
    },
    complexity: function() {
      return this._objects.reduce(function(memo, current) {
        memo += current.complexity ? current.complexity() : 0;
        return memo;
      }, 0);
    }
  };
  fabric2.CommonMethods = {
    _setOptions: function(options) {
      for (var prop in options) {
        this.set(prop, options[prop]);
      }
    },
    _initGradient: function(filler, property) {
      if (filler && filler.colorStops && !(filler instanceof fabric2.Gradient)) {
        this.set(property, new fabric2.Gradient(filler));
      }
    },
    _initPattern: function(filler, property, callback) {
      if (filler && filler.source && !(filler instanceof fabric2.Pattern)) {
        this.set(property, new fabric2.Pattern(filler, callback));
      } else {
        callback && callback();
      }
    },
    _setObject: function(obj) {
      for (var prop in obj) {
        this._set(prop, obj[prop]);
      }
    },
    set: function(key, value) {
      if (typeof key === "object") {
        this._setObject(key);
      } else {
        this._set(key, value);
      }
      return this;
    },
    _set: function(key, value) {
      this[key] = value;
    },
    toggle: function(property) {
      var value = this.get(property);
      if (typeof value === "boolean") {
        this.set(property, !value);
      }
      return this;
    },
    get: function(property) {
      return this[property];
    }
  };
  (function(global2) {
    var sqrt = Math.sqrt, atan2 = Math.atan2, pow = Math.pow, PiBy180 = Math.PI / 180, PiBy2 = Math.PI / 2;
    fabric2.util = {
      cos: function(angle) {
        if (angle === 0) {
          return 1;
        }
        if (angle < 0) {
          angle = -angle;
        }
        var angleSlice = angle / PiBy2;
        switch (angleSlice) {
          case 1:
          case 3:
            return 0;
          case 2:
            return -1;
        }
        return Math.cos(angle);
      },
      sin: function(angle) {
        if (angle === 0) {
          return 0;
        }
        var angleSlice = angle / PiBy2, sign = 1;
        if (angle < 0) {
          sign = -1;
        }
        switch (angleSlice) {
          case 1:
            return sign;
          case 2:
            return 0;
          case 3:
            return -sign;
        }
        return Math.sin(angle);
      },
      removeFromArray: function(array, value) {
        var idx = array.indexOf(value);
        if (idx !== -1) {
          array.splice(idx, 1);
        }
        return array;
      },
      getRandomInt: function(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
      },
      degreesToRadians: function(degrees2) {
        return degrees2 * PiBy180;
      },
      radiansToDegrees: function(radians) {
        return radians / PiBy180;
      },
      rotatePoint: function(point, origin, radians) {
        var newPoint = new fabric2.Point(point.x - origin.x, point.y - origin.y), v2 = fabric2.util.rotateVector(newPoint, radians);
        return new fabric2.Point(v2.x, v2.y).addEquals(origin);
      },
      rotateVector: function(vector, radians) {
        var sin = fabric2.util.sin(radians), cos = fabric2.util.cos(radians), rx = vector.x * cos - vector.y * sin, ry = vector.x * sin + vector.y * cos;
        return {
          x: rx,
          y: ry
        };
      },
      transformPoint: function(p2, t2, ignoreOffset) {
        if (ignoreOffset) {
          return new fabric2.Point(t2[0] * p2.x + t2[2] * p2.y, t2[1] * p2.x + t2[3] * p2.y);
        }
        return new fabric2.Point(t2[0] * p2.x + t2[2] * p2.y + t2[4], t2[1] * p2.x + t2[3] * p2.y + t2[5]);
      },
      makeBoundingBoxFromPoints: function(points, transform2) {
        if (transform2) {
          for (var i2 = 0; i2 < points.length; i2++) {
            points[i2] = fabric2.util.transformPoint(points[i2], transform2);
          }
        }
        var xPoints = [points[0].x, points[1].x, points[2].x, points[3].x], minX = fabric2.util.array.min(xPoints), maxX = fabric2.util.array.max(xPoints), width = maxX - minX, yPoints = [points[0].y, points[1].y, points[2].y, points[3].y], minY = fabric2.util.array.min(yPoints), maxY = fabric2.util.array.max(yPoints), height = maxY - minY;
        return {
          left: minX,
          top: minY,
          width,
          height
        };
      },
      invertTransform: function(t2) {
        var a2 = 1 / (t2[0] * t2[3] - t2[1] * t2[2]), r2 = [a2 * t2[3], -a2 * t2[1], -a2 * t2[2], a2 * t2[0]], o2 = fabric2.util.transformPoint({ x: t2[4], y: t2[5] }, r2, true);
        r2[4] = -o2.x;
        r2[5] = -o2.y;
        return r2;
      },
      toFixed: function(number2, fractionDigits) {
        return parseFloat(Number(number2).toFixed(fractionDigits));
      },
      parseUnit: function(value, fontSize) {
        var unit = /\D{0,2}$/.exec(value), number2 = parseFloat(value);
        if (!fontSize) {
          fontSize = fabric2.Text.DEFAULT_SVG_FONT_SIZE;
        }
        switch (unit[0]) {
          case "mm":
            return number2 * fabric2.DPI / 25.4;
          case "cm":
            return number2 * fabric2.DPI / 2.54;
          case "in":
            return number2 * fabric2.DPI;
          case "pt":
            return number2 * fabric2.DPI / 72;
          case "pc":
            return number2 * fabric2.DPI / 72 * 12;
          case "em":
            return number2 * fontSize;
          default:
            return number2;
        }
      },
      falseFunction: function() {
        return false;
      },
      getKlass: function(type, namespace) {
        type = fabric2.util.string.camelize(type.charAt(0).toUpperCase() + type.slice(1));
        return fabric2.util.resolveNamespace(namespace)[type];
      },
      getSvgAttributes: function(type) {
        var attributes = [
          "instantiated_by_use",
          "style",
          "id",
          "class"
        ];
        switch (type) {
          case "linearGradient":
            attributes = attributes.concat(["x1", "y1", "x2", "y2", "gradientUnits", "gradientTransform"]);
            break;
          case "radialGradient":
            attributes = attributes.concat(["gradientUnits", "gradientTransform", "cx", "cy", "r", "fx", "fy", "fr"]);
            break;
          case "stop":
            attributes = attributes.concat(["offset", "stop-color", "stop-opacity"]);
            break;
        }
        return attributes;
      },
      resolveNamespace: function(namespace) {
        if (!namespace) {
          return fabric2;
        }
        var parts = namespace.split("."), len = parts.length, i2, obj = global2 || fabric2.window;
        for (i2 = 0; i2 < len; ++i2) {
          obj = obj[parts[i2]];
        }
        return obj;
      },
      loadImage: function(url, callback, context, crossOrigin) {
        if (!url) {
          callback && callback.call(context, url);
          return;
        }
        var img = fabric2.util.createImage();
        var onLoadCallback = function() {
          callback && callback.call(context, img, false);
          img = img.onload = img.onerror = null;
        };
        img.onload = onLoadCallback;
        img.onerror = function() {
          fabric2.log("Error loading " + img.src);
          callback && callback.call(context, null, true);
          img = img.onload = img.onerror = null;
        };
        if (url.indexOf("data") !== 0 && crossOrigin !== void 0 && crossOrigin !== null) {
          img.crossOrigin = crossOrigin;
        }
        if (url.substring(0, 14) === "data:image/svg") {
          img.onload = null;
          fabric2.util.loadImageInDom(img, onLoadCallback);
        }
        img.src = url;
      },
      loadImageInDom: function(img, onLoadCallback) {
        var div = fabric2.document.createElement("div");
        div.style.width = div.style.height = "1px";
        div.style.left = div.style.top = "-100%";
        div.style.position = "absolute";
        div.appendChild(img);
        fabric2.document.querySelector("body").appendChild(div);
        img.onload = function() {
          onLoadCallback();
          div.parentNode.removeChild(div);
          div = null;
        };
      },
      enlivenObjects: function(objects, callback, namespace, reviver) {
        objects = objects || [];
        var enlivenedObjects = [], numLoadedObjects = 0, numTotalObjects = objects.length;
        function onLoaded() {
          if (++numLoadedObjects === numTotalObjects) {
            callback && callback(enlivenedObjects.filter(function(obj) {
              return obj;
            }));
          }
        }
        if (!numTotalObjects) {
          callback && callback(enlivenedObjects);
          return;
        }
        objects.forEach(function(o2, index2) {
          if (!o2 || !o2.type) {
            onLoaded();
            return;
          }
          var klass = fabric2.util.getKlass(o2.type, namespace);
          klass.fromObject(o2, function(obj, error) {
            error || (enlivenedObjects[index2] = obj);
            reviver && reviver(o2, obj, error);
            onLoaded();
          });
        });
      },
      enlivenPatterns: function(patterns, callback) {
        patterns = patterns || [];
        function onLoaded() {
          if (++numLoadedPatterns === numPatterns) {
            callback && callback(enlivenedPatterns);
          }
        }
        var enlivenedPatterns = [], numLoadedPatterns = 0, numPatterns = patterns.length;
        if (!numPatterns) {
          callback && callback(enlivenedPatterns);
          return;
        }
        patterns.forEach(function(p2, index2) {
          if (p2 && p2.source) {
            new fabric2.Pattern(p2, function(pattern) {
              enlivenedPatterns[index2] = pattern;
              onLoaded();
            });
          } else {
            enlivenedPatterns[index2] = p2;
            onLoaded();
          }
        });
      },
      groupSVGElements: function(elements, options, path) {
        var object;
        if (elements && elements.length === 1) {
          return elements[0];
        }
        if (options) {
          if (options.width && options.height) {
            options.centerPoint = {
              x: options.width / 2,
              y: options.height / 2
            };
          } else {
            delete options.width;
            delete options.height;
          }
        }
        object = new fabric2.Group(elements, options);
        if (typeof path !== "undefined") {
          object.sourcePath = path;
        }
        return object;
      },
      populateWithProperties: function(source, destination, properties2) {
        if (properties2 && Object.prototype.toString.call(properties2) === "[object Array]") {
          for (var i2 = 0, len = properties2.length; i2 < len; i2++) {
            if (properties2[i2] in source) {
              destination[properties2[i2]] = source[properties2[i2]];
            }
          }
        }
      },
      drawDashedLine: function(ctx, x2, y2, x22, y22, da) {
        var dx = x22 - x2, dy = y22 - y2, len = sqrt(dx * dx + dy * dy), rot = atan2(dy, dx), dc = da.length, di = 0, draw = true;
        ctx.save();
        ctx.translate(x2, y2);
        ctx.moveTo(0, 0);
        ctx.rotate(rot);
        x2 = 0;
        while (len > x2) {
          x2 += da[di++ % dc];
          if (x2 > len) {
            x2 = len;
          }
          ctx[draw ? "lineTo" : "moveTo"](x2, 0);
          draw = !draw;
        }
        ctx.restore();
      },
      createCanvasElement: function() {
        return fabric2.document.createElement("canvas");
      },
      copyCanvasElement: function(canvas) {
        var newCanvas = fabric2.util.createCanvasElement();
        newCanvas.width = canvas.width;
        newCanvas.height = canvas.height;
        newCanvas.getContext("2d").drawImage(canvas, 0, 0);
        return newCanvas;
      },
      toDataURL: function(canvasEl, format, quality) {
        return canvasEl.toDataURL("image/" + format, quality);
      },
      createImage: function() {
        return fabric2.document.createElement("img");
      },
      multiplyTransformMatrices: function(a2, b2, is2x2) {
        return [
          a2[0] * b2[0] + a2[2] * b2[1],
          a2[1] * b2[0] + a2[3] * b2[1],
          a2[0] * b2[2] + a2[2] * b2[3],
          a2[1] * b2[2] + a2[3] * b2[3],
          is2x2 ? 0 : a2[0] * b2[4] + a2[2] * b2[5] + a2[4],
          is2x2 ? 0 : a2[1] * b2[4] + a2[3] * b2[5] + a2[5]
        ];
      },
      qrDecompose: function(a2) {
        var angle = atan2(a2[1], a2[0]), denom = pow(a2[0], 2) + pow(a2[1], 2), scaleX = sqrt(denom), scaleY = (a2[0] * a2[3] - a2[2] * a2[1]) / scaleX, skewX = atan2(a2[0] * a2[2] + a2[1] * a2[3], denom);
        return {
          angle: angle / PiBy180,
          scaleX,
          scaleY,
          skewX: skewX / PiBy180,
          skewY: 0,
          translateX: a2[4],
          translateY: a2[5]
        };
      },
      calcRotateMatrix: function(options) {
        if (!options.angle) {
          return fabric2.iMatrix.concat();
        }
        var theta = fabric2.util.degreesToRadians(options.angle), cos = fabric2.util.cos(theta), sin = fabric2.util.sin(theta);
        return [cos, sin, -sin, cos, 0, 0];
      },
      calcDimensionsMatrix: function(options) {
        var scaleX = typeof options.scaleX === "undefined" ? 1 : options.scaleX, scaleY = typeof options.scaleY === "undefined" ? 1 : options.scaleY, scaleMatrix = [
          options.flipX ? -scaleX : scaleX,
          0,
          0,
          options.flipY ? -scaleY : scaleY,
          0,
          0
        ], multiply = fabric2.util.multiplyTransformMatrices, degreesToRadians = fabric2.util.degreesToRadians;
        if (options.skewX) {
          scaleMatrix = multiply(scaleMatrix, [1, 0, Math.tan(degreesToRadians(options.skewX)), 1], true);
        }
        if (options.skewY) {
          scaleMatrix = multiply(scaleMatrix, [1, Math.tan(degreesToRadians(options.skewY)), 0, 1], true);
        }
        return scaleMatrix;
      },
      composeMatrix: function(options) {
        var matrix = [1, 0, 0, 1, options.translateX || 0, options.translateY || 0], multiply = fabric2.util.multiplyTransformMatrices;
        if (options.angle) {
          matrix = multiply(matrix, fabric2.util.calcRotateMatrix(options));
        }
        if (options.scaleX !== 1 || options.scaleY !== 1 || options.skewX || options.skewY || options.flipX || options.flipY) {
          matrix = multiply(matrix, fabric2.util.calcDimensionsMatrix(options));
        }
        return matrix;
      },
      resetObjectTransform: function(target) {
        target.scaleX = 1;
        target.scaleY = 1;
        target.skewX = 0;
        target.skewY = 0;
        target.flipX = false;
        target.flipY = false;
        target.rotate(0);
      },
      saveObjectTransform: function(target) {
        return {
          scaleX: target.scaleX,
          scaleY: target.scaleY,
          skewX: target.skewX,
          skewY: target.skewY,
          angle: target.angle,
          left: target.left,
          flipX: target.flipX,
          flipY: target.flipY,
          top: target.top
        };
      },
      isTransparent: function(ctx, x2, y2, tolerance) {
        if (tolerance > 0) {
          if (x2 > tolerance) {
            x2 -= tolerance;
          } else {
            x2 = 0;
          }
          if (y2 > tolerance) {
            y2 -= tolerance;
          } else {
            y2 = 0;
          }
        }
        var _isTransparent = true, i2, temp, imageData = ctx.getImageData(x2, y2, tolerance * 2 || 1, tolerance * 2 || 1), l2 = imageData.data.length;
        for (i2 = 3; i2 < l2; i2 += 4) {
          temp = imageData.data[i2];
          _isTransparent = temp <= 0;
          if (_isTransparent === false) {
            break;
          }
        }
        imageData = null;
        return _isTransparent;
      },
      parsePreserveAspectRatioAttribute: function(attribute) {
        var meetOrSlice = "meet", alignX = "Mid", alignY = "Mid", aspectRatioAttrs = attribute.split(" "), align;
        if (aspectRatioAttrs && aspectRatioAttrs.length) {
          meetOrSlice = aspectRatioAttrs.pop();
          if (meetOrSlice !== "meet" && meetOrSlice !== "slice") {
            align = meetOrSlice;
            meetOrSlice = "meet";
          } else if (aspectRatioAttrs.length) {
            align = aspectRatioAttrs.pop();
          }
        }
        alignX = align !== "none" ? align.slice(1, 4) : "none";
        alignY = align !== "none" ? align.slice(5, 8) : "none";
        return {
          meetOrSlice,
          alignX,
          alignY
        };
      },
      clearFabricFontCache: function(fontFamily) {
        fontFamily = (fontFamily || "").toLowerCase();
        if (!fontFamily) {
          fabric2.charWidthsCache = {};
        } else if (fabric2.charWidthsCache[fontFamily]) {
          delete fabric2.charWidthsCache[fontFamily];
        }
      },
      limitDimsByArea: function(ar, maximumArea) {
        var roughWidth = Math.sqrt(maximumArea * ar), perfLimitSizeY = Math.floor(maximumArea / roughWidth);
        return { x: Math.floor(roughWidth), y: perfLimitSizeY };
      },
      capValue: function(min, value, max) {
        return Math.max(min, Math.min(value, max));
      },
      findScaleToFit: function(source, destination) {
        return Math.min(destination.width / source.width, destination.height / source.height);
      },
      findScaleToCover: function(source, destination) {
        return Math.max(destination.width / source.width, destination.height / source.height);
      },
      matrixToSVG: function(transform2) {
        return "matrix(" + transform2.map(function(value) {
          return fabric2.util.toFixed(value, fabric2.Object.NUM_FRACTION_DIGITS);
        }).join(" ") + ")";
      },
      removeTransformFromObject: function(object, transform2) {
        var inverted = fabric2.util.invertTransform(transform2), finalTransform = fabric2.util.multiplyTransformMatrices(inverted, object.calcOwnMatrix());
        fabric2.util.applyTransformToObject(object, finalTransform);
      },
      addTransformToObject: function(object, transform2) {
        fabric2.util.applyTransformToObject(object, fabric2.util.multiplyTransformMatrices(transform2, object.calcOwnMatrix()));
      },
      applyTransformToObject: function(object, transform2) {
        var options = fabric2.util.qrDecompose(transform2), center = new fabric2.Point(options.translateX, options.translateY);
        object.flipX = false;
        object.flipY = false;
        object.set("scaleX", options.scaleX);
        object.set("scaleY", options.scaleY);
        object.skewX = options.skewX;
        object.skewY = options.skewY;
        object.angle = options.angle;
        object.setPositionByOrigin(center, "center", "center");
      },
      sizeAfterTransform: function(width, height, options) {
        var dimX = width / 2, dimY = height / 2, points = [
          {
            x: -dimX,
            y: -dimY
          },
          {
            x: dimX,
            y: -dimY
          },
          {
            x: -dimX,
            y: dimY
          },
          {
            x: dimX,
            y: dimY
          }
        ], transformMatrix = fabric2.util.calcDimensionsMatrix(options), bbox = fabric2.util.makeBoundingBoxFromPoints(points, transformMatrix);
        return {
          x: bbox.width,
          y: bbox.height
        };
      }
    };
  })(exports2);
  (function() {
    var _join = Array.prototype.join, commandLengths = {
      m: 2,
      l: 2,
      h: 1,
      v: 1,
      c: 6,
      s: 4,
      q: 4,
      t: 2,
      a: 7
    }, repeatedCommands = {
      m: "l",
      M: "L"
    };
    function segmentToBezier(th2, th3, cosTh, sinTh, rx, ry, cx1, cy1, mT, fromX, fromY) {
      var costh2 = fabric2.util.cos(th2), sinth2 = fabric2.util.sin(th2), costh3 = fabric2.util.cos(th3), sinth3 = fabric2.util.sin(th3), toX = cosTh * rx * costh3 - sinTh * ry * sinth3 + cx1, toY = sinTh * rx * costh3 + cosTh * ry * sinth3 + cy1, cp1X = fromX + mT * (-cosTh * rx * sinth2 - sinTh * ry * costh2), cp1Y = fromY + mT * (-sinTh * rx * sinth2 + cosTh * ry * costh2), cp2X = toX + mT * (cosTh * rx * sinth3 + sinTh * ry * costh3), cp2Y = toY + mT * (sinTh * rx * sinth3 - cosTh * ry * costh3);
      return [
        "C",
        cp1X,
        cp1Y,
        cp2X,
        cp2Y,
        toX,
        toY
      ];
    }
    function arcToSegments(toX, toY, rx, ry, large, sweep, rotateX) {
      var PI = Math.PI, th = rotateX * PI / 180, sinTh = fabric2.util.sin(th), cosTh = fabric2.util.cos(th), fromX = 0, fromY = 0;
      rx = Math.abs(rx);
      ry = Math.abs(ry);
      var px2 = -cosTh * toX * 0.5 - sinTh * toY * 0.5, py = -cosTh * toY * 0.5 + sinTh * toX * 0.5, rx2 = rx * rx, ry2 = ry * ry, py2 = py * py, px22 = px2 * px2, pl = rx2 * ry2 - rx2 * py2 - ry2 * px22, root = 0;
      if (pl < 0) {
        var s2 = Math.sqrt(1 - pl / (rx2 * ry2));
        rx *= s2;
        ry *= s2;
      } else {
        root = (large === sweep ? -1 : 1) * Math.sqrt(pl / (rx2 * py2 + ry2 * px22));
      }
      var cx = root * rx * py / ry, cy = -root * ry * px2 / rx, cx1 = cosTh * cx - sinTh * cy + toX * 0.5, cy1 = sinTh * cx + cosTh * cy + toY * 0.5, mTheta = calcVectorAngle(1, 0, (px2 - cx) / rx, (py - cy) / ry), dtheta = calcVectorAngle((px2 - cx) / rx, (py - cy) / ry, (-px2 - cx) / rx, (-py - cy) / ry);
      if (sweep === 0 && dtheta > 0) {
        dtheta -= 2 * PI;
      } else if (sweep === 1 && dtheta < 0) {
        dtheta += 2 * PI;
      }
      var segments = Math.ceil(Math.abs(dtheta / PI * 2)), result = [], mDelta = dtheta / segments, mT = 8 / 3 * Math.sin(mDelta / 4) * Math.sin(mDelta / 4) / Math.sin(mDelta / 2), th3 = mTheta + mDelta;
      for (var i2 = 0; i2 < segments; i2++) {
        result[i2] = segmentToBezier(mTheta, th3, cosTh, sinTh, rx, ry, cx1, cy1, mT, fromX, fromY);
        fromX = result[i2][5];
        fromY = result[i2][6];
        mTheta = th3;
        th3 += mDelta;
      }
      return result;
    }
    function calcVectorAngle(ux, uy, vx, vy) {
      var ta = Math.atan2(uy, ux), tb = Math.atan2(vy, vx);
      if (tb >= ta) {
        return tb - ta;
      } else {
        return 2 * Math.PI - (ta - tb);
      }
    }
    function getBoundsOfCurve(x0, y0, x1, y1, x2, y2, x3, y3) {
      var argsString;
      if (fabric2.cachesBoundsOfCurve) {
        argsString = _join.call(arguments);
        if (fabric2.boundsOfCurveCache[argsString]) {
          return fabric2.boundsOfCurveCache[argsString];
        }
      }
      var sqrt = Math.sqrt, min = Math.min, max = Math.max, abs = Math.abs, tvalues = [], bounds = [[], []], a2, b2, c2, t2, t1, t22, b2ac, sqrtb2ac;
      b2 = 6 * x0 - 12 * x1 + 6 * x2;
      a2 = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3;
      c2 = 3 * x1 - 3 * x0;
      for (var i2 = 0; i2 < 2; ++i2) {
        if (i2 > 0) {
          b2 = 6 * y0 - 12 * y1 + 6 * y2;
          a2 = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3;
          c2 = 3 * y1 - 3 * y0;
        }
        if (abs(a2) < 1e-12) {
          if (abs(b2) < 1e-12) {
            continue;
          }
          t2 = -c2 / b2;
          if (0 < t2 && t2 < 1) {
            tvalues.push(t2);
          }
          continue;
        }
        b2ac = b2 * b2 - 4 * c2 * a2;
        if (b2ac < 0) {
          continue;
        }
        sqrtb2ac = sqrt(b2ac);
        t1 = (-b2 + sqrtb2ac) / (2 * a2);
        if (0 < t1 && t1 < 1) {
          tvalues.push(t1);
        }
        t22 = (-b2 - sqrtb2ac) / (2 * a2);
        if (0 < t22 && t22 < 1) {
          tvalues.push(t22);
        }
      }
      var x4, y4, j2 = tvalues.length, jlen = j2, mt;
      while (j2--) {
        t2 = tvalues[j2];
        mt = 1 - t2;
        x4 = mt * mt * mt * x0 + 3 * mt * mt * t2 * x1 + 3 * mt * t2 * t2 * x2 + t2 * t2 * t2 * x3;
        bounds[0][j2] = x4;
        y4 = mt * mt * mt * y0 + 3 * mt * mt * t2 * y1 + 3 * mt * t2 * t2 * y2 + t2 * t2 * t2 * y3;
        bounds[1][j2] = y4;
      }
      bounds[0][jlen] = x0;
      bounds[1][jlen] = y0;
      bounds[0][jlen + 1] = x3;
      bounds[1][jlen + 1] = y3;
      var result = [
        {
          x: min.apply(null, bounds[0]),
          y: min.apply(null, bounds[1])
        },
        {
          x: max.apply(null, bounds[0]),
          y: max.apply(null, bounds[1])
        }
      ];
      if (fabric2.cachesBoundsOfCurve) {
        fabric2.boundsOfCurveCache[argsString] = result;
      }
      return result;
    }
    function fromArcToBeziers(fx, fy, coords) {
      var rx = coords[1], ry = coords[2], rot = coords[3], large = coords[4], sweep = coords[5], tx = coords[6], ty = coords[7], segsNorm = arcToSegments(tx - fx, ty - fy, rx, ry, large, sweep, rot);
      for (var i2 = 0, len = segsNorm.length; i2 < len; i2++) {
        segsNorm[i2][1] += fx;
        segsNorm[i2][2] += fy;
        segsNorm[i2][3] += fx;
        segsNorm[i2][4] += fy;
        segsNorm[i2][5] += fx;
        segsNorm[i2][6] += fy;
      }
      return segsNorm;
    }
    function makePathSimpler(path) {
      var x2 = 0, y2 = 0, len = path.length, x1 = 0, y1 = 0, current, i2, converted, destinationPath = [], previous, controlX, controlY;
      for (i2 = 0; i2 < len; ++i2) {
        converted = false;
        current = path[i2].slice(0);
        switch (current[0]) {
          case "l":
            current[0] = "L";
            current[1] += x2;
            current[2] += y2;
          case "L":
            x2 = current[1];
            y2 = current[2];
            break;
          case "h":
            current[1] += x2;
          case "H":
            current[0] = "L";
            current[2] = y2;
            x2 = current[1];
            break;
          case "v":
            current[1] += y2;
          case "V":
            current[0] = "L";
            y2 = current[1];
            current[1] = x2;
            current[2] = y2;
            break;
          case "m":
            current[0] = "M";
            current[1] += x2;
            current[2] += y2;
          case "M":
            x2 = current[1];
            y2 = current[2];
            x1 = current[1];
            y1 = current[2];
            break;
          case "c":
            current[0] = "C";
            current[1] += x2;
            current[2] += y2;
            current[3] += x2;
            current[4] += y2;
            current[5] += x2;
            current[6] += y2;
          case "C":
            controlX = current[3];
            controlY = current[4];
            x2 = current[5];
            y2 = current[6];
            break;
          case "s":
            current[0] = "S";
            current[1] += x2;
            current[2] += y2;
            current[3] += x2;
            current[4] += y2;
          case "S":
            if (previous === "C") {
              controlX = 2 * x2 - controlX;
              controlY = 2 * y2 - controlY;
            } else {
              controlX = x2;
              controlY = y2;
            }
            x2 = current[3];
            y2 = current[4];
            current[0] = "C";
            current[5] = current[3];
            current[6] = current[4];
            current[3] = current[1];
            current[4] = current[2];
            current[1] = controlX;
            current[2] = controlY;
            controlX = current[3];
            controlY = current[4];
            break;
          case "q":
            current[0] = "Q";
            current[1] += x2;
            current[2] += y2;
            current[3] += x2;
            current[4] += y2;
          case "Q":
            controlX = current[1];
            controlY = current[2];
            x2 = current[3];
            y2 = current[4];
            break;
          case "t":
            current[0] = "T";
            current[1] += x2;
            current[2] += y2;
          case "T":
            if (previous === "Q") {
              controlX = 2 * x2 - controlX;
              controlY = 2 * y2 - controlY;
            } else {
              controlX = x2;
              controlY = y2;
            }
            current[0] = "Q";
            x2 = current[1];
            y2 = current[2];
            current[1] = controlX;
            current[2] = controlY;
            current[3] = x2;
            current[4] = y2;
            break;
          case "a":
            current[0] = "A";
            current[6] += x2;
            current[7] += y2;
          case "A":
            converted = true;
            destinationPath = destinationPath.concat(fromArcToBeziers(x2, y2, current));
            x2 = current[6];
            y2 = current[7];
            break;
          case "z":
          case "Z":
            x2 = x1;
            y2 = y1;
            break;
        }
        if (!converted) {
          destinationPath.push(current);
        }
        previous = current[0];
      }
      return destinationPath;
    }
    function calcLineLength(x1, y1, x2, y2) {
      return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
    }
    function CB1(t2) {
      return t2 * t2 * t2;
    }
    function CB2(t2) {
      return 3 * t2 * t2 * (1 - t2);
    }
    function CB3(t2) {
      return 3 * t2 * (1 - t2) * (1 - t2);
    }
    function CB4(t2) {
      return (1 - t2) * (1 - t2) * (1 - t2);
    }
    function getPointOnCubicBezierIterator(p1x, p1y, p2x, p2y, p3x, p3y, p4x, p4y) {
      return function(pct) {
        var c1 = CB1(pct), c2 = CB2(pct), c3 = CB3(pct), c4 = CB4(pct);
        return {
          x: p4x * c1 + p3x * c2 + p2x * c3 + p1x * c4,
          y: p4y * c1 + p3y * c2 + p2y * c3 + p1y * c4
        };
      };
    }
    function getTangentCubicIterator(p1x, p1y, p2x, p2y, p3x, p3y, p4x, p4y) {
      return function(pct) {
        var invT = 1 - pct, tangentX = 3 * invT * invT * (p2x - p1x) + 6 * invT * pct * (p3x - p2x) + 3 * pct * pct * (p4x - p3x), tangentY = 3 * invT * invT * (p2y - p1y) + 6 * invT * pct * (p3y - p2y) + 3 * pct * pct * (p4y - p3y);
        return Math.atan2(tangentY, tangentX);
      };
    }
    function QB1(t2) {
      return t2 * t2;
    }
    function QB2(t2) {
      return 2 * t2 * (1 - t2);
    }
    function QB3(t2) {
      return (1 - t2) * (1 - t2);
    }
    function getPointOnQuadraticBezierIterator(p1x, p1y, p2x, p2y, p3x, p3y) {
      return function(pct) {
        var c1 = QB1(pct), c2 = QB2(pct), c3 = QB3(pct);
        return {
          x: p3x * c1 + p2x * c2 + p1x * c3,
          y: p3y * c1 + p2y * c2 + p1y * c3
        };
      };
    }
    function getTangentQuadraticIterator(p1x, p1y, p2x, p2y, p3x, p3y) {
      return function(pct) {
        var invT = 1 - pct, tangentX = 2 * invT * (p2x - p1x) + 2 * pct * (p3x - p2x), tangentY = 2 * invT * (p2y - p1y) + 2 * pct * (p3y - p2y);
        return Math.atan2(tangentY, tangentX);
      };
    }
    function pathIterator(iterator, x1, y1) {
      var tempP = { x: x1, y: y1 }, p2, tmpLen = 0, perc;
      for (perc = 1; perc <= 100; perc += 1) {
        p2 = iterator(perc / 100);
        tmpLen += calcLineLength(tempP.x, tempP.y, p2.x, p2.y);
        tempP = p2;
      }
      return tmpLen;
    }
    function findPercentageForDistance(segInfo, distance) {
      var perc = 0, tmpLen = 0, iterator = segInfo.iterator, tempP = { x: segInfo.x, y: segInfo.y }, p2, nextLen, nextStep = 0.01, angleFinder = segInfo.angleFinder, lastPerc;
      while (tmpLen < distance && perc <= 1 && nextStep > 1e-4) {
        p2 = iterator(perc);
        lastPerc = perc;
        nextLen = calcLineLength(tempP.x, tempP.y, p2.x, p2.y);
        if (nextLen + tmpLen > distance) {
          nextStep /= 2;
          perc -= nextStep;
        } else {
          tempP = p2;
          perc += nextStep;
          tmpLen += nextLen;
        }
      }
      p2.angle = angleFinder(lastPerc);
      return p2;
    }
    function getPathSegmentsInfo(path) {
      var totalLength = 0, len = path.length, current, x1 = 0, y1 = 0, x2 = 0, y2 = 0, info = [], iterator, tempInfo, angleFinder;
      for (var i2 = 0; i2 < len; i2++) {
        current = path[i2];
        tempInfo = {
          x: x1,
          y: y1,
          command: current[0]
        };
        switch (current[0]) {
          case "M":
            tempInfo.length = 0;
            x2 = x1 = current[1];
            y2 = y1 = current[2];
            break;
          case "L":
            tempInfo.length = calcLineLength(x1, y1, current[1], current[2]);
            x1 = current[1];
            y1 = current[2];
            break;
          case "C":
            iterator = getPointOnCubicBezierIterator(x1, y1, current[1], current[2], current[3], current[4], current[5], current[6]);
            angleFinder = getTangentCubicIterator(x1, y1, current[1], current[2], current[3], current[4], current[5], current[6]);
            tempInfo.iterator = iterator;
            tempInfo.angleFinder = angleFinder;
            tempInfo.length = pathIterator(iterator, x1, y1);
            x1 = current[5];
            y1 = current[6];
            break;
          case "Q":
            iterator = getPointOnQuadraticBezierIterator(x1, y1, current[1], current[2], current[3], current[4]);
            angleFinder = getTangentQuadraticIterator(x1, y1, current[1], current[2], current[3], current[4]);
            tempInfo.iterator = iterator;
            tempInfo.angleFinder = angleFinder;
            tempInfo.length = pathIterator(iterator, x1, y1);
            x1 = current[3];
            y1 = current[4];
            break;
          case "Z":
          case "z":
            tempInfo.destX = x2;
            tempInfo.destY = y2;
            tempInfo.length = calcLineLength(x1, y1, x2, y2);
            x1 = x2;
            y1 = y2;
            break;
        }
        totalLength += tempInfo.length;
        info.push(tempInfo);
      }
      info.push({ length: totalLength, x: x1, y: y1 });
      return info;
    }
    function getPointOnPath(path, distance, infos) {
      if (!infos) {
        infos = getPathSegmentsInfo(path);
      }
      var i2 = 0;
      while (distance - infos[i2].length > 0 && i2 < infos.length - 2) {
        distance -= infos[i2].length;
        i2++;
      }
      var segInfo = infos[i2], segPercent = distance / segInfo.length, command = segInfo.command, segment = path[i2], info;
      switch (command) {
        case "M":
          return { x: segInfo.x, y: segInfo.y, angle: 0 };
        case "Z":
        case "z":
          info = new fabric2.Point(segInfo.x, segInfo.y).lerp(new fabric2.Point(segInfo.destX, segInfo.destY), segPercent);
          info.angle = Math.atan2(segInfo.destY - segInfo.y, segInfo.destX - segInfo.x);
          return info;
        case "L":
          info = new fabric2.Point(segInfo.x, segInfo.y).lerp(new fabric2.Point(segment[1], segment[2]), segPercent);
          info.angle = Math.atan2(segment[2] - segInfo.y, segment[1] - segInfo.x);
          return info;
        case "C":
          return findPercentageForDistance(segInfo, distance);
        case "Q":
          return findPercentageForDistance(segInfo, distance);
      }
    }
    function parsePath(pathString) {
      var result = [], coords = [], currentPath, parsed, re = fabric2.rePathCommand, rNumber = "[-+]?(?:\\d*\\.\\d+|\\d+\\.?)(?:[eE][-+]?\\d+)?\\s*", rNumberCommaWsp = "(" + rNumber + ")" + fabric2.commaWsp, rFlagCommaWsp = "([01])" + fabric2.commaWsp + "?", rArcSeq = rNumberCommaWsp + "?" + rNumberCommaWsp + "?" + rNumberCommaWsp + rFlagCommaWsp + rFlagCommaWsp + rNumberCommaWsp + "?(" + rNumber + ")", regArcArgumentSequence = new RegExp(rArcSeq, "g"), match, coordsStr, path;
      if (!pathString || !pathString.match) {
        return result;
      }
      path = pathString.match(/[mzlhvcsqta][^mzlhvcsqta]*/gi);
      for (var i2 = 0, coordsParsed, len = path.length; i2 < len; i2++) {
        currentPath = path[i2];
        coordsStr = currentPath.slice(1).trim();
        coords.length = 0;
        var command = currentPath.charAt(0);
        coordsParsed = [command];
        if (command.toLowerCase() === "a") {
          for (var args; args = regArcArgumentSequence.exec(coordsStr); ) {
            for (var j2 = 1; j2 < args.length; j2++) {
              coords.push(args[j2]);
            }
          }
        } else {
          while (match = re.exec(coordsStr)) {
            coords.push(match[0]);
          }
        }
        for (var j2 = 0, jlen = coords.length; j2 < jlen; j2++) {
          parsed = parseFloat(coords[j2]);
          if (!isNaN(parsed)) {
            coordsParsed.push(parsed);
          }
        }
        var commandLength = commandLengths[command.toLowerCase()], repeatedCommand = repeatedCommands[command] || command;
        if (coordsParsed.length - 1 > commandLength) {
          for (var k2 = 1, klen = coordsParsed.length; k2 < klen; k2 += commandLength) {
            result.push([command].concat(coordsParsed.slice(k2, k2 + commandLength)));
            command = repeatedCommand;
          }
        } else {
          result.push(coordsParsed);
        }
      }
      return result;
    }
    function getSmoothPathFromPoints(points, correction) {
      var path = [], i2, p1 = new fabric2.Point(points[0].x, points[0].y), p2 = new fabric2.Point(points[1].x, points[1].y), len = points.length, multSignX = 1, multSignY = 0, manyPoints = len > 2;
      correction = correction || 0;
      if (manyPoints) {
        multSignX = points[2].x < p2.x ? -1 : points[2].x === p2.x ? 0 : 1;
        multSignY = points[2].y < p2.y ? -1 : points[2].y === p2.y ? 0 : 1;
      }
      path.push(["M", p1.x - multSignX * correction, p1.y - multSignY * correction]);
      for (i2 = 1; i2 < len; i2++) {
        if (!p1.eq(p2)) {
          var midPoint = p1.midPointFrom(p2);
          path.push(["Q", p1.x, p1.y, midPoint.x, midPoint.y]);
        }
        p1 = points[i2];
        if (i2 + 1 < points.length) {
          p2 = points[i2 + 1];
        }
      }
      if (manyPoints) {
        multSignX = p1.x > points[i2 - 2].x ? 1 : p1.x === points[i2 - 2].x ? 0 : -1;
        multSignY = p1.y > points[i2 - 2].y ? 1 : p1.y === points[i2 - 2].y ? 0 : -1;
      }
      path.push(["L", p1.x + multSignX * correction, p1.y + multSignY * correction]);
      return path;
    }
    function transformPath(path, transform2, pathOffset) {
      if (pathOffset) {
        transform2 = fabric2.util.multiplyTransformMatrices(transform2, [1, 0, 0, 1, -pathOffset.x, -pathOffset.y]);
      }
      return path.map(function(pathSegment) {
        var newSegment = pathSegment.slice(0), point = {};
        for (var i2 = 1; i2 < pathSegment.length - 1; i2 += 2) {
          point.x = pathSegment[i2];
          point.y = pathSegment[i2 + 1];
          point = fabric2.util.transformPoint(point, transform2);
          newSegment[i2] = point.x;
          newSegment[i2 + 1] = point.y;
        }
        return newSegment;
      });
    }
    function getBoundsOfArc(fx, fy, rx, ry, rot, large, sweep, tx, ty) {
      var fromX = 0, fromY = 0, bound, bounds = [], segs = arcToSegments(tx - fx, ty - fy, rx, ry, large, sweep, rot);
      for (var i2 = 0, len = segs.length; i2 < len; i2++) {
        bound = getBoundsOfCurve(fromX, fromY, segs[i2][1], segs[i2][2], segs[i2][3], segs[i2][4], segs[i2][5], segs[i2][6]);
        bounds.push({ x: bound[0].x + fx, y: bound[0].y + fy });
        bounds.push({ x: bound[1].x + fx, y: bound[1].y + fy });
        fromX = segs[i2][5];
        fromY = segs[i2][6];
      }
      return bounds;
    }
    function drawArc(ctx, fx, fy, coords) {
      coords = coords.slice(0).unshift("X");
      var beziers = fromArcToBeziers(fx, fy, coords);
      beziers.forEach(function(bezier) {
        ctx.bezierCurveTo.apply(ctx, bezier.slice(1));
      });
    }
    fabric2.util.joinPath = function(pathData) {
      return pathData.map(function(segment) {
        return segment.join(" ");
      }).join(" ");
    };
    fabric2.util.parsePath = parsePath;
    fabric2.util.makePathSimpler = makePathSimpler;
    fabric2.util.getSmoothPathFromPoints = getSmoothPathFromPoints;
    fabric2.util.getPathSegmentsInfo = getPathSegmentsInfo;
    fabric2.util.getBoundsOfCurve = getBoundsOfCurve;
    fabric2.util.getPointOnPath = getPointOnPath;
    fabric2.util.transformPath = transformPath;
    fabric2.util.fromArcToBeizers = fromArcToBeziers;
    fabric2.util.getBoundsOfArc = getBoundsOfArc;
    fabric2.util.drawArc = drawArc;
  })();
  (function() {
    var slice2 = Array.prototype.slice;
    function invoke(array, method) {
      var args = slice2.call(arguments, 2), result = [];
      for (var i2 = 0, len = array.length; i2 < len; i2++) {
        result[i2] = args.length ? array[i2][method].apply(array[i2], args) : array[i2][method].call(array[i2]);
      }
      return result;
    }
    function max(array, byProperty) {
      return find(array, byProperty, function(value1, value2) {
        return value1 >= value2;
      });
    }
    function min(array, byProperty) {
      return find(array, byProperty, function(value1, value2) {
        return value1 < value2;
      });
    }
    function fill2(array, value) {
      var k2 = array.length;
      while (k2--) {
        array[k2] = value;
      }
      return array;
    }
    function find(array, byProperty, condition) {
      if (!array || array.length === 0) {
        return;
      }
      var i2 = array.length - 1, result = byProperty ? array[i2][byProperty] : array[i2];
      if (byProperty) {
        while (i2--) {
          if (condition(array[i2][byProperty], result)) {
            result = array[i2][byProperty];
          }
        }
      } else {
        while (i2--) {
          if (condition(array[i2], result)) {
            result = array[i2];
          }
        }
      }
      return result;
    }
    fabric2.util.array = {
      fill: fill2,
      invoke,
      min,
      max
    };
  })();
  (function() {
    function extend(destination, source, deep) {
      if (deep) {
        if (!fabric2.isLikelyNode && source instanceof Element) {
          destination = source;
        } else if (source instanceof Array) {
          destination = [];
          for (var i2 = 0, len = source.length; i2 < len; i2++) {
            destination[i2] = extend({}, source[i2], deep);
          }
        } else if (source && typeof source === "object") {
          for (var property in source) {
            if (property === "canvas" || property === "group") {
              destination[property] = null;
            } else if (source.hasOwnProperty(property)) {
              destination[property] = extend({}, source[property], deep);
            }
          }
        } else {
          destination = source;
        }
      } else {
        for (var property in source) {
          destination[property] = source[property];
        }
      }
      return destination;
    }
    function clone(object, deep) {
      return extend({}, object, deep);
    }
    fabric2.util.object = {
      extend,
      clone
    };
    fabric2.util.object.extend(fabric2.util, fabric2.Observable);
  })();
  (function() {
    function camelize2(string) {
      return string.replace(/-+(.)?/g, function(match, character) {
        return character ? character.toUpperCase() : "";
      });
    }
    function capitalize2(string, firstLetterOnly) {
      return string.charAt(0).toUpperCase() + (firstLetterOnly ? string.slice(1) : string.slice(1).toLowerCase());
    }
    function escapeXml(string) {
      return string.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/'/g, "&apos;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
    }
    function graphemeSplit(textstring) {
      var i2 = 0, chr, graphemes = [];
      for (i2 = 0, chr; i2 < textstring.length; i2++) {
        if ((chr = getWholeChar(textstring, i2)) === false) {
          continue;
        }
        graphemes.push(chr);
      }
      return graphemes;
    }
    function getWholeChar(str, i2) {
      var code = str.charCodeAt(i2);
      if (isNaN(code)) {
        return "";
      }
      if (code < 55296 || code > 57343) {
        return str.charAt(i2);
      }
      if (55296 <= code && code <= 56319) {
        if (str.length <= i2 + 1) {
          throw "High surrogate without following low surrogate";
        }
        var next = str.charCodeAt(i2 + 1);
        if (56320 > next || next > 57343) {
          throw "High surrogate without following low surrogate";
        }
        return str.charAt(i2) + str.charAt(i2 + 1);
      }
      if (i2 === 0) {
        throw "Low surrogate without preceding high surrogate";
      }
      var prev = str.charCodeAt(i2 - 1);
      if (55296 > prev || prev > 56319) {
        throw "Low surrogate without preceding high surrogate";
      }
      return false;
    }
    fabric2.util.string = {
      camelize: camelize2,
      capitalize: capitalize2,
      escapeXml,
      graphemeSplit
    };
  })();
  (function() {
    var slice2 = Array.prototype.slice, emptyFunction2 = function() {
    }, IS_DONTENUM_BUGGY = function() {
      for (var p2 in { toString: 1 }) {
        if (p2 === "toString") {
          return false;
        }
      }
      return true;
    }(), addMethods = function(klass, source, parent) {
      for (var property in source) {
        if (property in klass.prototype && typeof klass.prototype[property] === "function" && (source[property] + "").indexOf("callSuper") > -1) {
          klass.prototype[property] = function(property2) {
            return function() {
              var superclass = this.constructor.superclass;
              this.constructor.superclass = parent;
              var returnValue = source[property2].apply(this, arguments);
              this.constructor.superclass = superclass;
              if (property2 !== "initialize") {
                return returnValue;
              }
            };
          }(property);
        } else {
          klass.prototype[property] = source[property];
        }
        if (IS_DONTENUM_BUGGY) {
          if (source.toString !== Object.prototype.toString) {
            klass.prototype.toString = source.toString;
          }
          if (source.valueOf !== Object.prototype.valueOf) {
            klass.prototype.valueOf = source.valueOf;
          }
        }
      }
    };
    function Subclass() {
    }
    function callSuper(methodName) {
      var parentMethod = null, _this = this;
      while (_this.constructor.superclass) {
        var superClassMethod = _this.constructor.superclass.prototype[methodName];
        if (_this[methodName] !== superClassMethod) {
          parentMethod = superClassMethod;
          break;
        }
        _this = _this.constructor.superclass.prototype;
      }
      if (!parentMethod) {
        return console.log("tried to callSuper " + methodName + ", method not found in prototype chain", this);
      }
      return arguments.length > 1 ? parentMethod.apply(this, slice2.call(arguments, 1)) : parentMethod.call(this);
    }
    function createClass() {
      var parent = null, properties2 = slice2.call(arguments, 0);
      if (typeof properties2[0] === "function") {
        parent = properties2.shift();
      }
      function klass() {
        this.initialize.apply(this, arguments);
      }
      klass.superclass = parent;
      klass.subclasses = [];
      if (parent) {
        Subclass.prototype = parent.prototype;
        klass.prototype = new Subclass();
        parent.subclasses.push(klass);
      }
      for (var i2 = 0, length = properties2.length; i2 < length; i2++) {
        addMethods(klass, properties2[i2], parent);
      }
      if (!klass.prototype.initialize) {
        klass.prototype.initialize = emptyFunction2;
      }
      klass.prototype.constructor = klass;
      klass.prototype.callSuper = callSuper;
      return klass;
    }
    fabric2.util.createClass = createClass;
  })();
  (function() {
    var couldUseAttachEvent = !!fabric2.document.createElement("div").attachEvent, touchEvents = ["touchstart", "touchmove", "touchend"];
    fabric2.util.addListener = function(element, eventName, handler, options) {
      element && element.addEventListener(eventName, handler, couldUseAttachEvent ? false : options);
    };
    fabric2.util.removeListener = function(element, eventName, handler, options) {
      element && element.removeEventListener(eventName, handler, couldUseAttachEvent ? false : options);
    };
    function getTouchInfo(event) {
      var touchProp = event.changedTouches;
      if (touchProp && touchProp[0]) {
        return touchProp[0];
      }
      return event;
    }
    fabric2.util.getPointer = function(event) {
      var element = event.target, scroll = fabric2.util.getScrollLeftTop(element), _evt = getTouchInfo(event);
      return {
        x: _evt.clientX + scroll.left,
        y: _evt.clientY + scroll.top
      };
    };
    fabric2.util.isTouchEvent = function(event) {
      return touchEvents.indexOf(event.type) > -1 || event.pointerType === "touch";
    };
  })();
  (function() {
    function setStyle(element, styles) {
      var elementStyle = element.style;
      if (!elementStyle) {
        return element;
      }
      if (typeof styles === "string") {
        element.style.cssText += ";" + styles;
        return styles.indexOf("opacity") > -1 ? setOpacity(element, styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element;
      }
      for (var property in styles) {
        if (property === "opacity") {
          setOpacity(element, styles[property]);
        } else {
          var normalizedProperty = property === "float" || property === "cssFloat" ? typeof elementStyle.styleFloat === "undefined" ? "cssFloat" : "styleFloat" : property;
          elementStyle[normalizedProperty] = styles[property];
        }
      }
      return element;
    }
    var parseEl = fabric2.document.createElement("div"), supportsOpacity = typeof parseEl.style.opacity === "string", supportsFilters = typeof parseEl.style.filter === "string", reOpacity = /alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/, setOpacity = function(element) {
      return element;
    };
    if (supportsOpacity) {
      setOpacity = function(element, value) {
        element.style.opacity = value;
        return element;
      };
    } else if (supportsFilters) {
      setOpacity = function(element, value) {
        var es = element.style;
        if (element.currentStyle && !element.currentStyle.hasLayout) {
          es.zoom = 1;
        }
        if (reOpacity.test(es.filter)) {
          value = value >= 0.9999 ? "" : "alpha(opacity=" + value * 100 + ")";
          es.filter = es.filter.replace(reOpacity, value);
        } else {
          es.filter += " alpha(opacity=" + value * 100 + ")";
        }
        return element;
      };
    }
    fabric2.util.setStyle = setStyle;
  })();
  (function() {
    var _slice2 = Array.prototype.slice;
    function getById(id2) {
      return typeof id2 === "string" ? fabric2.document.getElementById(id2) : id2;
    }
    var sliceCanConvertNodelists, toArray = function(arrayLike) {
      return _slice2.call(arrayLike, 0);
    };
    try {
      sliceCanConvertNodelists = toArray(fabric2.document.childNodes) instanceof Array;
    } catch (err) {
    }
    if (!sliceCanConvertNodelists) {
      toArray = function(arrayLike) {
        var arr = new Array(arrayLike.length), i2 = arrayLike.length;
        while (i2--) {
          arr[i2] = arrayLike[i2];
        }
        return arr;
      };
    }
    function makeElement(tagName, attributes) {
      var el = fabric2.document.createElement(tagName);
      for (var prop in attributes) {
        if (prop === "class") {
          el.className = attributes[prop];
        } else if (prop === "for") {
          el.htmlFor = attributes[prop];
        } else {
          el.setAttribute(prop, attributes[prop]);
        }
      }
      return el;
    }
    function addClass(element, className) {
      if (element && (" " + element.className + " ").indexOf(" " + className + " ") === -1) {
        element.className += (element.className ? " " : "") + className;
      }
    }
    function wrapElement(element, wrapper, attributes) {
      if (typeof wrapper === "string") {
        wrapper = makeElement(wrapper, attributes);
      }
      if (element.parentNode) {
        element.parentNode.replaceChild(wrapper, element);
      }
      wrapper.appendChild(element);
      return wrapper;
    }
    function getScrollLeftTop(element) {
      var left = 0, top = 0, docElement = fabric2.document.documentElement, body = fabric2.document.body || {
        scrollLeft: 0,
        scrollTop: 0
      };
      while (element && (element.parentNode || element.host)) {
        element = element.parentNode || element.host;
        if (element === fabric2.document) {
          left = body.scrollLeft || docElement.scrollLeft || 0;
          top = body.scrollTop || docElement.scrollTop || 0;
        } else {
          left += element.scrollLeft || 0;
          top += element.scrollTop || 0;
        }
        if (element.nodeType === 1 && element.style.position === "fixed") {
          break;
        }
      }
      return { left, top };
    }
    function getElementOffset(element) {
      var docElem, doc = element && element.ownerDocument, box = { left: 0, top: 0 }, offset2 = { left: 0, top: 0 }, scrollLeftTop, offsetAttributes = {
        borderLeftWidth: "left",
        borderTopWidth: "top",
        paddingLeft: "left",
        paddingTop: "top"
      };
      if (!doc) {
        return offset2;
      }
      for (var attr in offsetAttributes) {
        offset2[offsetAttributes[attr]] += parseInt(getElementStyle(element, attr), 10) || 0;
      }
      docElem = doc.documentElement;
      if (typeof element.getBoundingClientRect !== "undefined") {
        box = element.getBoundingClientRect();
      }
      scrollLeftTop = getScrollLeftTop(element);
      return {
        left: box.left + scrollLeftTop.left - (docElem.clientLeft || 0) + offset2.left,
        top: box.top + scrollLeftTop.top - (docElem.clientTop || 0) + offset2.top
      };
    }
    var getElementStyle;
    if (fabric2.document.defaultView && fabric2.document.defaultView.getComputedStyle) {
      getElementStyle = function(element, attr) {
        var style2 = fabric2.document.defaultView.getComputedStyle(element, null);
        return style2 ? style2[attr] : void 0;
      };
    } else {
      getElementStyle = function(element, attr) {
        var value = element.style[attr];
        if (!value && element.currentStyle) {
          value = element.currentStyle[attr];
        }
        return value;
      };
    }
    (function() {
      var style2 = fabric2.document.documentElement.style, selectProp = "userSelect" in style2 ? "userSelect" : "MozUserSelect" in style2 ? "MozUserSelect" : "WebkitUserSelect" in style2 ? "WebkitUserSelect" : "KhtmlUserSelect" in style2 ? "KhtmlUserSelect" : "";
      function makeElementUnselectable(element) {
        if (typeof element.onselectstart !== "undefined") {
          element.onselectstart = fabric2.util.falseFunction;
        }
        if (selectProp) {
          element.style[selectProp] = "none";
        } else if (typeof element.unselectable === "string") {
          element.unselectable = "on";
        }
        return element;
      }
      function makeElementSelectable(element) {
        if (typeof element.onselectstart !== "undefined") {
          element.onselectstart = null;
        }
        if (selectProp) {
          element.style[selectProp] = "";
        } else if (typeof element.unselectable === "string") {
          element.unselectable = "";
        }
        return element;
      }
      fabric2.util.makeElementUnselectable = makeElementUnselectable;
      fabric2.util.makeElementSelectable = makeElementSelectable;
    })();
    function getNodeCanvas(element) {
      var impl = fabric2.jsdomImplForWrapper(element);
      return impl._canvas || impl._image;
    }
    function cleanUpJsdomNode(element) {
      if (!fabric2.isLikelyNode) {
        return;
      }
      var impl = fabric2.jsdomImplForWrapper(element);
      if (impl) {
        impl._image = null;
        impl._canvas = null;
        impl._currentSrc = null;
        impl._attributes = null;
        impl._classList = null;
      }
    }
    function setImageSmoothing(ctx, value) {
      ctx.imageSmoothingEnabled = ctx.imageSmoothingEnabled || ctx.webkitImageSmoothingEnabled || ctx.mozImageSmoothingEnabled || ctx.msImageSmoothingEnabled || ctx.oImageSmoothingEnabled;
      ctx.imageSmoothingEnabled = value;
    }
    fabric2.util.setImageSmoothing = setImageSmoothing;
    fabric2.util.getById = getById;
    fabric2.util.toArray = toArray;
    fabric2.util.addClass = addClass;
    fabric2.util.makeElement = makeElement;
    fabric2.util.wrapElement = wrapElement;
    fabric2.util.getScrollLeftTop = getScrollLeftTop;
    fabric2.util.getElementOffset = getElementOffset;
    fabric2.util.getNodeCanvas = getNodeCanvas;
    fabric2.util.cleanUpJsdomNode = cleanUpJsdomNode;
  })();
  (function() {
    function addParamToUrl(url, param) {
      return url + (/\?/.test(url) ? "&" : "?") + param;
    }
    function emptyFn() {
    }
    function request(url, options) {
      options || (options = {});
      var method = options.method ? options.method.toUpperCase() : "GET", onComplete = options.onComplete || function() {
      }, xhr = new fabric2.window.XMLHttpRequest(), body = options.body || options.parameters;
      xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
          onComplete(xhr);
          xhr.onreadystatechange = emptyFn;
        }
      };
      if (method === "GET") {
        body = null;
        if (typeof options.parameters === "string") {
          url = addParamToUrl(url, options.parameters);
        }
      }
      xhr.open(method, url, true);
      if (method === "POST" || method === "PUT") {
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      }
      xhr.send(body);
      return xhr;
    }
    fabric2.util.request = request;
  })();
  fabric2.log = console.log;
  fabric2.warn = console.warn;
  (function() {
    function noop2() {
      return false;
    }
    function defaultEasing2(t2, b2, c2, d2) {
      return -c2 * Math.cos(t2 / d2 * (Math.PI / 2)) + c2 + b2;
    }
    function animate2(options) {
      var cancel = false;
      requestAnimFrame(function(timestamp) {
        options || (options = {});
        var start = timestamp || +new Date(), duration = options.duration || 500, finish = start + duration, time, onChange = options.onChange || noop2, abort = options.abort || noop2, onComplete = options.onComplete || noop2, easing = options.easing || defaultEasing2, startValue = "startValue" in options ? options.startValue : 0, endValue = "endValue" in options ? options.endValue : 100, byValue = options.byValue || endValue - startValue;
        options.onStart && options.onStart();
        (function tick(ticktime) {
          time = ticktime || +new Date();
          var currentTime = time > finish ? duration : time - start, timePerc = currentTime / duration, current = easing(currentTime, startValue, byValue, duration), valuePerc = Math.abs((current - startValue) / byValue);
          if (cancel) {
            return;
          }
          if (abort(current, valuePerc, timePerc)) {
            onComplete(endValue, 1, 1);
            return;
          }
          if (time > finish) {
            onChange(endValue, 1, 1);
            onComplete(endValue, 1, 1);
            return;
          } else {
            onChange(current, valuePerc, timePerc);
            requestAnimFrame(tick);
          }
        })(start);
      });
      return function() {
        cancel = true;
      };
    }
    var _requestAnimFrame = fabric2.window.requestAnimationFrame || fabric2.window.webkitRequestAnimationFrame || fabric2.window.mozRequestAnimationFrame || fabric2.window.oRequestAnimationFrame || fabric2.window.msRequestAnimationFrame || function(callback) {
      return fabric2.window.setTimeout(callback, 1e3 / 60);
    };
    var _cancelAnimFrame = fabric2.window.cancelAnimationFrame || fabric2.window.clearTimeout;
    function requestAnimFrame() {
      return _requestAnimFrame.apply(fabric2.window, arguments);
    }
    function cancelAnimFrame() {
      return _cancelAnimFrame.apply(fabric2.window, arguments);
    }
    fabric2.util.animate = animate2;
    fabric2.util.requestAnimFrame = requestAnimFrame;
    fabric2.util.cancelAnimFrame = cancelAnimFrame;
  })();
  (function() {
    function calculateColor(begin, end, pos) {
      var color2 = "rgba(" + parseInt(begin[0] + pos * (end[0] - begin[0]), 10) + "," + parseInt(begin[1] + pos * (end[1] - begin[1]), 10) + "," + parseInt(begin[2] + pos * (end[2] - begin[2]), 10);
      color2 += "," + (begin && end ? parseFloat(begin[3] + pos * (end[3] - begin[3])) : 1);
      color2 += ")";
      return color2;
    }
    function animateColor(fromColor, toColor, duration, options) {
      var startColor = new fabric2.Color(fromColor).getSource(), endColor = new fabric2.Color(toColor).getSource(), originalOnComplete = options.onComplete, originalOnChange = options.onChange;
      options = options || {};
      return fabric2.util.animate(fabric2.util.object.extend(options, {
        duration: duration || 500,
        startValue: startColor,
        endValue: endColor,
        byValue: endColor,
        easing: function(currentTime, startValue, byValue, duration2) {
          var posValue = options.colorEasing ? options.colorEasing(currentTime, duration2) : 1 - Math.cos(currentTime / duration2 * (Math.PI / 2));
          return calculateColor(startValue, byValue, posValue);
        },
        onComplete: function(current, valuePerc, timePerc) {
          if (originalOnComplete) {
            return originalOnComplete(calculateColor(endColor, endColor, 0), valuePerc, timePerc);
          }
        },
        onChange: function(current, valuePerc, timePerc) {
          if (originalOnChange) {
            if (Array.isArray(current)) {
              return originalOnChange(calculateColor(current, current, 0), valuePerc, timePerc);
            }
            originalOnChange(current, valuePerc, timePerc);
          }
        }
      }));
    }
    fabric2.util.animateColor = animateColor;
  })();
  (function() {
    function normalize2(a2, c2, p2, s2) {
      if (a2 < Math.abs(c2)) {
        a2 = c2;
        s2 = p2 / 4;
      } else {
        if (c2 === 0 && a2 === 0) {
          s2 = p2 / (2 * Math.PI) * Math.asin(1);
        } else {
          s2 = p2 / (2 * Math.PI) * Math.asin(c2 / a2);
        }
      }
      return { a: a2, c: c2, p: p2, s: s2 };
    }
    function elastic(opts, t2, d2) {
      return opts.a * Math.pow(2, 10 * (t2 -= 1)) * Math.sin((t2 * d2 - opts.s) * (2 * Math.PI) / opts.p);
    }
    function easeOutCubic(t2, b2, c2, d2) {
      return c2 * ((t2 = t2 / d2 - 1) * t2 * t2 + 1) + b2;
    }
    function easeInOutCubic(t2, b2, c2, d2) {
      t2 /= d2 / 2;
      if (t2 < 1) {
        return c2 / 2 * t2 * t2 * t2 + b2;
      }
      return c2 / 2 * ((t2 -= 2) * t2 * t2 + 2) + b2;
    }
    function easeInQuart(t2, b2, c2, d2) {
      return c2 * (t2 /= d2) * t2 * t2 * t2 + b2;
    }
    function easeOutQuart(t2, b2, c2, d2) {
      return -c2 * ((t2 = t2 / d2 - 1) * t2 * t2 * t2 - 1) + b2;
    }
    function easeInOutQuart(t2, b2, c2, d2) {
      t2 /= d2 / 2;
      if (t2 < 1) {
        return c2 / 2 * t2 * t2 * t2 * t2 + b2;
      }
      return -c2 / 2 * ((t2 -= 2) * t2 * t2 * t2 - 2) + b2;
    }
    function easeInQuint(t2, b2, c2, d2) {
      return c2 * (t2 /= d2) * t2 * t2 * t2 * t2 + b2;
    }
    function easeOutQuint(t2, b2, c2, d2) {
      return c2 * ((t2 = t2 / d2 - 1) * t2 * t2 * t2 * t2 + 1) + b2;
    }
    function easeInOutQuint(t2, b2, c2, d2) {
      t2 /= d2 / 2;
      if (t2 < 1) {
        return c2 / 2 * t2 * t2 * t2 * t2 * t2 + b2;
      }
      return c2 / 2 * ((t2 -= 2) * t2 * t2 * t2 * t2 + 2) + b2;
    }
    function easeInSine(t2, b2, c2, d2) {
      return -c2 * Math.cos(t2 / d2 * (Math.PI / 2)) + c2 + b2;
    }
    function easeOutSine(t2, b2, c2, d2) {
      return c2 * Math.sin(t2 / d2 * (Math.PI / 2)) + b2;
    }
    function easeInOutSine(t2, b2, c2, d2) {
      return -c2 / 2 * (Math.cos(Math.PI * t2 / d2) - 1) + b2;
    }
    function easeInExpo(t2, b2, c2, d2) {
      return t2 === 0 ? b2 : c2 * Math.pow(2, 10 * (t2 / d2 - 1)) + b2;
    }
    function easeOutExpo(t2, b2, c2, d2) {
      return t2 === d2 ? b2 + c2 : c2 * (-Math.pow(2, -10 * t2 / d2) + 1) + b2;
    }
    function easeInOutExpo(t2, b2, c2, d2) {
      if (t2 === 0) {
        return b2;
      }
      if (t2 === d2) {
        return b2 + c2;
      }
      t2 /= d2 / 2;
      if (t2 < 1) {
        return c2 / 2 * Math.pow(2, 10 * (t2 - 1)) + b2;
      }
      return c2 / 2 * (-Math.pow(2, -10 * --t2) + 2) + b2;
    }
    function easeInCirc(t2, b2, c2, d2) {
      return -c2 * (Math.sqrt(1 - (t2 /= d2) * t2) - 1) + b2;
    }
    function easeOutCirc(t2, b2, c2, d2) {
      return c2 * Math.sqrt(1 - (t2 = t2 / d2 - 1) * t2) + b2;
    }
    function easeInOutCirc(t2, b2, c2, d2) {
      t2 /= d2 / 2;
      if (t2 < 1) {
        return -c2 / 2 * (Math.sqrt(1 - t2 * t2) - 1) + b2;
      }
      return c2 / 2 * (Math.sqrt(1 - (t2 -= 2) * t2) + 1) + b2;
    }
    function easeInElastic(t2, b2, c2, d2) {
      var s2 = 1.70158, p2 = 0, a2 = c2;
      if (t2 === 0) {
        return b2;
      }
      t2 /= d2;
      if (t2 === 1) {
        return b2 + c2;
      }
      if (!p2) {
        p2 = d2 * 0.3;
      }
      var opts = normalize2(a2, c2, p2, s2);
      return -elastic(opts, t2, d2) + b2;
    }
    function easeOutElastic(t2, b2, c2, d2) {
      var s2 = 1.70158, p2 = 0, a2 = c2;
      if (t2 === 0) {
        return b2;
      }
      t2 /= d2;
      if (t2 === 1) {
        return b2 + c2;
      }
      if (!p2) {
        p2 = d2 * 0.3;
      }
      var opts = normalize2(a2, c2, p2, s2);
      return opts.a * Math.pow(2, -10 * t2) * Math.sin((t2 * d2 - opts.s) * (2 * Math.PI) / opts.p) + opts.c + b2;
    }
    function easeInOutElastic(t2, b2, c2, d2) {
      var s2 = 1.70158, p2 = 0, a2 = c2;
      if (t2 === 0) {
        return b2;
      }
      t2 /= d2 / 2;
      if (t2 === 2) {
        return b2 + c2;
      }
      if (!p2) {
        p2 = d2 * (0.3 * 1.5);
      }
      var opts = normalize2(a2, c2, p2, s2);
      if (t2 < 1) {
        return -0.5 * elastic(opts, t2, d2) + b2;
      }
      return opts.a * Math.pow(2, -10 * (t2 -= 1)) * Math.sin((t2 * d2 - opts.s) * (2 * Math.PI) / opts.p) * 0.5 + opts.c + b2;
    }
    function easeInBack(t2, b2, c2, d2, s2) {
      if (s2 === void 0) {
        s2 = 1.70158;
      }
      return c2 * (t2 /= d2) * t2 * ((s2 + 1) * t2 - s2) + b2;
    }
    function easeOutBack(t2, b2, c2, d2, s2) {
      if (s2 === void 0) {
        s2 = 1.70158;
      }
      return c2 * ((t2 = t2 / d2 - 1) * t2 * ((s2 + 1) * t2 + s2) + 1) + b2;
    }
    function easeInOutBack(t2, b2, c2, d2, s2) {
      if (s2 === void 0) {
        s2 = 1.70158;
      }
      t2 /= d2 / 2;
      if (t2 < 1) {
        return c2 / 2 * (t2 * t2 * (((s2 *= 1.525) + 1) * t2 - s2)) + b2;
      }
      return c2 / 2 * ((t2 -= 2) * t2 * (((s2 *= 1.525) + 1) * t2 + s2) + 2) + b2;
    }
    function easeInBounce(t2, b2, c2, d2) {
      return c2 - easeOutBounce(d2 - t2, 0, c2, d2) + b2;
    }
    function easeOutBounce(t2, b2, c2, d2) {
      if ((t2 /= d2) < 1 / 2.75) {
        return c2 * (7.5625 * t2 * t2) + b2;
      } else if (t2 < 2 / 2.75) {
        return c2 * (7.5625 * (t2 -= 1.5 / 2.75) * t2 + 0.75) + b2;
      } else if (t2 < 2.5 / 2.75) {
        return c2 * (7.5625 * (t2 -= 2.25 / 2.75) * t2 + 0.9375) + b2;
      } else {
        return c2 * (7.5625 * (t2 -= 2.625 / 2.75) * t2 + 0.984375) + b2;
      }
    }
    function easeInOutBounce(t2, b2, c2, d2) {
      if (t2 < d2 / 2) {
        return easeInBounce(t2 * 2, 0, c2, d2) * 0.5 + b2;
      }
      return easeOutBounce(t2 * 2 - d2, 0, c2, d2) * 0.5 + c2 * 0.5 + b2;
    }
    fabric2.util.ease = {
      easeInQuad: function(t2, b2, c2, d2) {
        return c2 * (t2 /= d2) * t2 + b2;
      },
      easeOutQuad: function(t2, b2, c2, d2) {
        return -c2 * (t2 /= d2) * (t2 - 2) + b2;
      },
      easeInOutQuad: function(t2, b2, c2, d2) {
        t2 /= d2 / 2;
        if (t2 < 1) {
          return c2 / 2 * t2 * t2 + b2;
        }
        return -c2 / 2 * (--t2 * (t2 - 2) - 1) + b2;
      },
      easeInCubic: function(t2, b2, c2, d2) {
        return c2 * (t2 /= d2) * t2 * t2 + b2;
      },
      easeOutCubic,
      easeInOutCubic,
      easeInQuart,
      easeOutQuart,
      easeInOutQuart,
      easeInQuint,
      easeOutQuint,
      easeInOutQuint,
      easeInSine,
      easeOutSine,
      easeInOutSine,
      easeInExpo,
      easeOutExpo,
      easeInOutExpo,
      easeInCirc,
      easeOutCirc,
      easeInOutCirc,
      easeInElastic,
      easeOutElastic,
      easeInOutElastic,
      easeInBack,
      easeOutBack,
      easeInOutBack,
      easeInBounce,
      easeOutBounce,
      easeInOutBounce
    };
  })();
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {}), extend = fabric3.util.object.extend, clone = fabric3.util.object.clone, toFixed = fabric3.util.toFixed, parseUnit = fabric3.util.parseUnit, multiplyTransformMatrices = fabric3.util.multiplyTransformMatrices, svgValidTagNames = [
      "path",
      "circle",
      "polygon",
      "polyline",
      "ellipse",
      "rect",
      "line",
      "image",
      "text"
    ], svgViewBoxElements = ["symbol", "image", "marker", "pattern", "view", "svg"], svgInvalidAncestors = ["pattern", "defs", "symbol", "metadata", "clipPath", "mask", "desc"], svgValidParents = ["symbol", "g", "a", "svg", "clipPath", "defs"], attributesMap = {
      cx: "left",
      x: "left",
      r: "radius",
      cy: "top",
      y: "top",
      display: "visible",
      visibility: "visible",
      transform: "transformMatrix",
      "fill-opacity": "fillOpacity",
      "fill-rule": "fillRule",
      "font-family": "fontFamily",
      "font-size": "fontSize",
      "font-style": "fontStyle",
      "font-weight": "fontWeight",
      "letter-spacing": "charSpacing",
      "paint-order": "paintFirst",
      "stroke-dasharray": "strokeDashArray",
      "stroke-dashoffset": "strokeDashOffset",
      "stroke-linecap": "strokeLineCap",
      "stroke-linejoin": "strokeLineJoin",
      "stroke-miterlimit": "strokeMiterLimit",
      "stroke-opacity": "strokeOpacity",
      "stroke-width": "strokeWidth",
      "text-decoration": "textDecoration",
      "text-anchor": "textAnchor",
      opacity: "opacity",
      "clip-path": "clipPath",
      "clip-rule": "clipRule",
      "vector-effect": "strokeUniform",
      "image-rendering": "imageSmoothing"
    }, colorAttributes = {
      stroke: "strokeOpacity",
      fill: "fillOpacity"
    }, fSize = "font-size", cPath = "clip-path";
    fabric3.svgValidTagNamesRegEx = getSvgRegex(svgValidTagNames);
    fabric3.svgViewBoxElementsRegEx = getSvgRegex(svgViewBoxElements);
    fabric3.svgInvalidAncestorsRegEx = getSvgRegex(svgInvalidAncestors);
    fabric3.svgValidParentsRegEx = getSvgRegex(svgValidParents);
    fabric3.cssRules = {};
    fabric3.gradientDefs = {};
    fabric3.clipPaths = {};
    function normalizeAttr(attr) {
      if (attr in attributesMap) {
        return attributesMap[attr];
      }
      return attr;
    }
    function normalizeValue2(attr, value, parentAttributes, fontSize) {
      var isArray = Object.prototype.toString.call(value) === "[object Array]", parsed;
      if ((attr === "fill" || attr === "stroke") && value === "none") {
        value = "";
      } else if (attr === "strokeUniform") {
        return value === "non-scaling-stroke";
      } else if (attr === "strokeDashArray") {
        if (value === "none") {
          value = null;
        } else {
          value = value.replace(/,/g, " ").split(/\s+/).map(parseFloat);
        }
      } else if (attr === "transformMatrix") {
        if (parentAttributes && parentAttributes.transformMatrix) {
          value = multiplyTransformMatrices(parentAttributes.transformMatrix, fabric3.parseTransformAttribute(value));
        } else {
          value = fabric3.parseTransformAttribute(value);
        }
      } else if (attr === "visible") {
        value = value !== "none" && value !== "hidden";
        if (parentAttributes && parentAttributes.visible === false) {
          value = false;
        }
      } else if (attr === "opacity") {
        value = parseFloat(value);
        if (parentAttributes && typeof parentAttributes.opacity !== "undefined") {
          value *= parentAttributes.opacity;
        }
      } else if (attr === "textAnchor") {
        value = value === "start" ? "left" : value === "end" ? "right" : "center";
      } else if (attr === "charSpacing") {
        parsed = parseUnit(value, fontSize) / fontSize * 1e3;
      } else if (attr === "paintFirst") {
        var fillIndex = value.indexOf("fill");
        var strokeIndex = value.indexOf("stroke");
        var value = "fill";
        if (fillIndex > -1 && strokeIndex > -1 && strokeIndex < fillIndex) {
          value = "stroke";
        } else if (fillIndex === -1 && strokeIndex > -1) {
          value = "stroke";
        }
      } else if (attr === "href" || attr === "xlink:href" || attr === "font") {
        return value;
      } else if (attr === "imageSmoothing") {
        return value === "optimizeQuality";
      } else {
        parsed = isArray ? value.map(parseUnit) : parseUnit(value, fontSize);
      }
      return !isArray && isNaN(parsed) ? value : parsed;
    }
    function getSvgRegex(arr) {
      return new RegExp("^(" + arr.join("|") + ")\\b", "i");
    }
    function _setStrokeFillOpacity(attributes) {
      for (var attr in colorAttributes) {
        if (typeof attributes[colorAttributes[attr]] === "undefined" || attributes[attr] === "") {
          continue;
        }
        if (typeof attributes[attr] === "undefined") {
          if (!fabric3.Object.prototype[attr]) {
            continue;
          }
          attributes[attr] = fabric3.Object.prototype[attr];
        }
        if (attributes[attr].indexOf("url(") === 0) {
          continue;
        }
        var color2 = new fabric3.Color(attributes[attr]);
        attributes[attr] = color2.setAlpha(toFixed(color2.getAlpha() * attributes[colorAttributes[attr]], 2)).toRgba();
      }
      return attributes;
    }
    function _getMultipleNodes(doc, nodeNames) {
      var nodeName, nodeArray = [], nodeList, i2, len;
      for (i2 = 0, len = nodeNames.length; i2 < len; i2++) {
        nodeName = nodeNames[i2];
        nodeList = doc.getElementsByTagName(nodeName);
        nodeArray = nodeArray.concat(Array.prototype.slice.call(nodeList));
      }
      return nodeArray;
    }
    fabric3.parseTransformAttribute = function() {
      function rotateMatrix(matrix2, args) {
        var cos = fabric3.util.cos(args[0]), sin = fabric3.util.sin(args[0]), x2 = 0, y2 = 0;
        if (args.length === 3) {
          x2 = args[1];
          y2 = args[2];
        }
        matrix2[0] = cos;
        matrix2[1] = sin;
        matrix2[2] = -sin;
        matrix2[3] = cos;
        matrix2[4] = x2 - (cos * x2 - sin * y2);
        matrix2[5] = y2 - (sin * x2 + cos * y2);
      }
      function scaleMatrix(matrix2, args) {
        var multiplierX = args[0], multiplierY = args.length === 2 ? args[1] : args[0];
        matrix2[0] = multiplierX;
        matrix2[3] = multiplierY;
      }
      function skewMatrix(matrix2, args, pos) {
        matrix2[pos] = Math.tan(fabric3.util.degreesToRadians(args[0]));
      }
      function translateMatrix(matrix2, args) {
        matrix2[4] = args[0];
        if (args.length === 2) {
          matrix2[5] = args[1];
        }
      }
      var iMatrix = fabric3.iMatrix, number2 = fabric3.reNum, commaWsp = fabric3.commaWsp, skewX = "(?:(skewX)\\s*\\(\\s*(" + number2 + ")\\s*\\))", skewY = "(?:(skewY)\\s*\\(\\s*(" + number2 + ")\\s*\\))", rotate = "(?:(rotate)\\s*\\(\\s*(" + number2 + ")(?:" + commaWsp + "(" + number2 + ")" + commaWsp + "(" + number2 + "))?\\s*\\))", scale2 = "(?:(scale)\\s*\\(\\s*(" + number2 + ")(?:" + commaWsp + "(" + number2 + "))?\\s*\\))", translate = "(?:(translate)\\s*\\(\\s*(" + number2 + ")(?:" + commaWsp + "(" + number2 + "))?\\s*\\))", matrix = "(?:(matrix)\\s*\\(\\s*(" + number2 + ")" + commaWsp + "(" + number2 + ")" + commaWsp + "(" + number2 + ")" + commaWsp + "(" + number2 + ")" + commaWsp + "(" + number2 + ")" + commaWsp + "(" + number2 + ")\\s*\\))", transform2 = "(?:" + matrix + "|" + translate + "|" + scale2 + "|" + rotate + "|" + skewX + "|" + skewY + ")", transforms = "(?:" + transform2 + "(?:" + commaWsp + "*" + transform2 + ")*)", transformList = "^\\s*(?:" + transforms + "?)\\s*$", reTransformList = new RegExp(transformList), reTransform = new RegExp(transform2, "g");
      return function(attributeValue) {
        var matrix2 = iMatrix.concat(), matrices = [];
        if (!attributeValue || attributeValue && !reTransformList.test(attributeValue)) {
          return matrix2;
        }
        attributeValue.replace(reTransform, function(match) {
          var m2 = new RegExp(transform2).exec(match).filter(function(match2) {
            return !!match2;
          }), operation = m2[1], args = m2.slice(2).map(parseFloat);
          switch (operation) {
            case "translate":
              translateMatrix(matrix2, args);
              break;
            case "rotate":
              args[0] = fabric3.util.degreesToRadians(args[0]);
              rotateMatrix(matrix2, args);
              break;
            case "scale":
              scaleMatrix(matrix2, args);
              break;
            case "skewX":
              skewMatrix(matrix2, args, 2);
              break;
            case "skewY":
              skewMatrix(matrix2, args, 1);
              break;
            case "matrix":
              matrix2 = args;
              break;
          }
          matrices.push(matrix2.concat());
          matrix2 = iMatrix.concat();
        });
        var combinedMatrix = matrices[0];
        while (matrices.length > 1) {
          matrices.shift();
          combinedMatrix = fabric3.util.multiplyTransformMatrices(combinedMatrix, matrices[0]);
        }
        return combinedMatrix;
      };
    }();
    function parseStyleString(style2, oStyle) {
      var attr, value;
      style2.replace(/;\s*$/, "").split(";").forEach(function(chunk) {
        var pair = chunk.split(":");
        attr = pair[0].trim().toLowerCase();
        value = pair[1].trim();
        oStyle[attr] = value;
      });
    }
    function parseStyleObject(style2, oStyle) {
      var attr, value;
      for (var prop in style2) {
        if (typeof style2[prop] === "undefined") {
          continue;
        }
        attr = prop.toLowerCase();
        value = style2[prop];
        oStyle[attr] = value;
      }
    }
    function getGlobalStylesForElement(element, svgUid) {
      var styles = {};
      for (var rule in fabric3.cssRules[svgUid]) {
        if (elementMatchesRule(element, rule.split(" "))) {
          for (var property in fabric3.cssRules[svgUid][rule]) {
            styles[property] = fabric3.cssRules[svgUid][rule][property];
          }
        }
      }
      return styles;
    }
    function elementMatchesRule(element, selectors) {
      var firstMatching, parentMatching = true;
      firstMatching = selectorMatches(element, selectors.pop());
      if (firstMatching && selectors.length) {
        parentMatching = doesSomeParentMatch(element, selectors);
      }
      return firstMatching && parentMatching && selectors.length === 0;
    }
    function doesSomeParentMatch(element, selectors) {
      var selector, parentMatching = true;
      while (element.parentNode && element.parentNode.nodeType === 1 && selectors.length) {
        if (parentMatching) {
          selector = selectors.pop();
        }
        element = element.parentNode;
        parentMatching = selectorMatches(element, selector);
      }
      return selectors.length === 0;
    }
    function selectorMatches(element, selector) {
      var nodeName = element.nodeName, classNames = element.getAttribute("class"), id2 = element.getAttribute("id"), matcher, i2;
      matcher = new RegExp("^" + nodeName, "i");
      selector = selector.replace(matcher, "");
      if (id2 && selector.length) {
        matcher = new RegExp("#" + id2 + "(?![a-zA-Z\\-]+)", "i");
        selector = selector.replace(matcher, "");
      }
      if (classNames && selector.length) {
        classNames = classNames.split(" ");
        for (i2 = classNames.length; i2--; ) {
          matcher = new RegExp("\\." + classNames[i2] + "(?![a-zA-Z\\-]+)", "i");
          selector = selector.replace(matcher, "");
        }
      }
      return selector.length === 0;
    }
    function elementById(doc, id2) {
      var el;
      doc.getElementById && (el = doc.getElementById(id2));
      if (el) {
        return el;
      }
      var node, i2, len, nodelist = doc.getElementsByTagName("*");
      for (i2 = 0, len = nodelist.length; i2 < len; i2++) {
        node = nodelist[i2];
        if (id2 === node.getAttribute("id")) {
          return node;
        }
      }
    }
    function parseUseDirectives(doc) {
      var nodelist = _getMultipleNodes(doc, ["use", "svg:use"]), i2 = 0;
      while (nodelist.length && i2 < nodelist.length) {
        var el = nodelist[i2], xlinkAttribute = el.getAttribute("xlink:href") || el.getAttribute("href");
        if (xlinkAttribute === null) {
          return;
        }
        var xlink = xlinkAttribute.substr(1), x2 = el.getAttribute("x") || 0, y2 = el.getAttribute("y") || 0, el2 = elementById(doc, xlink).cloneNode(true), currentTrans = (el2.getAttribute("transform") || "") + " translate(" + x2 + ", " + y2 + ")", parentNode, oldLength = nodelist.length, attr, j2, attrs, len, namespace = fabric3.svgNS;
        applyViewboxTransform(el2);
        if (/^svg$/i.test(el2.nodeName)) {
          var el3 = el2.ownerDocument.createElementNS(namespace, "g");
          for (j2 = 0, attrs = el2.attributes, len = attrs.length; j2 < len; j2++) {
            attr = attrs.item(j2);
            el3.setAttributeNS(namespace, attr.nodeName, attr.nodeValue);
          }
          while (el2.firstChild) {
            el3.appendChild(el2.firstChild);
          }
          el2 = el3;
        }
        for (j2 = 0, attrs = el.attributes, len = attrs.length; j2 < len; j2++) {
          attr = attrs.item(j2);
          if (attr.nodeName === "x" || attr.nodeName === "y" || attr.nodeName === "xlink:href" || attr.nodeName === "href") {
            continue;
          }
          if (attr.nodeName === "transform") {
            currentTrans = attr.nodeValue + " " + currentTrans;
          } else {
            el2.setAttribute(attr.nodeName, attr.nodeValue);
          }
        }
        el2.setAttribute("transform", currentTrans);
        el2.setAttribute("instantiated_by_use", "1");
        el2.removeAttribute("id");
        parentNode = el.parentNode;
        parentNode.replaceChild(el2, el);
        if (nodelist.length === oldLength) {
          i2++;
        }
      }
    }
    var reViewBoxAttrValue = new RegExp("^\\s*(" + fabric3.reNum + "+)\\s*,?\\s*(" + fabric3.reNum + "+)\\s*,?\\s*(" + fabric3.reNum + "+)\\s*,?\\s*(" + fabric3.reNum + "+)\\s*$");
    function applyViewboxTransform(element) {
      if (!fabric3.svgViewBoxElementsRegEx.test(element.nodeName)) {
        return {};
      }
      var viewBoxAttr = element.getAttribute("viewBox"), scaleX = 1, scaleY = 1, minX = 0, minY = 0, viewBoxWidth, viewBoxHeight, matrix, el, widthAttr = element.getAttribute("width"), heightAttr = element.getAttribute("height"), x2 = element.getAttribute("x") || 0, y2 = element.getAttribute("y") || 0, preserveAspectRatio = element.getAttribute("preserveAspectRatio") || "", missingViewBox = !viewBoxAttr || !(viewBoxAttr = viewBoxAttr.match(reViewBoxAttrValue)), missingDimAttr = !widthAttr || !heightAttr || widthAttr === "100%" || heightAttr === "100%", toBeParsed = missingViewBox && missingDimAttr, parsedDim = {}, translateMatrix = "", widthDiff = 0, heightDiff = 0;
      parsedDim.width = 0;
      parsedDim.height = 0;
      parsedDim.toBeParsed = toBeParsed;
      if (missingViewBox) {
        if ((x2 || y2) && element.parentNode && element.parentNode.nodeName !== "#document") {
          translateMatrix = " translate(" + parseUnit(x2) + " " + parseUnit(y2) + ") ";
          matrix = (element.getAttribute("transform") || "") + translateMatrix;
          element.setAttribute("transform", matrix);
          element.removeAttribute("x");
          element.removeAttribute("y");
        }
      }
      if (toBeParsed) {
        return parsedDim;
      }
      if (missingViewBox) {
        parsedDim.width = parseUnit(widthAttr);
        parsedDim.height = parseUnit(heightAttr);
        return parsedDim;
      }
      minX = -parseFloat(viewBoxAttr[1]);
      minY = -parseFloat(viewBoxAttr[2]);
      viewBoxWidth = parseFloat(viewBoxAttr[3]);
      viewBoxHeight = parseFloat(viewBoxAttr[4]);
      parsedDim.minX = minX;
      parsedDim.minY = minY;
      parsedDim.viewBoxWidth = viewBoxWidth;
      parsedDim.viewBoxHeight = viewBoxHeight;
      if (!missingDimAttr) {
        parsedDim.width = parseUnit(widthAttr);
        parsedDim.height = parseUnit(heightAttr);
        scaleX = parsedDim.width / viewBoxWidth;
        scaleY = parsedDim.height / viewBoxHeight;
      } else {
        parsedDim.width = viewBoxWidth;
        parsedDim.height = viewBoxHeight;
      }
      preserveAspectRatio = fabric3.util.parsePreserveAspectRatioAttribute(preserveAspectRatio);
      if (preserveAspectRatio.alignX !== "none") {
        if (preserveAspectRatio.meetOrSlice === "meet") {
          scaleY = scaleX = scaleX > scaleY ? scaleY : scaleX;
        }
        if (preserveAspectRatio.meetOrSlice === "slice") {
          scaleY = scaleX = scaleX > scaleY ? scaleX : scaleY;
        }
        widthDiff = parsedDim.width - viewBoxWidth * scaleX;
        heightDiff = parsedDim.height - viewBoxHeight * scaleX;
        if (preserveAspectRatio.alignX === "Mid") {
          widthDiff /= 2;
        }
        if (preserveAspectRatio.alignY === "Mid") {
          heightDiff /= 2;
        }
        if (preserveAspectRatio.alignX === "Min") {
          widthDiff = 0;
        }
        if (preserveAspectRatio.alignY === "Min") {
          heightDiff = 0;
        }
      }
      if (scaleX === 1 && scaleY === 1 && minX === 0 && minY === 0 && x2 === 0 && y2 === 0) {
        return parsedDim;
      }
      if ((x2 || y2) && element.parentNode.nodeName !== "#document") {
        translateMatrix = " translate(" + parseUnit(x2) + " " + parseUnit(y2) + ") ";
      }
      matrix = translateMatrix + " matrix(" + scaleX + " 0 0 " + scaleY + " " + (minX * scaleX + widthDiff) + " " + (minY * scaleY + heightDiff) + ") ";
      if (element.nodeName === "svg") {
        el = element.ownerDocument.createElementNS(fabric3.svgNS, "g");
        while (element.firstChild) {
          el.appendChild(element.firstChild);
        }
        element.appendChild(el);
      } else {
        el = element;
        el.removeAttribute("x");
        el.removeAttribute("y");
        matrix = el.getAttribute("transform") + matrix;
      }
      el.setAttribute("transform", matrix);
      return parsedDim;
    }
    function hasAncestorWithNodeName(element, nodeName) {
      while (element && (element = element.parentNode)) {
        if (element.nodeName && nodeName.test(element.nodeName.replace("svg:", "")) && !element.getAttribute("instantiated_by_use")) {
          return true;
        }
      }
      return false;
    }
    fabric3.parseSVGDocument = function(doc, callback, reviver, parsingOptions) {
      if (!doc) {
        return;
      }
      parseUseDirectives(doc);
      var svgUid = fabric3.Object.__uid++, i2, len, options = applyViewboxTransform(doc), descendants = fabric3.util.toArray(doc.getElementsByTagName("*"));
      options.crossOrigin = parsingOptions && parsingOptions.crossOrigin;
      options.svgUid = svgUid;
      if (descendants.length === 0 && fabric3.isLikelyNode) {
        descendants = doc.selectNodes('//*[name(.)!="svg"]');
        var arr = [];
        for (i2 = 0, len = descendants.length; i2 < len; i2++) {
          arr[i2] = descendants[i2];
        }
        descendants = arr;
      }
      var elements = descendants.filter(function(el) {
        applyViewboxTransform(el);
        return fabric3.svgValidTagNamesRegEx.test(el.nodeName.replace("svg:", "")) && !hasAncestorWithNodeName(el, fabric3.svgInvalidAncestorsRegEx);
      });
      if (!elements || elements && !elements.length) {
        callback && callback([], {});
        return;
      }
      var clipPaths = {};
      descendants.filter(function(el) {
        return el.nodeName.replace("svg:", "") === "clipPath";
      }).forEach(function(el) {
        var id2 = el.getAttribute("id");
        clipPaths[id2] = fabric3.util.toArray(el.getElementsByTagName("*")).filter(function(el2) {
          return fabric3.svgValidTagNamesRegEx.test(el2.nodeName.replace("svg:", ""));
        });
      });
      fabric3.gradientDefs[svgUid] = fabric3.getGradientDefs(doc);
      fabric3.cssRules[svgUid] = fabric3.getCSSRules(doc);
      fabric3.clipPaths[svgUid] = clipPaths;
      fabric3.parseElements(elements, function(instances, elements2) {
        if (callback) {
          callback(instances, options, elements2, descendants);
          delete fabric3.gradientDefs[svgUid];
          delete fabric3.cssRules[svgUid];
          delete fabric3.clipPaths[svgUid];
        }
      }, clone(options), reviver, parsingOptions);
    };
    function recursivelyParseGradientsXlink(doc, gradient) {
      var gradientsAttrs = ["gradientTransform", "x1", "x2", "y1", "y2", "gradientUnits", "cx", "cy", "r", "fx", "fy"], xlinkAttr = "xlink:href", xLink = gradient.getAttribute(xlinkAttr).substr(1), referencedGradient = elementById(doc, xLink);
      if (referencedGradient && referencedGradient.getAttribute(xlinkAttr)) {
        recursivelyParseGradientsXlink(doc, referencedGradient);
      }
      gradientsAttrs.forEach(function(attr) {
        if (referencedGradient && !gradient.hasAttribute(attr) && referencedGradient.hasAttribute(attr)) {
          gradient.setAttribute(attr, referencedGradient.getAttribute(attr));
        }
      });
      if (!gradient.children.length) {
        var referenceClone = referencedGradient.cloneNode(true);
        while (referenceClone.firstChild) {
          gradient.appendChild(referenceClone.firstChild);
        }
      }
      gradient.removeAttribute(xlinkAttr);
    }
    var reFontDeclaration = new RegExp("(normal|italic)?\\s*(normal|small-caps)?\\s*(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*(" + fabric3.reNum + "(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|" + fabric3.reNum + "))?\\s+(.*)");
    extend(fabric3, {
      parseFontDeclaration: function(value, oStyle) {
        var match = value.match(reFontDeclaration);
        if (!match) {
          return;
        }
        var fontStyle = match[1], fontWeight = match[3], fontSize = match[4], lineHeight = match[5], fontFamily = match[6];
        if (fontStyle) {
          oStyle.fontStyle = fontStyle;
        }
        if (fontWeight) {
          oStyle.fontWeight = isNaN(parseFloat(fontWeight)) ? fontWeight : parseFloat(fontWeight);
        }
        if (fontSize) {
          oStyle.fontSize = parseUnit(fontSize);
        }
        if (fontFamily) {
          oStyle.fontFamily = fontFamily;
        }
        if (lineHeight) {
          oStyle.lineHeight = lineHeight === "normal" ? 1 : lineHeight;
        }
      },
      getGradientDefs: function(doc) {
        var tagArray = [
          "linearGradient",
          "radialGradient",
          "svg:linearGradient",
          "svg:radialGradient"
        ], elList = _getMultipleNodes(doc, tagArray), el, j2 = 0, gradientDefs = {};
        j2 = elList.length;
        while (j2--) {
          el = elList[j2];
          if (el.getAttribute("xlink:href")) {
            recursivelyParseGradientsXlink(doc, el);
          }
          gradientDefs[el.getAttribute("id")] = el;
        }
        return gradientDefs;
      },
      parseAttributes: function(element, attributes, svgUid) {
        if (!element) {
          return;
        }
        var value, parentAttributes = {}, fontSize, parentFontSize;
        if (typeof svgUid === "undefined") {
          svgUid = element.getAttribute("svgUid");
        }
        if (element.parentNode && fabric3.svgValidParentsRegEx.test(element.parentNode.nodeName)) {
          parentAttributes = fabric3.parseAttributes(element.parentNode, attributes, svgUid);
        }
        var ownAttributes = attributes.reduce(function(memo, attr2) {
          value = element.getAttribute(attr2);
          if (value) {
            memo[attr2] = value;
          }
          return memo;
        }, {});
        var cssAttrs = extend(getGlobalStylesForElement(element, svgUid), fabric3.parseStyleAttribute(element));
        ownAttributes = extend(ownAttributes, cssAttrs);
        if (cssAttrs[cPath]) {
          element.setAttribute(cPath, cssAttrs[cPath]);
        }
        fontSize = parentFontSize = parentAttributes.fontSize || fabric3.Text.DEFAULT_SVG_FONT_SIZE;
        if (ownAttributes[fSize]) {
          ownAttributes[fSize] = fontSize = parseUnit(ownAttributes[fSize], parentFontSize);
        }
        var normalizedAttr, normalizedValue, normalizedStyle = {};
        for (var attr in ownAttributes) {
          normalizedAttr = normalizeAttr(attr);
          normalizedValue = normalizeValue2(normalizedAttr, ownAttributes[attr], parentAttributes, fontSize);
          normalizedStyle[normalizedAttr] = normalizedValue;
        }
        if (normalizedStyle && normalizedStyle.font) {
          fabric3.parseFontDeclaration(normalizedStyle.font, normalizedStyle);
        }
        var mergedAttrs = extend(parentAttributes, normalizedStyle);
        return fabric3.svgValidParentsRegEx.test(element.nodeName) ? mergedAttrs : _setStrokeFillOpacity(mergedAttrs);
      },
      parseElements: function(elements, callback, options, reviver, parsingOptions) {
        new fabric3.ElementsParser(elements, callback, options, reviver, parsingOptions).parse();
      },
      parseStyleAttribute: function(element) {
        var oStyle = {}, style2 = element.getAttribute("style");
        if (!style2) {
          return oStyle;
        }
        if (typeof style2 === "string") {
          parseStyleString(style2, oStyle);
        } else {
          parseStyleObject(style2, oStyle);
        }
        return oStyle;
      },
      parsePointsAttribute: function(points) {
        if (!points) {
          return null;
        }
        points = points.replace(/,/g, " ").trim();
        points = points.split(/\s+/);
        var parsedPoints = [], i2, len;
        for (i2 = 0, len = points.length; i2 < len; i2 += 2) {
          parsedPoints.push({
            x: parseFloat(points[i2]),
            y: parseFloat(points[i2 + 1])
          });
        }
        return parsedPoints;
      },
      getCSSRules: function(doc) {
        var styles = doc.getElementsByTagName("style"), i2, len, allRules = {}, rules;
        for (i2 = 0, len = styles.length; i2 < len; i2++) {
          var styleContents = styles[i2].textContent;
          styleContents = styleContents.replace(/\/\*[\s\S]*?\*\//g, "");
          if (styleContents.trim() === "") {
            continue;
          }
          rules = styleContents.match(/[^{]*\{[\s\S]*?\}/g);
          rules = rules.map(function(rule) {
            return rule.trim();
          });
          rules.forEach(function(rule) {
            var match = rule.match(/([\s\S]*?)\s*\{([^}]*)\}/), ruleObj = {}, declaration = match[2].trim(), propertyValuePairs = declaration.replace(/;$/, "").split(/\s*;\s*/);
            for (i2 = 0, len = propertyValuePairs.length; i2 < len; i2++) {
              var pair = propertyValuePairs[i2].split(/\s*:\s*/), property = pair[0], value = pair[1];
              ruleObj[property] = value;
            }
            rule = match[1];
            rule.split(",").forEach(function(_rule) {
              _rule = _rule.replace(/^svg/i, "").trim();
              if (_rule === "") {
                return;
              }
              if (allRules[_rule]) {
                fabric3.util.object.extend(allRules[_rule], ruleObj);
              } else {
                allRules[_rule] = fabric3.util.object.clone(ruleObj);
              }
            });
          });
        }
        return allRules;
      },
      loadSVGFromURL: function(url, callback, reviver, options) {
        url = url.replace(/^\n\s*/, "").trim();
        new fabric3.util.request(url, {
          method: "get",
          onComplete
        });
        function onComplete(r2) {
          var xml = r2.responseXML;
          if (!xml || !xml.documentElement) {
            callback && callback(null);
            return false;
          }
          fabric3.parseSVGDocument(xml.documentElement, function(results, _options, elements, allElements) {
            callback && callback(results, _options, elements, allElements);
          }, reviver, options);
        }
      },
      loadSVGFromString: function(string, callback, reviver, options) {
        var parser = new fabric3.window.DOMParser(), doc = parser.parseFromString(string.trim(), "text/xml");
        fabric3.parseSVGDocument(doc.documentElement, function(results, _options, elements, allElements) {
          callback(results, _options, elements, allElements);
        }, reviver, options);
      }
    });
  })(exports2);
  fabric2.ElementsParser = function(elements, callback, options, reviver, parsingOptions, doc) {
    this.elements = elements;
    this.callback = callback;
    this.options = options;
    this.reviver = reviver;
    this.svgUid = options && options.svgUid || 0;
    this.parsingOptions = parsingOptions;
    this.regexUrl = /^url\(['"]?#([^'"]+)['"]?\)/g;
    this.doc = doc;
  };
  (function(proto) {
    proto.parse = function() {
      this.instances = new Array(this.elements.length);
      this.numElements = this.elements.length;
      this.createObjects();
    };
    proto.createObjects = function() {
      var _this = this;
      this.elements.forEach(function(element, i2) {
        element.setAttribute("svgUid", _this.svgUid);
        _this.createObject(element, i2);
      });
    };
    proto.findTag = function(el) {
      return fabric2[fabric2.util.string.capitalize(el.tagName.replace("svg:", ""))];
    };
    proto.createObject = function(el, index2) {
      var klass = this.findTag(el);
      if (klass && klass.fromElement) {
        try {
          klass.fromElement(el, this.createCallback(index2, el), this.options);
        } catch (err) {
          fabric2.log(err);
        }
      } else {
        this.checkIfDone();
      }
    };
    proto.createCallback = function(index2, el) {
      var _this = this;
      return function(obj) {
        var _options;
        _this.resolveGradient(obj, el, "fill");
        _this.resolveGradient(obj, el, "stroke");
        if (obj instanceof fabric2.Image && obj._originalElement) {
          _options = obj.parsePreserveAspectRatioAttribute(el);
        }
        obj._removeTransformMatrix(_options);
        _this.resolveClipPath(obj, el);
        _this.reviver && _this.reviver(el, obj);
        _this.instances[index2] = obj;
        _this.checkIfDone();
      };
    };
    proto.extractPropertyDefinition = function(obj, property, storage) {
      var value = obj[property], regex = this.regexUrl;
      if (!regex.test(value)) {
        return;
      }
      regex.lastIndex = 0;
      var id2 = regex.exec(value)[1];
      regex.lastIndex = 0;
      return fabric2[storage][this.svgUid][id2];
    };
    proto.resolveGradient = function(obj, el, property) {
      var gradientDef = this.extractPropertyDefinition(obj, property, "gradientDefs");
      if (gradientDef) {
        var opacityAttr = el.getAttribute(property + "-opacity");
        var gradient = fabric2.Gradient.fromElement(gradientDef, obj, opacityAttr, this.options);
        obj.set(property, gradient);
      }
    };
    proto.createClipPathCallback = function(obj, container) {
      return function(_newObj) {
        _newObj._removeTransformMatrix();
        _newObj.fillRule = _newObj.clipRule;
        container.push(_newObj);
      };
    };
    proto.resolveClipPath = function(obj, usingElement) {
      var clipPath = this.extractPropertyDefinition(obj, "clipPath", "clipPaths"), element, klass, objTransformInv, container, gTransform, options;
      if (clipPath) {
        container = [];
        objTransformInv = fabric2.util.invertTransform(obj.calcTransformMatrix());
        var clipPathTag = clipPath[0].parentNode;
        var clipPathOwner = usingElement;
        while (clipPathOwner.parentNode && clipPathOwner.getAttribute("clip-path") !== obj.clipPath) {
          clipPathOwner = clipPathOwner.parentNode;
        }
        clipPathOwner.parentNode.appendChild(clipPathTag);
        for (var i2 = 0; i2 < clipPath.length; i2++) {
          element = clipPath[i2];
          klass = this.findTag(element);
          klass.fromElement(element, this.createClipPathCallback(obj, container), this.options);
        }
        if (container.length === 1) {
          clipPath = container[0];
        } else {
          clipPath = new fabric2.Group(container);
        }
        gTransform = fabric2.util.multiplyTransformMatrices(objTransformInv, clipPath.calcTransformMatrix());
        if (clipPath.clipPath) {
          this.resolveClipPath(clipPath, clipPathOwner);
        }
        var options = fabric2.util.qrDecompose(gTransform);
        clipPath.flipX = false;
        clipPath.flipY = false;
        clipPath.set("scaleX", options.scaleX);
        clipPath.set("scaleY", options.scaleY);
        clipPath.angle = options.angle;
        clipPath.skewX = options.skewX;
        clipPath.skewY = 0;
        clipPath.setPositionByOrigin({ x: options.translateX, y: options.translateY }, "center", "center");
        obj.clipPath = clipPath;
      } else {
        delete obj.clipPath;
      }
    };
    proto.checkIfDone = function() {
      if (--this.numElements === 0) {
        this.instances = this.instances.filter(function(el) {
          return el != null;
        });
        this.callback(this.instances, this.elements);
      }
    };
  })(fabric2.ElementsParser.prototype);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {});
    if (fabric3.Point) {
      fabric3.warn("fabric.Point is already defined");
      return;
    }
    fabric3.Point = Point;
    function Point(x2, y2) {
      this.x = x2;
      this.y = y2;
    }
    Point.prototype = {
      type: "point",
      constructor: Point,
      add: function(that) {
        return new Point(this.x + that.x, this.y + that.y);
      },
      addEquals: function(that) {
        this.x += that.x;
        this.y += that.y;
        return this;
      },
      scalarAdd: function(scalar) {
        return new Point(this.x + scalar, this.y + scalar);
      },
      scalarAddEquals: function(scalar) {
        this.x += scalar;
        this.y += scalar;
        return this;
      },
      subtract: function(that) {
        return new Point(this.x - that.x, this.y - that.y);
      },
      subtractEquals: function(that) {
        this.x -= that.x;
        this.y -= that.y;
        return this;
      },
      scalarSubtract: function(scalar) {
        return new Point(this.x - scalar, this.y - scalar);
      },
      scalarSubtractEquals: function(scalar) {
        this.x -= scalar;
        this.y -= scalar;
        return this;
      },
      multiply: function(scalar) {
        return new Point(this.x * scalar, this.y * scalar);
      },
      multiplyEquals: function(scalar) {
        this.x *= scalar;
        this.y *= scalar;
        return this;
      },
      divide: function(scalar) {
        return new Point(this.x / scalar, this.y / scalar);
      },
      divideEquals: function(scalar) {
        this.x /= scalar;
        this.y /= scalar;
        return this;
      },
      eq: function(that) {
        return this.x === that.x && this.y === that.y;
      },
      lt: function(that) {
        return this.x < that.x && this.y < that.y;
      },
      lte: function(that) {
        return this.x <= that.x && this.y <= that.y;
      },
      gt: function(that) {
        return this.x > that.x && this.y > that.y;
      },
      gte: function(that) {
        return this.x >= that.x && this.y >= that.y;
      },
      lerp: function(that, t2) {
        if (typeof t2 === "undefined") {
          t2 = 0.5;
        }
        t2 = Math.max(Math.min(1, t2), 0);
        return new Point(this.x + (that.x - this.x) * t2, this.y + (that.y - this.y) * t2);
      },
      distanceFrom: function(that) {
        var dx = this.x - that.x, dy = this.y - that.y;
        return Math.sqrt(dx * dx + dy * dy);
      },
      midPointFrom: function(that) {
        return this.lerp(that);
      },
      min: function(that) {
        return new Point(Math.min(this.x, that.x), Math.min(this.y, that.y));
      },
      max: function(that) {
        return new Point(Math.max(this.x, that.x), Math.max(this.y, that.y));
      },
      toString: function() {
        return this.x + "," + this.y;
      },
      setXY: function(x2, y2) {
        this.x = x2;
        this.y = y2;
        return this;
      },
      setX: function(x2) {
        this.x = x2;
        return this;
      },
      setY: function(y2) {
        this.y = y2;
        return this;
      },
      setFromPoint: function(that) {
        this.x = that.x;
        this.y = that.y;
        return this;
      },
      swap: function(that) {
        var x2 = this.x, y2 = this.y;
        this.x = that.x;
        this.y = that.y;
        that.x = x2;
        that.y = y2;
      },
      clone: function() {
        return new Point(this.x, this.y);
      }
    };
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {});
    if (fabric3.Intersection) {
      fabric3.warn("fabric.Intersection is already defined");
      return;
    }
    function Intersection(status) {
      this.status = status;
      this.points = [];
    }
    fabric3.Intersection = Intersection;
    fabric3.Intersection.prototype = {
      constructor: Intersection,
      appendPoint: function(point) {
        this.points.push(point);
        return this;
      },
      appendPoints: function(points) {
        this.points = this.points.concat(points);
        return this;
      }
    };
    fabric3.Intersection.intersectLineLine = function(a1, a2, b1, b2) {
      var result, uaT = (b2.x - b1.x) * (a1.y - b1.y) - (b2.y - b1.y) * (a1.x - b1.x), ubT = (a2.x - a1.x) * (a1.y - b1.y) - (a2.y - a1.y) * (a1.x - b1.x), uB = (b2.y - b1.y) * (a2.x - a1.x) - (b2.x - b1.x) * (a2.y - a1.y);
      if (uB !== 0) {
        var ua = uaT / uB, ub = ubT / uB;
        if (0 <= ua && ua <= 1 && 0 <= ub && ub <= 1) {
          result = new Intersection("Intersection");
          result.appendPoint(new fabric3.Point(a1.x + ua * (a2.x - a1.x), a1.y + ua * (a2.y - a1.y)));
        } else {
          result = new Intersection();
        }
      } else {
        if (uaT === 0 || ubT === 0) {
          result = new Intersection("Coincident");
        } else {
          result = new Intersection("Parallel");
        }
      }
      return result;
    };
    fabric3.Intersection.intersectLinePolygon = function(a1, a2, points) {
      var result = new Intersection(), length = points.length, b1, b2, inter, i2;
      for (i2 = 0; i2 < length; i2++) {
        b1 = points[i2];
        b2 = points[(i2 + 1) % length];
        inter = Intersection.intersectLineLine(a1, a2, b1, b2);
        result.appendPoints(inter.points);
      }
      if (result.points.length > 0) {
        result.status = "Intersection";
      }
      return result;
    };
    fabric3.Intersection.intersectPolygonPolygon = function(points1, points2) {
      var result = new Intersection(), length = points1.length, i2;
      for (i2 = 0; i2 < length; i2++) {
        var a1 = points1[i2], a2 = points1[(i2 + 1) % length], inter = Intersection.intersectLinePolygon(a1, a2, points2);
        result.appendPoints(inter.points);
      }
      if (result.points.length > 0) {
        result.status = "Intersection";
      }
      return result;
    };
    fabric3.Intersection.intersectPolygonRectangle = function(points, r1, r2) {
      var min = r1.min(r2), max = r1.max(r2), topRight = new fabric3.Point(max.x, min.y), bottomLeft = new fabric3.Point(min.x, max.y), inter1 = Intersection.intersectLinePolygon(min, topRight, points), inter2 = Intersection.intersectLinePolygon(topRight, max, points), inter3 = Intersection.intersectLinePolygon(max, bottomLeft, points), inter4 = Intersection.intersectLinePolygon(bottomLeft, min, points), result = new Intersection();
      result.appendPoints(inter1.points);
      result.appendPoints(inter2.points);
      result.appendPoints(inter3.points);
      result.appendPoints(inter4.points);
      if (result.points.length > 0) {
        result.status = "Intersection";
      }
      return result;
    };
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {});
    if (fabric3.Color) {
      fabric3.warn("fabric.Color is already defined.");
      return;
    }
    function Color2(color2) {
      if (!color2) {
        this.setSource([0, 0, 0, 1]);
      } else {
        this._tryParsingColor(color2);
      }
    }
    fabric3.Color = Color2;
    fabric3.Color.prototype = {
      _tryParsingColor: function(color2) {
        var source;
        if (color2 in Color2.colorNameMap) {
          color2 = Color2.colorNameMap[color2];
        }
        if (color2 === "transparent") {
          source = [255, 255, 255, 0];
        }
        if (!source) {
          source = Color2.sourceFromHex(color2);
        }
        if (!source) {
          source = Color2.sourceFromRgb(color2);
        }
        if (!source) {
          source = Color2.sourceFromHsl(color2);
        }
        if (!source) {
          source = [0, 0, 0, 1];
        }
        if (source) {
          this.setSource(source);
        }
      },
      _rgbToHsl: function(r2, g2, b2) {
        r2 /= 255;
        g2 /= 255;
        b2 /= 255;
        var h2, s2, l2, max = fabric3.util.array.max([r2, g2, b2]), min = fabric3.util.array.min([r2, g2, b2]);
        l2 = (max + min) / 2;
        if (max === min) {
          h2 = s2 = 0;
        } else {
          var d2 = max - min;
          s2 = l2 > 0.5 ? d2 / (2 - max - min) : d2 / (max + min);
          switch (max) {
            case r2:
              h2 = (g2 - b2) / d2 + (g2 < b2 ? 6 : 0);
              break;
            case g2:
              h2 = (b2 - r2) / d2 + 2;
              break;
            case b2:
              h2 = (r2 - g2) / d2 + 4;
              break;
          }
          h2 /= 6;
        }
        return [
          Math.round(h2 * 360),
          Math.round(s2 * 100),
          Math.round(l2 * 100)
        ];
      },
      getSource: function() {
        return this._source;
      },
      setSource: function(source) {
        this._source = source;
      },
      toRgb: function() {
        var source = this.getSource();
        return "rgb(" + source[0] + "," + source[1] + "," + source[2] + ")";
      },
      toRgba: function() {
        var source = this.getSource();
        return "rgba(" + source[0] + "," + source[1] + "," + source[2] + "," + source[3] + ")";
      },
      toHsl: function() {
        var source = this.getSource(), hsl = this._rgbToHsl(source[0], source[1], source[2]);
        return "hsl(" + hsl[0] + "," + hsl[1] + "%," + hsl[2] + "%)";
      },
      toHsla: function() {
        var source = this.getSource(), hsl = this._rgbToHsl(source[0], source[1], source[2]);
        return "hsla(" + hsl[0] + "," + hsl[1] + "%," + hsl[2] + "%," + source[3] + ")";
      },
      toHex: function() {
        var source = this.getSource(), r2, g2, b2;
        r2 = source[0].toString(16);
        r2 = r2.length === 1 ? "0" + r2 : r2;
        g2 = source[1].toString(16);
        g2 = g2.length === 1 ? "0" + g2 : g2;
        b2 = source[2].toString(16);
        b2 = b2.length === 1 ? "0" + b2 : b2;
        return r2.toUpperCase() + g2.toUpperCase() + b2.toUpperCase();
      },
      toHexa: function() {
        var source = this.getSource(), a2;
        a2 = Math.round(source[3] * 255);
        a2 = a2.toString(16);
        a2 = a2.length === 1 ? "0" + a2 : a2;
        return this.toHex() + a2.toUpperCase();
      },
      getAlpha: function() {
        return this.getSource()[3];
      },
      setAlpha: function(alpha2) {
        var source = this.getSource();
        source[3] = alpha2;
        this.setSource(source);
        return this;
      },
      toGrayscale: function() {
        var source = this.getSource(), average = parseInt((source[0] * 0.3 + source[1] * 0.59 + source[2] * 0.11).toFixed(0), 10), currentAlpha = source[3];
        this.setSource([average, average, average, currentAlpha]);
        return this;
      },
      toBlackWhite: function(threshold) {
        var source = this.getSource(), average = (source[0] * 0.3 + source[1] * 0.59 + source[2] * 0.11).toFixed(0), currentAlpha = source[3];
        threshold = threshold || 127;
        average = Number(average) < Number(threshold) ? 0 : 255;
        this.setSource([average, average, average, currentAlpha]);
        return this;
      },
      overlayWith: function(otherColor) {
        if (!(otherColor instanceof Color2)) {
          otherColor = new Color2(otherColor);
        }
        var result = [], alpha2 = this.getAlpha(), otherAlpha = 0.5, source = this.getSource(), otherSource = otherColor.getSource(), i2;
        for (i2 = 0; i2 < 3; i2++) {
          result.push(Math.round(source[i2] * (1 - otherAlpha) + otherSource[i2] * otherAlpha));
        }
        result[3] = alpha2;
        this.setSource(result);
        return this;
      }
    };
    fabric3.Color.reRGBa = /^rgba?\(\s*(\d{1,3}(?:\.\d+)?\%?)\s*,\s*(\d{1,3}(?:\.\d+)?\%?)\s*,\s*(\d{1,3}(?:\.\d+)?\%?)\s*(?:\s*,\s*((?:\d*\.?\d+)?)\s*)?\)$/i;
    fabric3.Color.reHSLa = /^hsla?\(\s*(\d{1,3})\s*,\s*(\d{1,3}\%)\s*,\s*(\d{1,3}\%)\s*(?:\s*,\s*(\d+(?:\.\d+)?)\s*)?\)$/i;
    fabric3.Color.reHex = /^#?([0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{4}|[0-9a-f]{3})$/i;
    fabric3.Color.colorNameMap = {
      aliceblue: "#F0F8FF",
      antiquewhite: "#FAEBD7",
      aqua: "#00FFFF",
      aquamarine: "#7FFFD4",
      azure: "#F0FFFF",
      beige: "#F5F5DC",
      bisque: "#FFE4C4",
      black: "#000000",
      blanchedalmond: "#FFEBCD",
      blue: "#0000FF",
      blueviolet: "#8A2BE2",
      brown: "#A52A2A",
      burlywood: "#DEB887",
      cadetblue: "#5F9EA0",
      chartreuse: "#7FFF00",
      chocolate: "#D2691E",
      coral: "#FF7F50",
      cornflowerblue: "#6495ED",
      cornsilk: "#FFF8DC",
      crimson: "#DC143C",
      cyan: "#00FFFF",
      darkblue: "#00008B",
      darkcyan: "#008B8B",
      darkgoldenrod: "#B8860B",
      darkgray: "#A9A9A9",
      darkgrey: "#A9A9A9",
      darkgreen: "#006400",
      darkkhaki: "#BDB76B",
      darkmagenta: "#8B008B",
      darkolivegreen: "#556B2F",
      darkorange: "#FF8C00",
      darkorchid: "#9932CC",
      darkred: "#8B0000",
      darksalmon: "#E9967A",
      darkseagreen: "#8FBC8F",
      darkslateblue: "#483D8B",
      darkslategray: "#2F4F4F",
      darkslategrey: "#2F4F4F",
      darkturquoise: "#00CED1",
      darkviolet: "#9400D3",
      deeppink: "#FF1493",
      deepskyblue: "#00BFFF",
      dimgray: "#696969",
      dimgrey: "#696969",
      dodgerblue: "#1E90FF",
      firebrick: "#B22222",
      floralwhite: "#FFFAF0",
      forestgreen: "#228B22",
      fuchsia: "#FF00FF",
      gainsboro: "#DCDCDC",
      ghostwhite: "#F8F8FF",
      gold: "#FFD700",
      goldenrod: "#DAA520",
      gray: "#808080",
      grey: "#808080",
      green: "#008000",
      greenyellow: "#ADFF2F",
      honeydew: "#F0FFF0",
      hotpink: "#FF69B4",
      indianred: "#CD5C5C",
      indigo: "#4B0082",
      ivory: "#FFFFF0",
      khaki: "#F0E68C",
      lavender: "#E6E6FA",
      lavenderblush: "#FFF0F5",
      lawngreen: "#7CFC00",
      lemonchiffon: "#FFFACD",
      lightblue: "#ADD8E6",
      lightcoral: "#F08080",
      lightcyan: "#E0FFFF",
      lightgoldenrodyellow: "#FAFAD2",
      lightgray: "#D3D3D3",
      lightgrey: "#D3D3D3",
      lightgreen: "#90EE90",
      lightpink: "#FFB6C1",
      lightsalmon: "#FFA07A",
      lightseagreen: "#20B2AA",
      lightskyblue: "#87CEFA",
      lightslategray: "#778899",
      lightslategrey: "#778899",
      lightsteelblue: "#B0C4DE",
      lightyellow: "#FFFFE0",
      lime: "#00FF00",
      limegreen: "#32CD32",
      linen: "#FAF0E6",
      magenta: "#FF00FF",
      maroon: "#800000",
      mediumaquamarine: "#66CDAA",
      mediumblue: "#0000CD",
      mediumorchid: "#BA55D3",
      mediumpurple: "#9370DB",
      mediumseagreen: "#3CB371",
      mediumslateblue: "#7B68EE",
      mediumspringgreen: "#00FA9A",
      mediumturquoise: "#48D1CC",
      mediumvioletred: "#C71585",
      midnightblue: "#191970",
      mintcream: "#F5FFFA",
      mistyrose: "#FFE4E1",
      moccasin: "#FFE4B5",
      navajowhite: "#FFDEAD",
      navy: "#000080",
      oldlace: "#FDF5E6",
      olive: "#808000",
      olivedrab: "#6B8E23",
      orange: "#FFA500",
      orangered: "#FF4500",
      orchid: "#DA70D6",
      palegoldenrod: "#EEE8AA",
      palegreen: "#98FB98",
      paleturquoise: "#AFEEEE",
      palevioletred: "#DB7093",
      papayawhip: "#FFEFD5",
      peachpuff: "#FFDAB9",
      peru: "#CD853F",
      pink: "#FFC0CB",
      plum: "#DDA0DD",
      powderblue: "#B0E0E6",
      purple: "#800080",
      rebeccapurple: "#663399",
      red: "#FF0000",
      rosybrown: "#BC8F8F",
      royalblue: "#4169E1",
      saddlebrown: "#8B4513",
      salmon: "#FA8072",
      sandybrown: "#F4A460",
      seagreen: "#2E8B57",
      seashell: "#FFF5EE",
      sienna: "#A0522D",
      silver: "#C0C0C0",
      skyblue: "#87CEEB",
      slateblue: "#6A5ACD",
      slategray: "#708090",
      slategrey: "#708090",
      snow: "#FFFAFA",
      springgreen: "#00FF7F",
      steelblue: "#4682B4",
      tan: "#D2B48C",
      teal: "#008080",
      thistle: "#D8BFD8",
      tomato: "#FF6347",
      turquoise: "#40E0D0",
      violet: "#EE82EE",
      wheat: "#F5DEB3",
      white: "#FFFFFF",
      whitesmoke: "#F5F5F5",
      yellow: "#FFFF00",
      yellowgreen: "#9ACD32"
    };
    function hue2rgb(p2, q2, t2) {
      if (t2 < 0) {
        t2 += 1;
      }
      if (t2 > 1) {
        t2 -= 1;
      }
      if (t2 < 1 / 6) {
        return p2 + (q2 - p2) * 6 * t2;
      }
      if (t2 < 1 / 2) {
        return q2;
      }
      if (t2 < 2 / 3) {
        return p2 + (q2 - p2) * (2 / 3 - t2) * 6;
      }
      return p2;
    }
    fabric3.Color.fromRgb = function(color2) {
      return Color2.fromSource(Color2.sourceFromRgb(color2));
    };
    fabric3.Color.sourceFromRgb = function(color2) {
      var match = color2.match(Color2.reRGBa);
      if (match) {
        var r2 = parseInt(match[1], 10) / (/%$/.test(match[1]) ? 100 : 1) * (/%$/.test(match[1]) ? 255 : 1), g2 = parseInt(match[2], 10) / (/%$/.test(match[2]) ? 100 : 1) * (/%$/.test(match[2]) ? 255 : 1), b2 = parseInt(match[3], 10) / (/%$/.test(match[3]) ? 100 : 1) * (/%$/.test(match[3]) ? 255 : 1);
        return [
          parseInt(r2, 10),
          parseInt(g2, 10),
          parseInt(b2, 10),
          match[4] ? parseFloat(match[4]) : 1
        ];
      }
    };
    fabric3.Color.fromRgba = Color2.fromRgb;
    fabric3.Color.fromHsl = function(color2) {
      return Color2.fromSource(Color2.sourceFromHsl(color2));
    };
    fabric3.Color.sourceFromHsl = function(color2) {
      var match = color2.match(Color2.reHSLa);
      if (!match) {
        return;
      }
      var h2 = (parseFloat(match[1]) % 360 + 360) % 360 / 360, s2 = parseFloat(match[2]) / (/%$/.test(match[2]) ? 100 : 1), l2 = parseFloat(match[3]) / (/%$/.test(match[3]) ? 100 : 1), r2, g2, b2;
      if (s2 === 0) {
        r2 = g2 = b2 = l2;
      } else {
        var q2 = l2 <= 0.5 ? l2 * (s2 + 1) : l2 + s2 - l2 * s2, p2 = l2 * 2 - q2;
        r2 = hue2rgb(p2, q2, h2 + 1 / 3);
        g2 = hue2rgb(p2, q2, h2);
        b2 = hue2rgb(p2, q2, h2 - 1 / 3);
      }
      return [
        Math.round(r2 * 255),
        Math.round(g2 * 255),
        Math.round(b2 * 255),
        match[4] ? parseFloat(match[4]) : 1
      ];
    };
    fabric3.Color.fromHsla = Color2.fromHsl;
    fabric3.Color.fromHex = function(color2) {
      return Color2.fromSource(Color2.sourceFromHex(color2));
    };
    fabric3.Color.sourceFromHex = function(color2) {
      if (color2.match(Color2.reHex)) {
        var value = color2.slice(color2.indexOf("#") + 1), isShortNotation = value.length === 3 || value.length === 4, isRGBa = value.length === 8 || value.length === 4, r2 = isShortNotation ? value.charAt(0) + value.charAt(0) : value.substring(0, 2), g2 = isShortNotation ? value.charAt(1) + value.charAt(1) : value.substring(2, 4), b2 = isShortNotation ? value.charAt(2) + value.charAt(2) : value.substring(4, 6), a2 = isRGBa ? isShortNotation ? value.charAt(3) + value.charAt(3) : value.substring(6, 8) : "FF";
        return [
          parseInt(r2, 16),
          parseInt(g2, 16),
          parseInt(b2, 16),
          parseFloat((parseInt(a2, 16) / 255).toFixed(2))
        ];
      }
    };
    fabric3.Color.fromSource = function(source) {
      var oColor = new Color2();
      oColor.setSource(source);
      return oColor;
    };
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {}), scaleMap = ["e", "se", "s", "sw", "w", "nw", "n", "ne", "e"], skewMap = ["ns", "nesw", "ew", "nwse"], controls2 = {}, LEFT = "left", TOP = "top", RIGHT = "right", BOTTOM = "bottom", CENTER = "center", opposite = {
      top: BOTTOM,
      bottom: TOP,
      left: RIGHT,
      right: LEFT,
      center: CENTER
    }, radiansToDegrees = fabric3.util.radiansToDegrees, sign = Math.sign || function(x2) {
      return (x2 > 0) - (x2 < 0) || +x2;
    };
    function findCornerQuadrant(fabricObject, control) {
      var cornerAngle = fabricObject.angle + radiansToDegrees(Math.atan2(control.y, control.x)) + 360;
      return Math.round(cornerAngle % 360 / 45);
    }
    function fireEvent(eventName, options) {
      var target = options.transform.target, canvas = target.canvas, canvasOptions = fabric3.util.object.clone(options);
      canvasOptions.target = target;
      canvas && canvas.fire("object:" + eventName, canvasOptions);
      target.fire(eventName, options);
    }
    function scaleIsProportional(eventData, fabricObject) {
      var canvas = fabricObject.canvas, uniScaleKey = canvas.uniScaleKey, uniformIsToggled = eventData[uniScaleKey];
      return canvas.uniformScaling && !uniformIsToggled || !canvas.uniformScaling && uniformIsToggled;
    }
    function isTransformCentered(transform2) {
      return transform2.originX === CENTER && transform2.originY === CENTER;
    }
    function scalingIsForbidden(fabricObject, by, scaleProportionally) {
      var lockX = fabricObject.lockScalingX, lockY = fabricObject.lockScalingY;
      if (lockX && lockY) {
        return true;
      }
      if (!by && (lockX || lockY) && scaleProportionally) {
        return true;
      }
      if (lockX && by === "x") {
        return true;
      }
      if (lockY && by === "y") {
        return true;
      }
      return false;
    }
    function scaleCursorStyleHandler(eventData, control, fabricObject) {
      var notAllowed = "not-allowed", scaleProportionally = scaleIsProportional(eventData, fabricObject), by = "";
      if (control.x !== 0 && control.y === 0) {
        by = "x";
      } else if (control.x === 0 && control.y !== 0) {
        by = "y";
      }
      if (scalingIsForbidden(fabricObject, by, scaleProportionally)) {
        return notAllowed;
      }
      var n2 = findCornerQuadrant(fabricObject, control);
      return scaleMap[n2] + "-resize";
    }
    function skewCursorStyleHandler(eventData, control, fabricObject) {
      var notAllowed = "not-allowed";
      if (control.x !== 0 && fabricObject.lockSkewingY) {
        return notAllowed;
      }
      if (control.y !== 0 && fabricObject.lockSkewingX) {
        return notAllowed;
      }
      var n2 = findCornerQuadrant(fabricObject, control) % 4;
      return skewMap[n2] + "-resize";
    }
    function scaleSkewCursorStyleHandler(eventData, control, fabricObject) {
      if (eventData[fabricObject.canvas.altActionKey]) {
        return controls2.skewCursorStyleHandler(eventData, control, fabricObject);
      }
      return controls2.scaleCursorStyleHandler(eventData, control, fabricObject);
    }
    function scaleOrSkewActionName(eventData, control, fabricObject) {
      var isAlternative = eventData[fabricObject.canvas.altActionKey];
      if (control.x === 0) {
        return isAlternative ? "skewX" : "scaleY";
      }
      if (control.y === 0) {
        return isAlternative ? "skewY" : "scaleX";
      }
    }
    function rotationStyleHandler(eventData, control, fabricObject) {
      if (fabricObject.lockRotation) {
        return "not-allowed";
      }
      return control.cursorStyle;
    }
    function commonEventInfo(eventData, transform2, x2, y2) {
      return {
        e: eventData,
        transform: transform2,
        pointer: {
          x: x2,
          y: y2
        }
      };
    }
    function wrapWithFixedAnchor(actionHandler) {
      return function(eventData, transform2, x2, y2) {
        var target = transform2.target, centerPoint = target.getCenterPoint(), constraint = target.translateToOriginPoint(centerPoint, transform2.originX, transform2.originY), actionPerformed = actionHandler(eventData, transform2, x2, y2);
        target.setPositionByOrigin(constraint, transform2.originX, transform2.originY);
        return actionPerformed;
      };
    }
    function wrapWithFireEvent(eventName, actionHandler) {
      return function(eventData, transform2, x2, y2) {
        var actionPerformed = actionHandler(eventData, transform2, x2, y2);
        if (actionPerformed) {
          fireEvent(eventName, commonEventInfo(eventData, transform2, x2, y2));
        }
        return actionPerformed;
      };
    }
    function getLocalPoint(transform2, originX, originY, x2, y2) {
      var target = transform2.target, control = target.controls[transform2.corner], zoom = target.canvas.getZoom(), padding = target.padding / zoom, localPoint = target.toLocalPoint(new fabric3.Point(x2, y2), originX, originY);
      if (localPoint.x >= padding) {
        localPoint.x -= padding;
      }
      if (localPoint.x <= -padding) {
        localPoint.x += padding;
      }
      if (localPoint.y >= padding) {
        localPoint.y -= padding;
      }
      if (localPoint.y <= padding) {
        localPoint.y += padding;
      }
      localPoint.x -= control.offsetX;
      localPoint.y -= control.offsetY;
      return localPoint;
    }
    function targetHasOneFlip(target) {
      return target.flipX !== target.flipY;
    }
    function compensateScaleForSkew(target, oppositeSkew, scaleToCompensate, axis, reference) {
      if (target[oppositeSkew] !== 0) {
        var newDim = target._getTransformedDimensions()[axis];
        var newValue = reference / newDim * target[scaleToCompensate];
        target.set(scaleToCompensate, newValue);
      }
    }
    function skewObjectX(eventData, transform2, x2, y2) {
      var target = transform2.target, dimNoSkew = target._getTransformedDimensions(0, target.skewY), localPoint = getLocalPoint(transform2, transform2.originX, transform2.originY, x2, y2), totalSkewSize = Math.abs(localPoint.x * 2) - dimNoSkew.x, currentSkew = target.skewX, newSkew;
      if (totalSkewSize < 2) {
        newSkew = 0;
      } else {
        newSkew = radiansToDegrees(Math.atan2(totalSkewSize / target.scaleX, dimNoSkew.y / target.scaleY));
        if (transform2.originX === LEFT && transform2.originY === BOTTOM) {
          newSkew = -newSkew;
        }
        if (transform2.originX === RIGHT && transform2.originY === TOP) {
          newSkew = -newSkew;
        }
        if (targetHasOneFlip(target)) {
          newSkew = -newSkew;
        }
      }
      var hasSkewed = currentSkew !== newSkew;
      if (hasSkewed) {
        var dimBeforeSkewing = target._getTransformedDimensions().y;
        target.set("skewX", newSkew);
        compensateScaleForSkew(target, "skewY", "scaleY", "y", dimBeforeSkewing);
      }
      return hasSkewed;
    }
    function skewObjectY(eventData, transform2, x2, y2) {
      var target = transform2.target, dimNoSkew = target._getTransformedDimensions(target.skewX, 0), localPoint = getLocalPoint(transform2, transform2.originX, transform2.originY, x2, y2), totalSkewSize = Math.abs(localPoint.y * 2) - dimNoSkew.y, currentSkew = target.skewY, newSkew;
      if (totalSkewSize < 2) {
        newSkew = 0;
      } else {
        newSkew = radiansToDegrees(Math.atan2(totalSkewSize / target.scaleY, dimNoSkew.x / target.scaleX));
        if (transform2.originX === LEFT && transform2.originY === BOTTOM) {
          newSkew = -newSkew;
        }
        if (transform2.originX === RIGHT && transform2.originY === TOP) {
          newSkew = -newSkew;
        }
        if (targetHasOneFlip(target)) {
          newSkew = -newSkew;
        }
      }
      var hasSkewed = currentSkew !== newSkew;
      if (hasSkewed) {
        var dimBeforeSkewing = target._getTransformedDimensions().x;
        target.set("skewY", newSkew);
        compensateScaleForSkew(target, "skewX", "scaleX", "x", dimBeforeSkewing);
      }
      return hasSkewed;
    }
    function skewHandlerX(eventData, transform2, x2, y2) {
      var target = transform2.target, currentSkew = target.skewX, originX, originY = transform2.originY;
      if (target.lockSkewingX) {
        return false;
      }
      if (currentSkew === 0) {
        var localPointFromCenter = getLocalPoint(transform2, CENTER, CENTER, x2, y2);
        if (localPointFromCenter.x > 0) {
          originX = LEFT;
        } else {
          originX = RIGHT;
        }
      } else {
        if (currentSkew > 0) {
          originX = originY === TOP ? LEFT : RIGHT;
        }
        if (currentSkew < 0) {
          originX = originY === TOP ? RIGHT : LEFT;
        }
        if (targetHasOneFlip(target)) {
          originX = originX === LEFT ? RIGHT : LEFT;
        }
      }
      transform2.originX = originX;
      var finalHandler = wrapWithFireEvent("skewing", wrapWithFixedAnchor(skewObjectX));
      return finalHandler(eventData, transform2, x2, y2);
    }
    function skewHandlerY(eventData, transform2, x2, y2) {
      var target = transform2.target, currentSkew = target.skewY, originY, originX = transform2.originX;
      if (target.lockSkewingY) {
        return false;
      }
      if (currentSkew === 0) {
        var localPointFromCenter = getLocalPoint(transform2, CENTER, CENTER, x2, y2);
        if (localPointFromCenter.y > 0) {
          originY = TOP;
        } else {
          originY = BOTTOM;
        }
      } else {
        if (currentSkew > 0) {
          originY = originX === LEFT ? TOP : BOTTOM;
        }
        if (currentSkew < 0) {
          originY = originX === LEFT ? BOTTOM : TOP;
        }
        if (targetHasOneFlip(target)) {
          originY = originY === TOP ? BOTTOM : TOP;
        }
      }
      transform2.originY = originY;
      var finalHandler = wrapWithFireEvent("skewing", wrapWithFixedAnchor(skewObjectY));
      return finalHandler(eventData, transform2, x2, y2);
    }
    function rotationWithSnapping(eventData, transform2, x2, y2) {
      var t2 = transform2, target = t2.target, pivotPoint = target.translateToOriginPoint(target.getCenterPoint(), t2.originX, t2.originY);
      if (target.lockRotation) {
        return false;
      }
      var lastAngle = Math.atan2(t2.ey - pivotPoint.y, t2.ex - pivotPoint.x), curAngle = Math.atan2(y2 - pivotPoint.y, x2 - pivotPoint.x), angle = radiansToDegrees(curAngle - lastAngle + t2.theta), hasRotated = true;
      if (target.snapAngle > 0) {
        var snapAngle = target.snapAngle, snapThreshold = target.snapThreshold || snapAngle, rightAngleLocked = Math.ceil(angle / snapAngle) * snapAngle, leftAngleLocked = Math.floor(angle / snapAngle) * snapAngle;
        if (Math.abs(angle - leftAngleLocked) < snapThreshold) {
          angle = leftAngleLocked;
        } else if (Math.abs(angle - rightAngleLocked) < snapThreshold) {
          angle = rightAngleLocked;
        }
      }
      if (angle < 0) {
        angle = 360 + angle;
      }
      angle %= 360;
      hasRotated = target.angle !== angle;
      target.angle = angle;
      return hasRotated;
    }
    function scaleObject(eventData, transform2, x2, y2, options) {
      options = options || {};
      var target = transform2.target, lockScalingX = target.lockScalingX, lockScalingY = target.lockScalingY, by = options.by, newPoint, scaleX, scaleY, dim, scaleProportionally = scaleIsProportional(eventData, target), forbidScaling = scalingIsForbidden(target, by, scaleProportionally), signX, signY, gestureScale = transform2.gestureScale;
      if (forbidScaling) {
        return false;
      }
      if (gestureScale) {
        scaleX = transform2.scaleX * gestureScale;
        scaleY = transform2.scaleY * gestureScale;
      } else {
        newPoint = getLocalPoint(transform2, transform2.originX, transform2.originY, x2, y2);
        signX = by !== "y" ? sign(newPoint.x) : 1;
        signY = by !== "x" ? sign(newPoint.y) : 1;
        if (!transform2.signX) {
          transform2.signX = signX;
        }
        if (!transform2.signY) {
          transform2.signY = signY;
        }
        if (target.lockScalingFlip && (transform2.signX !== signX || transform2.signY !== signY)) {
          return false;
        }
        dim = target._getTransformedDimensions();
        if (scaleProportionally && !by) {
          var distance = Math.abs(newPoint.x) + Math.abs(newPoint.y), original = transform2.original, originalDistance = Math.abs(dim.x * original.scaleX / target.scaleX) + Math.abs(dim.y * original.scaleY / target.scaleY), scale2 = distance / originalDistance;
          scaleX = original.scaleX * scale2;
          scaleY = original.scaleY * scale2;
        } else {
          scaleX = Math.abs(newPoint.x * target.scaleX / dim.x);
          scaleY = Math.abs(newPoint.y * target.scaleY / dim.y);
        }
        if (isTransformCentered(transform2)) {
          scaleX *= 2;
          scaleY *= 2;
        }
        if (transform2.signX !== signX && by !== "y") {
          transform2.originX = opposite[transform2.originX];
          scaleX *= -1;
          transform2.signX = signX;
        }
        if (transform2.signY !== signY && by !== "x") {
          transform2.originY = opposite[transform2.originY];
          scaleY *= -1;
          transform2.signY = signY;
        }
      }
      var oldScaleX = target.scaleX, oldScaleY = target.scaleY;
      if (!by) {
        !lockScalingX && target.set("scaleX", scaleX);
        !lockScalingY && target.set("scaleY", scaleY);
      } else {
        by === "x" && target.set("scaleX", scaleX);
        by === "y" && target.set("scaleY", scaleY);
      }
      return oldScaleX !== target.scaleX || oldScaleY !== target.scaleY;
    }
    function scaleObjectFromCorner(eventData, transform2, x2, y2) {
      return scaleObject(eventData, transform2, x2, y2);
    }
    function scaleObjectX(eventData, transform2, x2, y2) {
      return scaleObject(eventData, transform2, x2, y2, { by: "x" });
    }
    function scaleObjectY(eventData, transform2, x2, y2) {
      return scaleObject(eventData, transform2, x2, y2, { by: "y" });
    }
    function scalingYOrSkewingX(eventData, transform2, x2, y2) {
      if (eventData[transform2.target.canvas.altActionKey]) {
        return controls2.skewHandlerX(eventData, transform2, x2, y2);
      }
      return controls2.scalingY(eventData, transform2, x2, y2);
    }
    function scalingXOrSkewingY(eventData, transform2, x2, y2) {
      if (eventData[transform2.target.canvas.altActionKey]) {
        return controls2.skewHandlerY(eventData, transform2, x2, y2);
      }
      return controls2.scalingX(eventData, transform2, x2, y2);
    }
    function changeWidth(eventData, transform2, x2, y2) {
      var target = transform2.target, localPoint = getLocalPoint(transform2, transform2.originX, transform2.originY, x2, y2), strokePadding = target.strokeWidth / (target.strokeUniform ? target.scaleX : 1), multiplier = isTransformCentered(transform2) ? 2 : 1, oldWidth = target.width, newWidth = Math.abs(localPoint.x * multiplier / target.scaleX) - strokePadding;
      target.set("width", Math.max(newWidth, 0));
      return oldWidth !== newWidth;
    }
    function dragHandler(eventData, transform2, x2, y2) {
      var target = transform2.target, newLeft = x2 - transform2.offsetX, newTop = y2 - transform2.offsetY, moveX = !target.get("lockMovementX") && target.left !== newLeft, moveY = !target.get("lockMovementY") && target.top !== newTop;
      moveX && target.set("left", newLeft);
      moveY && target.set("top", newTop);
      if (moveX || moveY) {
        fireEvent("moving", commonEventInfo(eventData, transform2, x2, y2));
      }
      return moveX || moveY;
    }
    controls2.scaleCursorStyleHandler = scaleCursorStyleHandler;
    controls2.skewCursorStyleHandler = skewCursorStyleHandler;
    controls2.scaleSkewCursorStyleHandler = scaleSkewCursorStyleHandler;
    controls2.rotationWithSnapping = wrapWithFireEvent("rotating", wrapWithFixedAnchor(rotationWithSnapping));
    controls2.scalingEqually = wrapWithFireEvent("scaling", wrapWithFixedAnchor(scaleObjectFromCorner));
    controls2.scalingX = wrapWithFireEvent("scaling", wrapWithFixedAnchor(scaleObjectX));
    controls2.scalingY = wrapWithFireEvent("scaling", wrapWithFixedAnchor(scaleObjectY));
    controls2.scalingYOrSkewingX = scalingYOrSkewingX;
    controls2.scalingXOrSkewingY = scalingXOrSkewingY;
    controls2.changeWidth = wrapWithFireEvent("resizing", wrapWithFixedAnchor(changeWidth));
    controls2.skewHandlerX = skewHandlerX;
    controls2.skewHandlerY = skewHandlerY;
    controls2.dragHandler = dragHandler;
    controls2.scaleOrSkewActionName = scaleOrSkewActionName;
    controls2.rotationStyleHandler = rotationStyleHandler;
    controls2.fireEvent = fireEvent;
    controls2.wrapWithFixedAnchor = wrapWithFixedAnchor;
    controls2.wrapWithFireEvent = wrapWithFireEvent;
    controls2.getLocalPoint = getLocalPoint;
    fabric3.controlsUtils = controls2;
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {}), degreesToRadians = fabric3.util.degreesToRadians, controls2 = fabric3.controlsUtils;
    function renderCircleControl(ctx, left, top, styleOverride, fabricObject) {
      styleOverride = styleOverride || {};
      var xSize = this.sizeX || styleOverride.cornerSize || fabricObject.cornerSize, ySize = this.sizeY || styleOverride.cornerSize || fabricObject.cornerSize, transparentCorners = typeof styleOverride.transparentCorners !== "undefined" ? styleOverride.transparentCorners : fabricObject.transparentCorners, methodName = transparentCorners ? "stroke" : "fill", stroke = !transparentCorners && (styleOverride.cornerStrokeColor || fabricObject.cornerStrokeColor), myLeft = left, myTop = top, size;
      ctx.save();
      ctx.fillStyle = styleOverride.cornerColor || fabricObject.cornerColor;
      ctx.strokeStyle = styleOverride.cornerStrokeColor || fabricObject.cornerStrokeColor;
      if (xSize > ySize) {
        size = xSize;
        ctx.scale(1, ySize / xSize);
        myTop = top * xSize / ySize;
      } else if (ySize > xSize) {
        size = ySize;
        ctx.scale(xSize / ySize, 1);
        myLeft = left * ySize / xSize;
      } else {
        size = xSize;
      }
      ctx.lineWidth = 1;
      ctx.beginPath();
      ctx.arc(myLeft, myTop, size / 2, 0, 2 * Math.PI, false);
      ctx[methodName]();
      if (stroke) {
        ctx.stroke();
      }
      ctx.restore();
    }
    function renderSquareControl(ctx, left, top, styleOverride, fabricObject) {
      styleOverride = styleOverride || {};
      var xSize = this.sizeX || styleOverride.cornerSize || fabricObject.cornerSize, ySize = this.sizeY || styleOverride.cornerSize || fabricObject.cornerSize, transparentCorners = typeof styleOverride.transparentCorners !== "undefined" ? styleOverride.transparentCorners : fabricObject.transparentCorners, methodName = transparentCorners ? "stroke" : "fill", stroke = !transparentCorners && (styleOverride.cornerStrokeColor || fabricObject.cornerStrokeColor), xSizeBy2 = xSize / 2, ySizeBy2 = ySize / 2;
      ctx.save();
      ctx.fillStyle = styleOverride.cornerColor || fabricObject.cornerColor;
      ctx.strokeStyle = styleOverride.cornerStrokeColor || fabricObject.cornerStrokeColor;
      ctx.lineWidth = 1;
      ctx.translate(left, top);
      ctx.rotate(degreesToRadians(fabricObject.angle));
      ctx[methodName + "Rect"](-xSizeBy2, -ySizeBy2, xSize, ySize);
      if (stroke) {
        ctx.strokeRect(-xSizeBy2, -ySizeBy2, xSize, ySize);
      }
      ctx.restore();
    }
    controls2.renderCircleControl = renderCircleControl;
    controls2.renderSquareControl = renderSquareControl;
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {});
    function Control(options) {
      for (var i2 in options) {
        this[i2] = options[i2];
      }
    }
    fabric3.Control = Control;
    fabric3.Control.prototype = {
      visible: true,
      actionName: "scale",
      angle: 0,
      x: 0,
      y: 0,
      offsetX: 0,
      offsetY: 0,
      sizeX: null,
      sizeY: null,
      touchSizeX: null,
      touchSizeY: null,
      cursorStyle: "crosshair",
      withConnection: false,
      actionHandler: function() {
      },
      mouseDownHandler: function() {
      },
      mouseUpHandler: function() {
      },
      getActionHandler: function() {
        return this.actionHandler;
      },
      getMouseDownHandler: function() {
        return this.mouseDownHandler;
      },
      getMouseUpHandler: function() {
        return this.mouseUpHandler;
      },
      cursorStyleHandler: function(eventData, control) {
        return control.cursorStyle;
      },
      getActionName: function(eventData, control) {
        return control.actionName;
      },
      getVisibility: function(fabricObject, controlKey) {
        var objectVisibility = fabricObject._controlsVisibility;
        if (objectVisibility && typeof objectVisibility[controlKey] !== "undefined") {
          return objectVisibility[controlKey];
        }
        return this.visible;
      },
      setVisibility: function(visibility) {
        this.visible = visibility;
      },
      positionHandler: function(dim, finalMatrix) {
        var point = fabric3.util.transformPoint({
          x: this.x * dim.x + this.offsetX,
          y: this.y * dim.y + this.offsetY
        }, finalMatrix);
        return point;
      },
      calcCornerCoords: function(objectAngle, objectCornerSize, centerX, centerY, isTouch2) {
        var cosHalfOffset, sinHalfOffset, cosHalfOffsetComp, sinHalfOffsetComp, xSize = isTouch2 ? this.touchSizeX : this.sizeX, ySize = isTouch2 ? this.touchSizeY : this.sizeY;
        if (xSize && ySize && xSize !== ySize) {
          var controlTriangleAngle = Math.atan2(ySize, xSize);
          var cornerHypotenuse = Math.sqrt(xSize * xSize + ySize * ySize) / 2;
          var newTheta = controlTriangleAngle - fabric3.util.degreesToRadians(objectAngle);
          var newThetaComp = Math.PI / 2 - controlTriangleAngle - fabric3.util.degreesToRadians(objectAngle);
          cosHalfOffset = cornerHypotenuse * fabric3.util.cos(newTheta);
          sinHalfOffset = cornerHypotenuse * fabric3.util.sin(newTheta);
          cosHalfOffsetComp = cornerHypotenuse * fabric3.util.cos(newThetaComp);
          sinHalfOffsetComp = cornerHypotenuse * fabric3.util.sin(newThetaComp);
        } else {
          var cornerSize = xSize && ySize ? xSize : objectCornerSize;
          cornerHypotenuse = cornerSize * 0.7071067812;
          var newTheta = fabric3.util.degreesToRadians(45 - objectAngle);
          cosHalfOffset = cosHalfOffsetComp = cornerHypotenuse * fabric3.util.cos(newTheta);
          sinHalfOffset = sinHalfOffsetComp = cornerHypotenuse * fabric3.util.sin(newTheta);
        }
        return {
          tl: {
            x: centerX - sinHalfOffsetComp,
            y: centerY - cosHalfOffsetComp
          },
          tr: {
            x: centerX + cosHalfOffset,
            y: centerY - sinHalfOffset
          },
          bl: {
            x: centerX - cosHalfOffset,
            y: centerY + sinHalfOffset
          },
          br: {
            x: centerX + sinHalfOffsetComp,
            y: centerY + cosHalfOffsetComp
          }
        };
      },
      render: function(ctx, left, top, styleOverride, fabricObject) {
        styleOverride = styleOverride || {};
        switch (styleOverride.cornerStyle || fabricObject.cornerStyle) {
          case "circle":
            fabric3.controlsUtils.renderCircleControl.call(this, ctx, left, top, styleOverride, fabricObject);
            break;
          default:
            fabric3.controlsUtils.renderSquareControl.call(this, ctx, left, top, styleOverride, fabricObject);
        }
      }
    };
  })(exports2);
  (function() {
    function getColorStop(el, multiplier) {
      var style2 = el.getAttribute("style"), offset2 = el.getAttribute("offset") || 0, color2, colorAlpha, opacity, i2;
      offset2 = parseFloat(offset2) / (/%$/.test(offset2) ? 100 : 1);
      offset2 = offset2 < 0 ? 0 : offset2 > 1 ? 1 : offset2;
      if (style2) {
        var keyValuePairs = style2.split(/\s*;\s*/);
        if (keyValuePairs[keyValuePairs.length - 1] === "") {
          keyValuePairs.pop();
        }
        for (i2 = keyValuePairs.length; i2--; ) {
          var split = keyValuePairs[i2].split(/\s*:\s*/), key = split[0].trim(), value = split[1].trim();
          if (key === "stop-color") {
            color2 = value;
          } else if (key === "stop-opacity") {
            opacity = value;
          }
        }
      }
      if (!color2) {
        color2 = el.getAttribute("stop-color") || "rgb(0,0,0)";
      }
      if (!opacity) {
        opacity = el.getAttribute("stop-opacity");
      }
      color2 = new fabric2.Color(color2);
      colorAlpha = color2.getAlpha();
      opacity = isNaN(parseFloat(opacity)) ? 1 : parseFloat(opacity);
      opacity *= colorAlpha * multiplier;
      return {
        offset: offset2,
        color: color2.toRgb(),
        opacity
      };
    }
    function getLinearCoords(el) {
      return {
        x1: el.getAttribute("x1") || 0,
        y1: el.getAttribute("y1") || 0,
        x2: el.getAttribute("x2") || "100%",
        y2: el.getAttribute("y2") || 0
      };
    }
    function getRadialCoords(el) {
      return {
        x1: el.getAttribute("fx") || el.getAttribute("cx") || "50%",
        y1: el.getAttribute("fy") || el.getAttribute("cy") || "50%",
        r1: 0,
        x2: el.getAttribute("cx") || "50%",
        y2: el.getAttribute("cy") || "50%",
        r2: el.getAttribute("r") || "50%"
      };
    }
    var clone = fabric2.util.object.clone;
    fabric2.Gradient = fabric2.util.createClass({
      offsetX: 0,
      offsetY: 0,
      gradientTransform: null,
      gradientUnits: "pixels",
      type: "linear",
      initialize: function(options) {
        options || (options = {});
        options.coords || (options.coords = {});
        var coords, _this = this;
        Object.keys(options).forEach(function(option) {
          _this[option] = options[option];
        });
        if (this.id) {
          this.id += "_" + fabric2.Object.__uid++;
        } else {
          this.id = fabric2.Object.__uid++;
        }
        coords = {
          x1: options.coords.x1 || 0,
          y1: options.coords.y1 || 0,
          x2: options.coords.x2 || 0,
          y2: options.coords.y2 || 0
        };
        if (this.type === "radial") {
          coords.r1 = options.coords.r1 || 0;
          coords.r2 = options.coords.r2 || 0;
        }
        this.coords = coords;
        this.colorStops = options.colorStops.slice();
      },
      addColorStop: function(colorStops) {
        for (var position2 in colorStops) {
          var color2 = new fabric2.Color(colorStops[position2]);
          this.colorStops.push({
            offset: parseFloat(position2),
            color: color2.toRgb(),
            opacity: color2.getAlpha()
          });
        }
        return this;
      },
      toObject: function(propertiesToInclude) {
        var object = {
          type: this.type,
          coords: this.coords,
          colorStops: this.colorStops,
          offsetX: this.offsetX,
          offsetY: this.offsetY,
          gradientUnits: this.gradientUnits,
          gradientTransform: this.gradientTransform ? this.gradientTransform.concat() : this.gradientTransform
        };
        fabric2.util.populateWithProperties(this, object, propertiesToInclude);
        return object;
      },
      toSVG: function(object, options) {
        var coords = clone(this.coords, true), i2, len, options = options || {}, markup, commonAttributes, colorStops = clone(this.colorStops, true), needsSwap = coords.r1 > coords.r2, transform2 = this.gradientTransform ? this.gradientTransform.concat() : fabric2.iMatrix.concat(), offsetX = -this.offsetX, offsetY = -this.offsetY, withViewport = !!options.additionalTransform, gradientUnits = this.gradientUnits === "pixels" ? "userSpaceOnUse" : "objectBoundingBox";
        colorStops.sort(function(a2, b2) {
          return a2.offset - b2.offset;
        });
        if (gradientUnits === "objectBoundingBox") {
          offsetX /= object.width;
          offsetY /= object.height;
        } else {
          offsetX += object.width / 2;
          offsetY += object.height / 2;
        }
        if (object.type === "path" && this.gradientUnits !== "percentage") {
          offsetX -= object.pathOffset.x;
          offsetY -= object.pathOffset.y;
        }
        transform2[4] -= offsetX;
        transform2[5] -= offsetY;
        commonAttributes = 'id="SVGID_' + this.id + '" gradientUnits="' + gradientUnits + '"';
        commonAttributes += ' gradientTransform="' + (withViewport ? options.additionalTransform + " " : "") + fabric2.util.matrixToSVG(transform2) + '" ';
        if (this.type === "linear") {
          markup = [
            "<linearGradient ",
            commonAttributes,
            ' x1="',
            coords.x1,
            '" y1="',
            coords.y1,
            '" x2="',
            coords.x2,
            '" y2="',
            coords.y2,
            '">\n'
          ];
        } else if (this.type === "radial") {
          markup = [
            "<radialGradient ",
            commonAttributes,
            ' cx="',
            needsSwap ? coords.x1 : coords.x2,
            '" cy="',
            needsSwap ? coords.y1 : coords.y2,
            '" r="',
            needsSwap ? coords.r1 : coords.r2,
            '" fx="',
            needsSwap ? coords.x2 : coords.x1,
            '" fy="',
            needsSwap ? coords.y2 : coords.y1,
            '">\n'
          ];
        }
        if (this.type === "radial") {
          if (needsSwap) {
            colorStops = colorStops.concat();
            colorStops.reverse();
            for (i2 = 0, len = colorStops.length; i2 < len; i2++) {
              colorStops[i2].offset = 1 - colorStops[i2].offset;
            }
          }
          var minRadius = Math.min(coords.r1, coords.r2);
          if (minRadius > 0) {
            var maxRadius = Math.max(coords.r1, coords.r2), percentageShift = minRadius / maxRadius;
            for (i2 = 0, len = colorStops.length; i2 < len; i2++) {
              colorStops[i2].offset += percentageShift * (1 - colorStops[i2].offset);
            }
          }
        }
        for (i2 = 0, len = colorStops.length; i2 < len; i2++) {
          var colorStop = colorStops[i2];
          markup.push("<stop ", 'offset="', colorStop.offset * 100 + "%", '" style="stop-color:', colorStop.color, typeof colorStop.opacity !== "undefined" ? ";stop-opacity: " + colorStop.opacity : ";", '"/>\n');
        }
        markup.push(this.type === "linear" ? "</linearGradient>\n" : "</radialGradient>\n");
        return markup.join("");
      },
      toLive: function(ctx) {
        var gradient, coords = fabric2.util.object.clone(this.coords), i2, len;
        if (!this.type) {
          return;
        }
        if (this.type === "linear") {
          gradient = ctx.createLinearGradient(coords.x1, coords.y1, coords.x2, coords.y2);
        } else if (this.type === "radial") {
          gradient = ctx.createRadialGradient(coords.x1, coords.y1, coords.r1, coords.x2, coords.y2, coords.r2);
        }
        for (i2 = 0, len = this.colorStops.length; i2 < len; i2++) {
          var color2 = this.colorStops[i2].color, opacity = this.colorStops[i2].opacity, offset2 = this.colorStops[i2].offset;
          if (typeof opacity !== "undefined") {
            color2 = new fabric2.Color(color2).setAlpha(opacity).toRgba();
          }
          gradient.addColorStop(offset2, color2);
        }
        return gradient;
      }
    });
    fabric2.util.object.extend(fabric2.Gradient, {
      fromElement: function(el, instance, opacityAttr, svgOptions) {
        var multiplier = parseFloat(opacityAttr) / (/%$/.test(opacityAttr) ? 100 : 1);
        multiplier = multiplier < 0 ? 0 : multiplier > 1 ? 1 : multiplier;
        if (isNaN(multiplier)) {
          multiplier = 1;
        }
        var colorStopEls = el.getElementsByTagName("stop"), type, gradientUnits = el.getAttribute("gradientUnits") === "userSpaceOnUse" ? "pixels" : "percentage", gradientTransform = el.getAttribute("gradientTransform") || "", colorStops = [], coords, i2, offsetX = 0, offsetY = 0, transformMatrix;
        if (el.nodeName === "linearGradient" || el.nodeName === "LINEARGRADIENT") {
          type = "linear";
          coords = getLinearCoords(el);
        } else {
          type = "radial";
          coords = getRadialCoords(el);
        }
        for (i2 = colorStopEls.length; i2--; ) {
          colorStops.push(getColorStop(colorStopEls[i2], multiplier));
        }
        transformMatrix = fabric2.parseTransformAttribute(gradientTransform);
        __convertPercentUnitsToValues(instance, coords, svgOptions, gradientUnits);
        if (gradientUnits === "pixels") {
          offsetX = -instance.left;
          offsetY = -instance.top;
        }
        var gradient = new fabric2.Gradient({
          id: el.getAttribute("id"),
          type,
          coords,
          colorStops,
          gradientUnits,
          gradientTransform: transformMatrix,
          offsetX,
          offsetY
        });
        return gradient;
      }
    });
    function __convertPercentUnitsToValues(instance, options, svgOptions, gradientUnits) {
      var propValue, finalValue;
      Object.keys(options).forEach(function(prop) {
        propValue = options[prop];
        if (propValue === "Infinity") {
          finalValue = 1;
        } else if (propValue === "-Infinity") {
          finalValue = 0;
        } else {
          finalValue = parseFloat(options[prop], 10);
          if (typeof propValue === "string" && /^(\d+\.\d+)%|(\d+)%$/.test(propValue)) {
            finalValue *= 0.01;
            if (gradientUnits === "pixels") {
              if (prop === "x1" || prop === "x2" || prop === "r2") {
                finalValue *= svgOptions.viewBoxWidth || svgOptions.width;
              }
              if (prop === "y1" || prop === "y2") {
                finalValue *= svgOptions.viewBoxHeight || svgOptions.height;
              }
            }
          }
        }
        options[prop] = finalValue;
      });
    }
  })();
  (function() {
    var toFixed = fabric2.util.toFixed;
    fabric2.Pattern = fabric2.util.createClass({
      repeat: "repeat",
      offsetX: 0,
      offsetY: 0,
      crossOrigin: "",
      patternTransform: null,
      initialize: function(options, callback) {
        options || (options = {});
        this.id = fabric2.Object.__uid++;
        this.setOptions(options);
        if (!options.source || options.source && typeof options.source !== "string") {
          callback && callback(this);
          return;
        } else {
          var _this = this;
          this.source = fabric2.util.createImage();
          fabric2.util.loadImage(options.source, function(img, isError2) {
            _this.source = img;
            callback && callback(_this, isError2);
          }, null, this.crossOrigin);
        }
      },
      toObject: function(propertiesToInclude) {
        var NUM_FRACTION_DIGITS = fabric2.Object.NUM_FRACTION_DIGITS, source, object;
        if (typeof this.source.src === "string") {
          source = this.source.src;
        } else if (typeof this.source === "object" && this.source.toDataURL) {
          source = this.source.toDataURL();
        }
        object = {
          type: "pattern",
          source,
          repeat: this.repeat,
          crossOrigin: this.crossOrigin,
          offsetX: toFixed(this.offsetX, NUM_FRACTION_DIGITS),
          offsetY: toFixed(this.offsetY, NUM_FRACTION_DIGITS),
          patternTransform: this.patternTransform ? this.patternTransform.concat() : null
        };
        fabric2.util.populateWithProperties(this, object, propertiesToInclude);
        return object;
      },
      toSVG: function(object) {
        var patternSource = typeof this.source === "function" ? this.source() : this.source, patternWidth = patternSource.width / object.width, patternHeight = patternSource.height / object.height, patternOffsetX = this.offsetX / object.width, patternOffsetY = this.offsetY / object.height, patternImgSrc = "";
        if (this.repeat === "repeat-x" || this.repeat === "no-repeat") {
          patternHeight = 1;
          if (patternOffsetY) {
            patternHeight += Math.abs(patternOffsetY);
          }
        }
        if (this.repeat === "repeat-y" || this.repeat === "no-repeat") {
          patternWidth = 1;
          if (patternOffsetX) {
            patternWidth += Math.abs(patternOffsetX);
          }
        }
        if (patternSource.src) {
          patternImgSrc = patternSource.src;
        } else if (patternSource.toDataURL) {
          patternImgSrc = patternSource.toDataURL();
        }
        return '<pattern id="SVGID_' + this.id + '" x="' + patternOffsetX + '" y="' + patternOffsetY + '" width="' + patternWidth + '" height="' + patternHeight + '">\n<image x="0" y="0" width="' + patternSource.width + '" height="' + patternSource.height + '" xlink:href="' + patternImgSrc + '"></image>\n</pattern>\n';
      },
      setOptions: function(options) {
        for (var prop in options) {
          this[prop] = options[prop];
        }
      },
      toLive: function(ctx) {
        var source = this.source;
        if (!source) {
          return "";
        }
        if (typeof source.src !== "undefined") {
          if (!source.complete) {
            return "";
          }
          if (source.naturalWidth === 0 || source.naturalHeight === 0) {
            return "";
          }
        }
        return ctx.createPattern(source, this.repeat);
      }
    });
  })();
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {}), toFixed = fabric3.util.toFixed;
    if (fabric3.Shadow) {
      fabric3.warn("fabric.Shadow is already defined.");
      return;
    }
    fabric3.Shadow = fabric3.util.createClass({
      color: "rgb(0,0,0)",
      blur: 0,
      offsetX: 0,
      offsetY: 0,
      affectStroke: false,
      includeDefaultValues: true,
      nonScaling: false,
      initialize: function(options) {
        if (typeof options === "string") {
          options = this._parseShadow(options);
        }
        for (var prop in options) {
          this[prop] = options[prop];
        }
        this.id = fabric3.Object.__uid++;
      },
      _parseShadow: function(shadow) {
        var shadowStr = shadow.trim(), offsetsAndBlur = fabric3.Shadow.reOffsetsAndBlur.exec(shadowStr) || [], color2 = shadowStr.replace(fabric3.Shadow.reOffsetsAndBlur, "") || "rgb(0,0,0)";
        return {
          color: color2.trim(),
          offsetX: parseFloat(offsetsAndBlur[1], 10) || 0,
          offsetY: parseFloat(offsetsAndBlur[2], 10) || 0,
          blur: parseFloat(offsetsAndBlur[3], 10) || 0
        };
      },
      toString: function() {
        return [this.offsetX, this.offsetY, this.blur, this.color].join("px ");
      },
      toSVG: function(object) {
        var fBoxX = 40, fBoxY = 40, NUM_FRACTION_DIGITS = fabric3.Object.NUM_FRACTION_DIGITS, offset2 = fabric3.util.rotateVector({ x: this.offsetX, y: this.offsetY }, fabric3.util.degreesToRadians(-object.angle)), BLUR_BOX = 20, color2 = new fabric3.Color(this.color);
        if (object.width && object.height) {
          fBoxX = toFixed((Math.abs(offset2.x) + this.blur) / object.width, NUM_FRACTION_DIGITS) * 100 + BLUR_BOX;
          fBoxY = toFixed((Math.abs(offset2.y) + this.blur) / object.height, NUM_FRACTION_DIGITS) * 100 + BLUR_BOX;
        }
        if (object.flipX) {
          offset2.x *= -1;
        }
        if (object.flipY) {
          offset2.y *= -1;
        }
        return '<filter id="SVGID_' + this.id + '" y="-' + fBoxY + '%" height="' + (100 + 2 * fBoxY) + '%" x="-' + fBoxX + '%" width="' + (100 + 2 * fBoxX) + '%" >\n	<feGaussianBlur in="SourceAlpha" stdDeviation="' + toFixed(this.blur ? this.blur / 2 : 0, NUM_FRACTION_DIGITS) + '"></feGaussianBlur>\n	<feOffset dx="' + toFixed(offset2.x, NUM_FRACTION_DIGITS) + '" dy="' + toFixed(offset2.y, NUM_FRACTION_DIGITS) + '" result="oBlur" ></feOffset>\n	<feFlood flood-color="' + color2.toRgb() + '" flood-opacity="' + color2.getAlpha() + '"/>\n	<feComposite in2="oBlur" operator="in" />\n	<feMerge>\n		<feMergeNode></feMergeNode>\n		<feMergeNode in="SourceGraphic"></feMergeNode>\n	</feMerge>\n</filter>\n';
      },
      toObject: function() {
        if (this.includeDefaultValues) {
          return {
            color: this.color,
            blur: this.blur,
            offsetX: this.offsetX,
            offsetY: this.offsetY,
            affectStroke: this.affectStroke,
            nonScaling: this.nonScaling
          };
        }
        var obj = {}, proto = fabric3.Shadow.prototype;
        ["color", "blur", "offsetX", "offsetY", "affectStroke", "nonScaling"].forEach(function(prop) {
          if (this[prop] !== proto[prop]) {
            obj[prop] = this[prop];
          }
        }, this);
        return obj;
      }
    });
    fabric3.Shadow.reOffsetsAndBlur = /(?:\s|^)(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(\d+(?:\.\d*)?(?:px)?)?(?:\s?|$)(?:$|\s)/;
  })(exports2);
  (function() {
    if (fabric2.StaticCanvas) {
      fabric2.warn("fabric.StaticCanvas is already defined.");
      return;
    }
    var extend = fabric2.util.object.extend, getElementOffset = fabric2.util.getElementOffset, removeFromArray = fabric2.util.removeFromArray, toFixed = fabric2.util.toFixed, transformPoint = fabric2.util.transformPoint, invertTransform = fabric2.util.invertTransform, getNodeCanvas = fabric2.util.getNodeCanvas, createCanvasElement = fabric2.util.createCanvasElement, CANVAS_INIT_ERROR = new Error("Could not initialize `canvas` element");
    fabric2.StaticCanvas = fabric2.util.createClass(fabric2.CommonMethods, {
      initialize: function(el, options) {
        options || (options = {});
        this.renderAndResetBound = this.renderAndReset.bind(this);
        this.requestRenderAllBound = this.requestRenderAll.bind(this);
        this._initStatic(el, options);
      },
      backgroundColor: "",
      backgroundImage: null,
      overlayColor: "",
      overlayImage: null,
      includeDefaultValues: true,
      stateful: false,
      renderOnAddRemove: true,
      controlsAboveOverlay: false,
      allowTouchScrolling: false,
      imageSmoothingEnabled: true,
      viewportTransform: fabric2.iMatrix.concat(),
      backgroundVpt: true,
      overlayVpt: true,
      enableRetinaScaling: true,
      vptCoords: {},
      skipOffscreen: true,
      clipPath: void 0,
      _initStatic: function(el, options) {
        var cb2 = this.requestRenderAllBound;
        this._objects = [];
        this._createLowerCanvas(el);
        this._initOptions(options);
        if (!this.interactive) {
          this._initRetinaScaling();
        }
        if (options.overlayImage) {
          this.setOverlayImage(options.overlayImage, cb2);
        }
        if (options.backgroundImage) {
          this.setBackgroundImage(options.backgroundImage, cb2);
        }
        if (options.backgroundColor) {
          this.setBackgroundColor(options.backgroundColor, cb2);
        }
        if (options.overlayColor) {
          this.setOverlayColor(options.overlayColor, cb2);
        }
        this.calcOffset();
      },
      _isRetinaScaling: function() {
        return fabric2.devicePixelRatio !== 1 && this.enableRetinaScaling;
      },
      getRetinaScaling: function() {
        return this._isRetinaScaling() ? fabric2.devicePixelRatio : 1;
      },
      _initRetinaScaling: function() {
        if (!this._isRetinaScaling()) {
          return;
        }
        var scaleRatio = fabric2.devicePixelRatio;
        this.__initRetinaScaling(scaleRatio, this.lowerCanvasEl, this.contextContainer);
        if (this.upperCanvasEl) {
          this.__initRetinaScaling(scaleRatio, this.upperCanvasEl, this.contextTop);
        }
      },
      __initRetinaScaling: function(scaleRatio, canvas, context) {
        canvas.setAttribute("width", this.width * scaleRatio);
        canvas.setAttribute("height", this.height * scaleRatio);
        context.scale(scaleRatio, scaleRatio);
      },
      calcOffset: function() {
        this._offset = getElementOffset(this.lowerCanvasEl);
        return this;
      },
      setOverlayImage: function(image, callback, options) {
        return this.__setBgOverlayImage("overlayImage", image, callback, options);
      },
      setBackgroundImage: function(image, callback, options) {
        return this.__setBgOverlayImage("backgroundImage", image, callback, options);
      },
      setOverlayColor: function(overlayColor, callback) {
        return this.__setBgOverlayColor("overlayColor", overlayColor, callback);
      },
      setBackgroundColor: function(backgroundColor, callback) {
        return this.__setBgOverlayColor("backgroundColor", backgroundColor, callback);
      },
      __setBgOverlayImage: function(property, image, callback, options) {
        if (typeof image === "string") {
          fabric2.util.loadImage(image, function(img, isError2) {
            if (img) {
              var instance = new fabric2.Image(img, options);
              this[property] = instance;
              instance.canvas = this;
            }
            callback && callback(img, isError2);
          }, this, options && options.crossOrigin);
        } else {
          options && image.setOptions(options);
          this[property] = image;
          image && (image.canvas = this);
          callback && callback(image, false);
        }
        return this;
      },
      __setBgOverlayColor: function(property, color2, callback) {
        this[property] = color2;
        this._initGradient(color2, property);
        this._initPattern(color2, property, callback);
        return this;
      },
      _createCanvasElement: function() {
        var element = createCanvasElement();
        if (!element) {
          throw CANVAS_INIT_ERROR;
        }
        if (!element.style) {
          element.style = {};
        }
        if (typeof element.getContext === "undefined") {
          throw CANVAS_INIT_ERROR;
        }
        return element;
      },
      _initOptions: function(options) {
        var lowerCanvasEl = this.lowerCanvasEl;
        this._setOptions(options);
        this.width = this.width || parseInt(lowerCanvasEl.width, 10) || 0;
        this.height = this.height || parseInt(lowerCanvasEl.height, 10) || 0;
        if (!this.lowerCanvasEl.style) {
          return;
        }
        lowerCanvasEl.width = this.width;
        lowerCanvasEl.height = this.height;
        lowerCanvasEl.style.width = this.width + "px";
        lowerCanvasEl.style.height = this.height + "px";
        this.viewportTransform = this.viewportTransform.slice();
      },
      _createLowerCanvas: function(canvasEl) {
        if (canvasEl && canvasEl.getContext) {
          this.lowerCanvasEl = canvasEl;
        } else {
          this.lowerCanvasEl = fabric2.util.getById(canvasEl) || this._createCanvasElement();
        }
        fabric2.util.addClass(this.lowerCanvasEl, "lower-canvas");
        this._originalCanvasStyle = this.lowerCanvasEl.style;
        if (this.interactive) {
          this._applyCanvasStyle(this.lowerCanvasEl);
        }
        this.contextContainer = this.lowerCanvasEl.getContext("2d");
      },
      getWidth: function() {
        return this.width;
      },
      getHeight: function() {
        return this.height;
      },
      setWidth: function(value, options) {
        return this.setDimensions({ width: value }, options);
      },
      setHeight: function(value, options) {
        return this.setDimensions({ height: value }, options);
      },
      setDimensions: function(dimensions, options) {
        var cssValue;
        options = options || {};
        for (var prop in dimensions) {
          cssValue = dimensions[prop];
          if (!options.cssOnly) {
            this._setBackstoreDimension(prop, dimensions[prop]);
            cssValue += "px";
            this.hasLostContext = true;
          }
          if (!options.backstoreOnly) {
            this._setCssDimension(prop, cssValue);
          }
        }
        if (this._isCurrentlyDrawing) {
          this.freeDrawingBrush && this.freeDrawingBrush._setBrushStyles();
        }
        this._initRetinaScaling();
        this.calcOffset();
        if (!options.cssOnly) {
          this.requestRenderAll();
        }
        return this;
      },
      _setBackstoreDimension: function(prop, value) {
        this.lowerCanvasEl[prop] = value;
        if (this.upperCanvasEl) {
          this.upperCanvasEl[prop] = value;
        }
        if (this.cacheCanvasEl) {
          this.cacheCanvasEl[prop] = value;
        }
        this[prop] = value;
        return this;
      },
      _setCssDimension: function(prop, value) {
        this.lowerCanvasEl.style[prop] = value;
        if (this.upperCanvasEl) {
          this.upperCanvasEl.style[prop] = value;
        }
        if (this.wrapperEl) {
          this.wrapperEl.style[prop] = value;
        }
        return this;
      },
      getZoom: function() {
        return this.viewportTransform[0];
      },
      setViewportTransform: function(vpt) {
        var activeObject = this._activeObject, backgroundObject = this.backgroundImage, overlayObject = this.overlayImage, object, i2, len;
        this.viewportTransform = vpt;
        for (i2 = 0, len = this._objects.length; i2 < len; i2++) {
          object = this._objects[i2];
          object.group || object.setCoords(true);
        }
        if (activeObject) {
          activeObject.setCoords();
        }
        if (backgroundObject) {
          backgroundObject.setCoords(true);
        }
        if (overlayObject) {
          overlayObject.setCoords(true);
        }
        this.calcViewportBoundaries();
        this.renderOnAddRemove && this.requestRenderAll();
        return this;
      },
      zoomToPoint: function(point, value) {
        var before = point, vpt = this.viewportTransform.slice(0);
        point = transformPoint(point, invertTransform(this.viewportTransform));
        vpt[0] = value;
        vpt[3] = value;
        var after = transformPoint(point, vpt);
        vpt[4] += before.x - after.x;
        vpt[5] += before.y - after.y;
        return this.setViewportTransform(vpt);
      },
      setZoom: function(value) {
        this.zoomToPoint(new fabric2.Point(0, 0), value);
        return this;
      },
      absolutePan: function(point) {
        var vpt = this.viewportTransform.slice(0);
        vpt[4] = -point.x;
        vpt[5] = -point.y;
        return this.setViewportTransform(vpt);
      },
      relativePan: function(point) {
        return this.absolutePan(new fabric2.Point(-point.x - this.viewportTransform[4], -point.y - this.viewportTransform[5]));
      },
      getElement: function() {
        return this.lowerCanvasEl;
      },
      _onObjectAdded: function(obj) {
        this.stateful && obj.setupState();
        obj._set("canvas", this);
        obj.setCoords();
        this.fire("object:added", { target: obj });
        obj.fire("added");
      },
      _onObjectRemoved: function(obj) {
        this.fire("object:removed", { target: obj });
        obj.fire("removed");
        delete obj.canvas;
      },
      clearContext: function(ctx) {
        ctx.clearRect(0, 0, this.width, this.height);
        return this;
      },
      getContext: function() {
        return this.contextContainer;
      },
      clear: function() {
        this.remove.apply(this, this.getObjects());
        this.backgroundImage = null;
        this.overlayImage = null;
        this.backgroundColor = "";
        this.overlayColor = "";
        if (this._hasITextHandlers) {
          this.off("mouse:up", this._mouseUpITextHandler);
          this._iTextInstances = null;
          this._hasITextHandlers = false;
        }
        this.clearContext(this.contextContainer);
        this.fire("canvas:cleared");
        this.renderOnAddRemove && this.requestRenderAll();
        return this;
      },
      renderAll: function() {
        var canvasToDrawOn = this.contextContainer;
        this.renderCanvas(canvasToDrawOn, this._objects);
        return this;
      },
      renderAndReset: function() {
        this.isRendering = 0;
        this.renderAll();
      },
      requestRenderAll: function() {
        if (!this.isRendering) {
          this.isRendering = fabric2.util.requestAnimFrame(this.renderAndResetBound);
        }
        return this;
      },
      calcViewportBoundaries: function() {
        var points = {}, width = this.width, height = this.height, iVpt = invertTransform(this.viewportTransform);
        points.tl = transformPoint({ x: 0, y: 0 }, iVpt);
        points.br = transformPoint({ x: width, y: height }, iVpt);
        points.tr = new fabric2.Point(points.br.x, points.tl.y);
        points.bl = new fabric2.Point(points.tl.x, points.br.y);
        this.vptCoords = points;
        return points;
      },
      cancelRequestedRender: function() {
        if (this.isRendering) {
          fabric2.util.cancelAnimFrame(this.isRendering);
          this.isRendering = 0;
        }
      },
      renderCanvas: function(ctx, objects) {
        var v2 = this.viewportTransform, path = this.clipPath;
        this.cancelRequestedRender();
        this.calcViewportBoundaries();
        this.clearContext(ctx);
        fabric2.util.setImageSmoothing(ctx, this.imageSmoothingEnabled);
        this.fire("before:render", { ctx });
        this._renderBackground(ctx);
        ctx.save();
        ctx.transform(v2[0], v2[1], v2[2], v2[3], v2[4], v2[5]);
        this._renderObjects(ctx, objects);
        ctx.restore();
        if (!this.controlsAboveOverlay && this.interactive) {
          this.drawControls(ctx);
        }
        if (path) {
          path.canvas = this;
          path.shouldCache();
          path._transformDone = true;
          path.renderCache({ forClipping: true });
          this.drawClipPathOnCanvas(ctx);
        }
        this._renderOverlay(ctx);
        if (this.controlsAboveOverlay && this.interactive) {
          this.drawControls(ctx);
        }
        this.fire("after:render", { ctx });
      },
      drawClipPathOnCanvas: function(ctx) {
        var v2 = this.viewportTransform, path = this.clipPath;
        ctx.save();
        ctx.transform(v2[0], v2[1], v2[2], v2[3], v2[4], v2[5]);
        ctx.globalCompositeOperation = "destination-in";
        path.transform(ctx);
        ctx.scale(1 / path.zoomX, 1 / path.zoomY);
        ctx.drawImage(path._cacheCanvas, -path.cacheTranslationX, -path.cacheTranslationY);
        ctx.restore();
      },
      _renderObjects: function(ctx, objects) {
        var i2, len;
        for (i2 = 0, len = objects.length; i2 < len; ++i2) {
          objects[i2] && objects[i2].render(ctx);
        }
      },
      _renderBackgroundOrOverlay: function(ctx, property) {
        var fill2 = this[property + "Color"], object = this[property + "Image"], v2 = this.viewportTransform, needsVpt = this[property + "Vpt"];
        if (!fill2 && !object) {
          return;
        }
        if (fill2) {
          ctx.save();
          ctx.beginPath();
          ctx.moveTo(0, 0);
          ctx.lineTo(this.width, 0);
          ctx.lineTo(this.width, this.height);
          ctx.lineTo(0, this.height);
          ctx.closePath();
          ctx.fillStyle = fill2.toLive ? fill2.toLive(ctx, this) : fill2;
          if (needsVpt) {
            ctx.transform(v2[0], v2[1], v2[2], v2[3], v2[4], v2[5]);
          }
          ctx.transform(1, 0, 0, 1, fill2.offsetX || 0, fill2.offsetY || 0);
          var m2 = fill2.gradientTransform || fill2.patternTransform;
          m2 && ctx.transform(m2[0], m2[1], m2[2], m2[3], m2[4], m2[5]);
          ctx.fill();
          ctx.restore();
        }
        if (object) {
          ctx.save();
          if (needsVpt) {
            ctx.transform(v2[0], v2[1], v2[2], v2[3], v2[4], v2[5]);
          }
          object.render(ctx);
          ctx.restore();
        }
      },
      _renderBackground: function(ctx) {
        this._renderBackgroundOrOverlay(ctx, "background");
      },
      _renderOverlay: function(ctx) {
        this._renderBackgroundOrOverlay(ctx, "overlay");
      },
      getCenter: function() {
        return {
          top: this.height / 2,
          left: this.width / 2
        };
      },
      centerObjectH: function(object) {
        return this._centerObject(object, new fabric2.Point(this.getCenter().left, object.getCenterPoint().y));
      },
      centerObjectV: function(object) {
        return this._centerObject(object, new fabric2.Point(object.getCenterPoint().x, this.getCenter().top));
      },
      centerObject: function(object) {
        var center = this.getCenter();
        return this._centerObject(object, new fabric2.Point(center.left, center.top));
      },
      viewportCenterObject: function(object) {
        var vpCenter = this.getVpCenter();
        return this._centerObject(object, vpCenter);
      },
      viewportCenterObjectH: function(object) {
        var vpCenter = this.getVpCenter();
        this._centerObject(object, new fabric2.Point(vpCenter.x, object.getCenterPoint().y));
        return this;
      },
      viewportCenterObjectV: function(object) {
        var vpCenter = this.getVpCenter();
        return this._centerObject(object, new fabric2.Point(object.getCenterPoint().x, vpCenter.y));
      },
      getVpCenter: function() {
        var center = this.getCenter(), iVpt = invertTransform(this.viewportTransform);
        return transformPoint({ x: center.left, y: center.top }, iVpt);
      },
      _centerObject: function(object, center) {
        object.setPositionByOrigin(center, "center", "center");
        object.setCoords();
        this.renderOnAddRemove && this.requestRenderAll();
        return this;
      },
      toDatalessJSON: function(propertiesToInclude) {
        return this.toDatalessObject(propertiesToInclude);
      },
      toObject: function(propertiesToInclude) {
        return this._toObjectMethod("toObject", propertiesToInclude);
      },
      toDatalessObject: function(propertiesToInclude) {
        return this._toObjectMethod("toDatalessObject", propertiesToInclude);
      },
      _toObjectMethod: function(methodName, propertiesToInclude) {
        var clipPath = this.clipPath, data = {
          version: fabric2.version,
          objects: this._toObjects(methodName, propertiesToInclude)
        };
        if (clipPath && !clipPath.excludeFromExport) {
          data.clipPath = this._toObject(this.clipPath, methodName, propertiesToInclude);
        }
        extend(data, this.__serializeBgOverlay(methodName, propertiesToInclude));
        fabric2.util.populateWithProperties(this, data, propertiesToInclude);
        return data;
      },
      _toObjects: function(methodName, propertiesToInclude) {
        return this._objects.filter(function(object) {
          return !object.excludeFromExport;
        }).map(function(instance) {
          return this._toObject(instance, methodName, propertiesToInclude);
        }, this);
      },
      _toObject: function(instance, methodName, propertiesToInclude) {
        var originalValue;
        if (!this.includeDefaultValues) {
          originalValue = instance.includeDefaultValues;
          instance.includeDefaultValues = false;
        }
        var object = instance[methodName](propertiesToInclude);
        if (!this.includeDefaultValues) {
          instance.includeDefaultValues = originalValue;
        }
        return object;
      },
      __serializeBgOverlay: function(methodName, propertiesToInclude) {
        var data = {}, bgImage = this.backgroundImage, overlayImage = this.overlayImage, bgColor = this.backgroundColor, overlayColor = this.overlayColor;
        if (bgColor && bgColor.toObject) {
          if (!bgColor.excludeFromExport) {
            data.background = bgColor.toObject(propertiesToInclude);
          }
        } else if (bgColor) {
          data.background = bgColor;
        }
        if (overlayColor && overlayColor.toObject) {
          if (!overlayColor.excludeFromExport) {
            data.overlay = overlayColor.toObject(propertiesToInclude);
          }
        } else if (overlayColor) {
          data.overlay = overlayColor;
        }
        if (bgImage && !bgImage.excludeFromExport) {
          data.backgroundImage = this._toObject(bgImage, methodName, propertiesToInclude);
        }
        if (overlayImage && !overlayImage.excludeFromExport) {
          data.overlayImage = this._toObject(overlayImage, methodName, propertiesToInclude);
        }
        return data;
      },
      svgViewportTransformation: true,
      toSVG: function(options, reviver) {
        options || (options = {});
        options.reviver = reviver;
        var markup = [];
        this._setSVGPreamble(markup, options);
        this._setSVGHeader(markup, options);
        if (this.clipPath) {
          markup.push('<g clip-path="url(#' + this.clipPath.clipPathId + ')" >\n');
        }
        this._setSVGBgOverlayColor(markup, "background");
        this._setSVGBgOverlayImage(markup, "backgroundImage", reviver);
        this._setSVGObjects(markup, reviver);
        if (this.clipPath) {
          markup.push("</g>\n");
        }
        this._setSVGBgOverlayColor(markup, "overlay");
        this._setSVGBgOverlayImage(markup, "overlayImage", reviver);
        markup.push("</svg>");
        return markup.join("");
      },
      _setSVGPreamble: function(markup, options) {
        if (options.suppressPreamble) {
          return;
        }
        markup.push('<?xml version="1.0" encoding="', options.encoding || "UTF-8", '" standalone="no" ?>\n', '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ', '"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n');
      },
      _setSVGHeader: function(markup, options) {
        var width = options.width || this.width, height = options.height || this.height, vpt, viewBox = 'viewBox="0 0 ' + this.width + " " + this.height + '" ', NUM_FRACTION_DIGITS = fabric2.Object.NUM_FRACTION_DIGITS;
        if (options.viewBox) {
          viewBox = 'viewBox="' + options.viewBox.x + " " + options.viewBox.y + " " + options.viewBox.width + " " + options.viewBox.height + '" ';
        } else {
          if (this.svgViewportTransformation) {
            vpt = this.viewportTransform;
            viewBox = 'viewBox="' + toFixed(-vpt[4] / vpt[0], NUM_FRACTION_DIGITS) + " " + toFixed(-vpt[5] / vpt[3], NUM_FRACTION_DIGITS) + " " + toFixed(this.width / vpt[0], NUM_FRACTION_DIGITS) + " " + toFixed(this.height / vpt[3], NUM_FRACTION_DIGITS) + '" ';
          }
        }
        markup.push("<svg ", 'xmlns="http://www.w3.org/2000/svg" ', 'xmlns:xlink="http://www.w3.org/1999/xlink" ', 'version="1.1" ', 'width="', width, '" ', 'height="', height, '" ', viewBox, 'xml:space="preserve">\n', "<desc>Created with Fabric.js ", fabric2.version, "</desc>\n", "<defs>\n", this.createSVGFontFacesMarkup(), this.createSVGRefElementsMarkup(), this.createSVGClipPathMarkup(options), "</defs>\n");
      },
      createSVGClipPathMarkup: function(options) {
        var clipPath = this.clipPath;
        if (clipPath) {
          clipPath.clipPathId = "CLIPPATH_" + fabric2.Object.__uid++;
          return '<clipPath id="' + clipPath.clipPathId + '" >\n' + this.clipPath.toClipPathSVG(options.reviver) + "</clipPath>\n";
        }
        return "";
      },
      createSVGRefElementsMarkup: function() {
        var _this = this, markup = ["background", "overlay"].map(function(prop) {
          var fill2 = _this[prop + "Color"];
          if (fill2 && fill2.toLive) {
            var shouldTransform = _this[prop + "Vpt"], vpt = _this.viewportTransform, object = {
              width: _this.width / (shouldTransform ? vpt[0] : 1),
              height: _this.height / (shouldTransform ? vpt[3] : 1)
            };
            return fill2.toSVG(object, { additionalTransform: shouldTransform ? fabric2.util.matrixToSVG(vpt) : "" });
          }
        });
        return markup.join("");
      },
      createSVGFontFacesMarkup: function() {
        var markup = "", fontList = {}, obj, fontFamily, style2, row, rowIndex, _char, charIndex, i2, len, fontPaths = fabric2.fontPaths, objects = [];
        this._objects.forEach(function add(object) {
          objects.push(object);
          if (object._objects) {
            object._objects.forEach(add);
          }
        });
        for (i2 = 0, len = objects.length; i2 < len; i2++) {
          obj = objects[i2];
          fontFamily = obj.fontFamily;
          if (obj.type.indexOf("text") === -1 || fontList[fontFamily] || !fontPaths[fontFamily]) {
            continue;
          }
          fontList[fontFamily] = true;
          if (!obj.styles) {
            continue;
          }
          style2 = obj.styles;
          for (rowIndex in style2) {
            row = style2[rowIndex];
            for (charIndex in row) {
              _char = row[charIndex];
              fontFamily = _char.fontFamily;
              if (!fontList[fontFamily] && fontPaths[fontFamily]) {
                fontList[fontFamily] = true;
              }
            }
          }
        }
        for (var j2 in fontList) {
          markup += [
            "		@font-face {\n",
            "			font-family: '",
            j2,
            "';\n",
            "			src: url('",
            fontPaths[j2],
            "');\n",
            "		}\n"
          ].join("");
        }
        if (markup) {
          markup = [
            '	<style type="text/css">',
            "<![CDATA[\n",
            markup,
            "]]>",
            "</style>\n"
          ].join("");
        }
        return markup;
      },
      _setSVGObjects: function(markup, reviver) {
        var instance, i2, len, objects = this._objects;
        for (i2 = 0, len = objects.length; i2 < len; i2++) {
          instance = objects[i2];
          if (instance.excludeFromExport) {
            continue;
          }
          this._setSVGObject(markup, instance, reviver);
        }
      },
      _setSVGObject: function(markup, instance, reviver) {
        markup.push(instance.toSVG(reviver));
      },
      _setSVGBgOverlayImage: function(markup, property, reviver) {
        if (this[property] && !this[property].excludeFromExport && this[property].toSVG) {
          markup.push(this[property].toSVG(reviver));
        }
      },
      _setSVGBgOverlayColor: function(markup, property) {
        var filler = this[property + "Color"], vpt = this.viewportTransform, finalWidth = this.width, finalHeight = this.height;
        if (!filler) {
          return;
        }
        if (filler.toLive) {
          var repeat = filler.repeat, iVpt = fabric2.util.invertTransform(vpt), shouldInvert = this[property + "Vpt"], additionalTransform = shouldInvert ? fabric2.util.matrixToSVG(iVpt) : "";
          markup.push('<rect transform="' + additionalTransform + " translate(", finalWidth / 2, ",", finalHeight / 2, ')"', ' x="', filler.offsetX - finalWidth / 2, '" y="', filler.offsetY - finalHeight / 2, '" ', 'width="', repeat === "repeat-y" || repeat === "no-repeat" ? filler.source.width : finalWidth, '" height="', repeat === "repeat-x" || repeat === "no-repeat" ? filler.source.height : finalHeight, '" fill="url(#SVGID_' + filler.id + ')"', "></rect>\n");
        } else {
          markup.push('<rect x="0" y="0" width="100%" height="100%" ', 'fill="', filler, '"', "></rect>\n");
        }
      },
      sendToBack: function(object) {
        if (!object) {
          return this;
        }
        var activeSelection = this._activeObject, i2, obj, objs;
        if (object === activeSelection && object.type === "activeSelection") {
          objs = activeSelection._objects;
          for (i2 = objs.length; i2--; ) {
            obj = objs[i2];
            removeFromArray(this._objects, obj);
            this._objects.unshift(obj);
          }
        } else {
          removeFromArray(this._objects, object);
          this._objects.unshift(object);
        }
        this.renderOnAddRemove && this.requestRenderAll();
        return this;
      },
      bringToFront: function(object) {
        if (!object) {
          return this;
        }
        var activeSelection = this._activeObject, i2, obj, objs;
        if (object === activeSelection && object.type === "activeSelection") {
          objs = activeSelection._objects;
          for (i2 = 0; i2 < objs.length; i2++) {
            obj = objs[i2];
            removeFromArray(this._objects, obj);
            this._objects.push(obj);
          }
        } else {
          removeFromArray(this._objects, object);
          this._objects.push(object);
        }
        this.renderOnAddRemove && this.requestRenderAll();
        return this;
      },
      sendBackwards: function(object, intersecting) {
        if (!object) {
          return this;
        }
        var activeSelection = this._activeObject, i2, obj, idx, newIdx, objs, objsMoved = 0;
        if (object === activeSelection && object.type === "activeSelection") {
          objs = activeSelection._objects;
          for (i2 = 0; i2 < objs.length; i2++) {
            obj = objs[i2];
            idx = this._objects.indexOf(obj);
            if (idx > 0 + objsMoved) {
              newIdx = idx - 1;
              removeFromArray(this._objects, obj);
              this._objects.splice(newIdx, 0, obj);
            }
            objsMoved++;
          }
        } else {
          idx = this._objects.indexOf(object);
          if (idx !== 0) {
            newIdx = this._findNewLowerIndex(object, idx, intersecting);
            removeFromArray(this._objects, object);
            this._objects.splice(newIdx, 0, object);
          }
        }
        this.renderOnAddRemove && this.requestRenderAll();
        return this;
      },
      _findNewLowerIndex: function(object, idx, intersecting) {
        var newIdx, i2;
        if (intersecting) {
          newIdx = idx;
          for (i2 = idx - 1; i2 >= 0; --i2) {
            var isIntersecting = object.intersectsWithObject(this._objects[i2]) || object.isContainedWithinObject(this._objects[i2]) || this._objects[i2].isContainedWithinObject(object);
            if (isIntersecting) {
              newIdx = i2;
              break;
            }
          }
        } else {
          newIdx = idx - 1;
        }
        return newIdx;
      },
      bringForward: function(object, intersecting) {
        if (!object) {
          return this;
        }
        var activeSelection = this._activeObject, i2, obj, idx, newIdx, objs, objsMoved = 0;
        if (object === activeSelection && object.type === "activeSelection") {
          objs = activeSelection._objects;
          for (i2 = objs.length; i2--; ) {
            obj = objs[i2];
            idx = this._objects.indexOf(obj);
            if (idx < this._objects.length - 1 - objsMoved) {
              newIdx = idx + 1;
              removeFromArray(this._objects, obj);
              this._objects.splice(newIdx, 0, obj);
            }
            objsMoved++;
          }
        } else {
          idx = this._objects.indexOf(object);
          if (idx !== this._objects.length - 1) {
            newIdx = this._findNewUpperIndex(object, idx, intersecting);
            removeFromArray(this._objects, object);
            this._objects.splice(newIdx, 0, object);
          }
        }
        this.renderOnAddRemove && this.requestRenderAll();
        return this;
      },
      _findNewUpperIndex: function(object, idx, intersecting) {
        var newIdx, i2, len;
        if (intersecting) {
          newIdx = idx;
          for (i2 = idx + 1, len = this._objects.length; i2 < len; ++i2) {
            var isIntersecting = object.intersectsWithObject(this._objects[i2]) || object.isContainedWithinObject(this._objects[i2]) || this._objects[i2].isContainedWithinObject(object);
            if (isIntersecting) {
              newIdx = i2;
              break;
            }
          }
        } else {
          newIdx = idx + 1;
        }
        return newIdx;
      },
      moveTo: function(object, index2) {
        removeFromArray(this._objects, object);
        this._objects.splice(index2, 0, object);
        return this.renderOnAddRemove && this.requestRenderAll();
      },
      dispose: function() {
        if (this.isRendering) {
          fabric2.util.cancelAnimFrame(this.isRendering);
          this.isRendering = 0;
        }
        this.forEachObject(function(object) {
          object.dispose && object.dispose();
        });
        this._objects = [];
        if (this.backgroundImage && this.backgroundImage.dispose) {
          this.backgroundImage.dispose();
        }
        this.backgroundImage = null;
        if (this.overlayImage && this.overlayImage.dispose) {
          this.overlayImage.dispose();
        }
        this.overlayImage = null;
        this._iTextInstances = null;
        this.contextContainer = null;
        this.lowerCanvasEl.classList.remove("lower-canvas");
        this.lowerCanvasEl.style = this._originalCanvasStyle;
        delete this._originalCanvasStyle;
        this.lowerCanvasEl.setAttribute("width", this.width);
        this.lowerCanvasEl.setAttribute("height", this.height);
        fabric2.util.cleanUpJsdomNode(this.lowerCanvasEl);
        this.lowerCanvasEl = void 0;
        return this;
      },
      toString: function() {
        return "#<fabric.Canvas (" + this.complexity() + "): { objects: " + this._objects.length + " }>";
      }
    });
    extend(fabric2.StaticCanvas.prototype, fabric2.Observable);
    extend(fabric2.StaticCanvas.prototype, fabric2.Collection);
    extend(fabric2.StaticCanvas.prototype, fabric2.DataURLExporter);
    extend(fabric2.StaticCanvas, {
      EMPTY_JSON: '{"objects": [], "background": "white"}',
      supports: function(methodName) {
        var el = createCanvasElement();
        if (!el || !el.getContext) {
          return null;
        }
        var ctx = el.getContext("2d");
        if (!ctx) {
          return null;
        }
        switch (methodName) {
          case "setLineDash":
            return typeof ctx.setLineDash !== "undefined";
          default:
            return null;
        }
      }
    });
    fabric2.StaticCanvas.prototype.toJSON = fabric2.StaticCanvas.prototype.toObject;
    if (fabric2.isLikelyNode) {
      fabric2.StaticCanvas.prototype.createPNGStream = function() {
        var impl = getNodeCanvas(this.lowerCanvasEl);
        return impl && impl.createPNGStream();
      };
      fabric2.StaticCanvas.prototype.createJPEGStream = function(opts) {
        var impl = getNodeCanvas(this.lowerCanvasEl);
        return impl && impl.createJPEGStream(opts);
      };
    }
  })();
  fabric2.BaseBrush = fabric2.util.createClass({
    color: "rgb(0, 0, 0)",
    width: 1,
    shadow: null,
    strokeLineCap: "round",
    strokeLineJoin: "round",
    strokeMiterLimit: 10,
    strokeDashArray: null,
    limitedToCanvasSize: false,
    _setBrushStyles: function() {
      var ctx = this.canvas.contextTop;
      ctx.strokeStyle = this.color;
      ctx.lineWidth = this.width;
      ctx.lineCap = this.strokeLineCap;
      ctx.miterLimit = this.strokeMiterLimit;
      ctx.lineJoin = this.strokeLineJoin;
      ctx.setLineDash(this.strokeDashArray || []);
    },
    _saveAndTransform: function(ctx) {
      var v2 = this.canvas.viewportTransform;
      ctx.save();
      ctx.transform(v2[0], v2[1], v2[2], v2[3], v2[4], v2[5]);
    },
    _setShadow: function() {
      if (!this.shadow) {
        return;
      }
      var canvas = this.canvas, shadow = this.shadow, ctx = canvas.contextTop, zoom = canvas.getZoom();
      if (canvas && canvas._isRetinaScaling()) {
        zoom *= fabric2.devicePixelRatio;
      }
      ctx.shadowColor = shadow.color;
      ctx.shadowBlur = shadow.blur * zoom;
      ctx.shadowOffsetX = shadow.offsetX * zoom;
      ctx.shadowOffsetY = shadow.offsetY * zoom;
    },
    needsFullRender: function() {
      var color2 = new fabric2.Color(this.color);
      return color2.getAlpha() < 1 || !!this.shadow;
    },
    _resetShadow: function() {
      var ctx = this.canvas.contextTop;
      ctx.shadowColor = "";
      ctx.shadowBlur = ctx.shadowOffsetX = ctx.shadowOffsetY = 0;
    },
    _isOutSideCanvas: function(pointer) {
      return pointer.x < 0 || pointer.x > this.canvas.getWidth() || pointer.y < 0 || pointer.y > this.canvas.getHeight();
    }
  });
  (function() {
    fabric2.PencilBrush = fabric2.util.createClass(fabric2.BaseBrush, {
      decimate: 0.4,
      initialize: function(canvas) {
        this.canvas = canvas;
        this._points = [];
      },
      _drawSegment: function(ctx, p1, p2) {
        var midPoint = p1.midPointFrom(p2);
        ctx.quadraticCurveTo(p1.x, p1.y, midPoint.x, midPoint.y);
        return midPoint;
      },
      onMouseDown: function(pointer, options) {
        if (!this.canvas._isMainEvent(options.e)) {
          return;
        }
        this._prepareForDrawing(pointer);
        this._captureDrawingPath(pointer);
        this._render();
      },
      onMouseMove: function(pointer, options) {
        if (!this.canvas._isMainEvent(options.e)) {
          return;
        }
        if (this.limitedToCanvasSize === true && this._isOutSideCanvas(pointer)) {
          return;
        }
        if (this._captureDrawingPath(pointer) && this._points.length > 1) {
          if (this.needsFullRender()) {
            this.canvas.clearContext(this.canvas.contextTop);
            this._render();
          } else {
            var points = this._points, length = points.length, ctx = this.canvas.contextTop;
            this._saveAndTransform(ctx);
            if (this.oldEnd) {
              ctx.beginPath();
              ctx.moveTo(this.oldEnd.x, this.oldEnd.y);
            }
            this.oldEnd = this._drawSegment(ctx, points[length - 2], points[length - 1], true);
            ctx.stroke();
            ctx.restore();
          }
        }
      },
      onMouseUp: function(options) {
        if (!this.canvas._isMainEvent(options.e)) {
          return true;
        }
        this.oldEnd = void 0;
        this._finalizeAndAddPath();
        return false;
      },
      _prepareForDrawing: function(pointer) {
        var p2 = new fabric2.Point(pointer.x, pointer.y);
        this._reset();
        this._addPoint(p2);
        this.canvas.contextTop.moveTo(p2.x, p2.y);
      },
      _addPoint: function(point) {
        if (this._points.length > 1 && point.eq(this._points[this._points.length - 1])) {
          return false;
        }
        this._points.push(point);
        return true;
      },
      _reset: function() {
        this._points = [];
        this._setBrushStyles();
        this._setShadow();
      },
      _captureDrawingPath: function(pointer) {
        var pointerPoint = new fabric2.Point(pointer.x, pointer.y);
        return this._addPoint(pointerPoint);
      },
      _render: function() {
        var ctx = this.canvas.contextTop, i2, len, p1 = this._points[0], p2 = this._points[1];
        this._saveAndTransform(ctx);
        ctx.beginPath();
        if (this._points.length === 2 && p1.x === p2.x && p1.y === p2.y) {
          var width = this.width / 1e3;
          p1 = new fabric2.Point(p1.x, p1.y);
          p2 = new fabric2.Point(p2.x, p2.y);
          p1.x -= width;
          p2.x += width;
        }
        ctx.moveTo(p1.x, p1.y);
        for (i2 = 1, len = this._points.length; i2 < len; i2++) {
          this._drawSegment(ctx, p1, p2);
          p1 = this._points[i2];
          p2 = this._points[i2 + 1];
        }
        ctx.lineTo(p1.x, p1.y);
        ctx.stroke();
        ctx.restore();
      },
      convertPointsToSVGPath: function(points) {
        var correction = this.width / 1e3;
        return fabric2.util.getSmoothPathFromPoints(points, correction);
      },
      _isEmptySVGPath: function(pathData) {
        var pathString = fabric2.util.joinPath(pathData);
        return pathString === "M 0 0 Q 0 0 0 0 L 0 0";
      },
      createPath: function(pathData) {
        var path = new fabric2.Path(pathData, {
          fill: null,
          stroke: this.color,
          strokeWidth: this.width,
          strokeLineCap: this.strokeLineCap,
          strokeMiterLimit: this.strokeMiterLimit,
          strokeLineJoin: this.strokeLineJoin,
          strokeDashArray: this.strokeDashArray
        });
        if (this.shadow) {
          this.shadow.affectStroke = true;
          path.shadow = new fabric2.Shadow(this.shadow);
        }
        return path;
      },
      decimatePoints: function(points, distance) {
        if (points.length <= 2) {
          return points;
        }
        var zoom = this.canvas.getZoom(), adjustedDistance = Math.pow(distance / zoom, 2), i2, l2 = points.length - 1, lastPoint = points[0], newPoints = [lastPoint], cDistance;
        for (i2 = 1; i2 < l2 - 1; i2++) {
          cDistance = Math.pow(lastPoint.x - points[i2].x, 2) + Math.pow(lastPoint.y - points[i2].y, 2);
          if (cDistance >= adjustedDistance) {
            lastPoint = points[i2];
            newPoints.push(lastPoint);
          }
        }
        newPoints.push(points[l2]);
        return newPoints;
      },
      _finalizeAndAddPath: function() {
        var ctx = this.canvas.contextTop;
        ctx.closePath();
        if (this.decimate) {
          this._points = this.decimatePoints(this._points, this.decimate);
        }
        var pathData = this.convertPointsToSVGPath(this._points);
        if (this._isEmptySVGPath(pathData)) {
          this.canvas.requestRenderAll();
          return;
        }
        var path = this.createPath(pathData);
        this.canvas.clearContext(this.canvas.contextTop);
        this.canvas.fire("before:path:created", { path });
        this.canvas.add(path);
        this.canvas.requestRenderAll();
        path.setCoords();
        this._resetShadow();
        this.canvas.fire("path:created", { path });
      }
    });
  })();
  fabric2.CircleBrush = fabric2.util.createClass(fabric2.BaseBrush, {
    width: 10,
    initialize: function(canvas) {
      this.canvas = canvas;
      this.points = [];
    },
    drawDot: function(pointer) {
      var point = this.addPoint(pointer), ctx = this.canvas.contextTop;
      this._saveAndTransform(ctx);
      this.dot(ctx, point);
      ctx.restore();
    },
    dot: function(ctx, point) {
      ctx.fillStyle = point.fill;
      ctx.beginPath();
      ctx.arc(point.x, point.y, point.radius, 0, Math.PI * 2, false);
      ctx.closePath();
      ctx.fill();
    },
    onMouseDown: function(pointer) {
      this.points.length = 0;
      this.canvas.clearContext(this.canvas.contextTop);
      this._setShadow();
      this.drawDot(pointer);
    },
    _render: function() {
      var ctx = this.canvas.contextTop, i2, len, points = this.points;
      this._saveAndTransform(ctx);
      for (i2 = 0, len = points.length; i2 < len; i2++) {
        this.dot(ctx, points[i2]);
      }
      ctx.restore();
    },
    onMouseMove: function(pointer) {
      if (this.limitedToCanvasSize === true && this._isOutSideCanvas(pointer)) {
        return;
      }
      if (this.needsFullRender()) {
        this.canvas.clearContext(this.canvas.contextTop);
        this.addPoint(pointer);
        this._render();
      } else {
        this.drawDot(pointer);
      }
    },
    onMouseUp: function() {
      var originalRenderOnAddRemove = this.canvas.renderOnAddRemove, i2, len;
      this.canvas.renderOnAddRemove = false;
      var circles = [];
      for (i2 = 0, len = this.points.length; i2 < len; i2++) {
        var point = this.points[i2], circle = new fabric2.Circle({
          radius: point.radius,
          left: point.x,
          top: point.y,
          originX: "center",
          originY: "center",
          fill: point.fill
        });
        this.shadow && (circle.shadow = new fabric2.Shadow(this.shadow));
        circles.push(circle);
      }
      var group = new fabric2.Group(circles);
      group.canvas = this.canvas;
      this.canvas.fire("before:path:created", { path: group });
      this.canvas.add(group);
      this.canvas.fire("path:created", { path: group });
      this.canvas.clearContext(this.canvas.contextTop);
      this._resetShadow();
      this.canvas.renderOnAddRemove = originalRenderOnAddRemove;
      this.canvas.requestRenderAll();
    },
    addPoint: function(pointer) {
      var pointerPoint = new fabric2.Point(pointer.x, pointer.y), circleRadius = fabric2.util.getRandomInt(Math.max(0, this.width - 20), this.width + 20) / 2, circleColor2 = new fabric2.Color(this.color).setAlpha(fabric2.util.getRandomInt(0, 100) / 100).toRgba();
      pointerPoint.radius = circleRadius;
      pointerPoint.fill = circleColor2;
      this.points.push(pointerPoint);
      return pointerPoint;
    }
  });
  fabric2.SprayBrush = fabric2.util.createClass(fabric2.BaseBrush, {
    width: 10,
    density: 20,
    dotWidth: 1,
    dotWidthVariance: 1,
    randomOpacity: false,
    optimizeOverlapping: true,
    initialize: function(canvas) {
      this.canvas = canvas;
      this.sprayChunks = [];
    },
    onMouseDown: function(pointer) {
      this.sprayChunks.length = 0;
      this.canvas.clearContext(this.canvas.contextTop);
      this._setShadow();
      this.addSprayChunk(pointer);
      this.render(this.sprayChunkPoints);
    },
    onMouseMove: function(pointer) {
      if (this.limitedToCanvasSize === true && this._isOutSideCanvas(pointer)) {
        return;
      }
      this.addSprayChunk(pointer);
      this.render(this.sprayChunkPoints);
    },
    onMouseUp: function() {
      var originalRenderOnAddRemove = this.canvas.renderOnAddRemove;
      this.canvas.renderOnAddRemove = false;
      var rects = [];
      for (var i2 = 0, ilen = this.sprayChunks.length; i2 < ilen; i2++) {
        var sprayChunk = this.sprayChunks[i2];
        for (var j2 = 0, jlen = sprayChunk.length; j2 < jlen; j2++) {
          var rect = new fabric2.Rect({
            width: sprayChunk[j2].width,
            height: sprayChunk[j2].width,
            left: sprayChunk[j2].x + 1,
            top: sprayChunk[j2].y + 1,
            originX: "center",
            originY: "center",
            fill: this.color
          });
          rects.push(rect);
        }
      }
      if (this.optimizeOverlapping) {
        rects = this._getOptimizedRects(rects);
      }
      var group = new fabric2.Group(rects);
      this.shadow && group.set("shadow", new fabric2.Shadow(this.shadow));
      this.canvas.fire("before:path:created", { path: group });
      this.canvas.add(group);
      this.canvas.fire("path:created", { path: group });
      this.canvas.clearContext(this.canvas.contextTop);
      this._resetShadow();
      this.canvas.renderOnAddRemove = originalRenderOnAddRemove;
      this.canvas.requestRenderAll();
    },
    _getOptimizedRects: function(rects) {
      var uniqueRects = {}, key, i2, len;
      for (i2 = 0, len = rects.length; i2 < len; i2++) {
        key = rects[i2].left + "" + rects[i2].top;
        if (!uniqueRects[key]) {
          uniqueRects[key] = rects[i2];
        }
      }
      var uniqueRectsArray = [];
      for (key in uniqueRects) {
        uniqueRectsArray.push(uniqueRects[key]);
      }
      return uniqueRectsArray;
    },
    render: function(sprayChunk) {
      var ctx = this.canvas.contextTop, i2, len;
      ctx.fillStyle = this.color;
      this._saveAndTransform(ctx);
      for (i2 = 0, len = sprayChunk.length; i2 < len; i2++) {
        var point = sprayChunk[i2];
        if (typeof point.opacity !== "undefined") {
          ctx.globalAlpha = point.opacity;
        }
        ctx.fillRect(point.x, point.y, point.width, point.width);
      }
      ctx.restore();
    },
    _render: function() {
      var ctx = this.canvas.contextTop, i2, ilen;
      ctx.fillStyle = this.color;
      this._saveAndTransform(ctx);
      for (i2 = 0, ilen = this.sprayChunks.length; i2 < ilen; i2++) {
        this.render(this.sprayChunks[i2]);
      }
      ctx.restore();
    },
    addSprayChunk: function(pointer) {
      this.sprayChunkPoints = [];
      var x2, y2, width, radius = this.width / 2, i2;
      for (i2 = 0; i2 < this.density; i2++) {
        x2 = fabric2.util.getRandomInt(pointer.x - radius, pointer.x + radius);
        y2 = fabric2.util.getRandomInt(pointer.y - radius, pointer.y + radius);
        if (this.dotWidthVariance) {
          width = fabric2.util.getRandomInt(Math.max(1, this.dotWidth - this.dotWidthVariance), this.dotWidth + this.dotWidthVariance);
        } else {
          width = this.dotWidth;
        }
        var point = new fabric2.Point(x2, y2);
        point.width = width;
        if (this.randomOpacity) {
          point.opacity = fabric2.util.getRandomInt(0, 100) / 100;
        }
        this.sprayChunkPoints.push(point);
      }
      this.sprayChunks.push(this.sprayChunkPoints);
    }
  });
  fabric2.PatternBrush = fabric2.util.createClass(fabric2.PencilBrush, {
    getPatternSrc: function() {
      var dotWidth = 20, dotDistance = 5, patternCanvas = fabric2.util.createCanvasElement(), patternCtx = patternCanvas.getContext("2d");
      patternCanvas.width = patternCanvas.height = dotWidth + dotDistance;
      patternCtx.fillStyle = this.color;
      patternCtx.beginPath();
      patternCtx.arc(dotWidth / 2, dotWidth / 2, dotWidth / 2, 0, Math.PI * 2, false);
      patternCtx.closePath();
      patternCtx.fill();
      return patternCanvas;
    },
    getPatternSrcFunction: function() {
      return String(this.getPatternSrc).replace("this.color", '"' + this.color + '"');
    },
    getPattern: function() {
      return this.canvas.contextTop.createPattern(this.source || this.getPatternSrc(), "repeat");
    },
    _setBrushStyles: function() {
      this.callSuper("_setBrushStyles");
      this.canvas.contextTop.strokeStyle = this.getPattern();
    },
    createPath: function(pathData) {
      var path = this.callSuper("createPath", pathData), topLeft = path._getLeftTopCoords().scalarAdd(path.strokeWidth / 2);
      path.stroke = new fabric2.Pattern({
        source: this.source || this.getPatternSrcFunction(),
        offsetX: -topLeft.x,
        offsetY: -topLeft.y
      });
      return path;
    }
  });
  (function() {
    var getPointer = fabric2.util.getPointer, degreesToRadians = fabric2.util.degreesToRadians, isTouchEvent2 = fabric2.util.isTouchEvent;
    fabric2.Canvas = fabric2.util.createClass(fabric2.StaticCanvas, {
      initialize: function(el, options) {
        options || (options = {});
        this.renderAndResetBound = this.renderAndReset.bind(this);
        this.requestRenderAllBound = this.requestRenderAll.bind(this);
        this._initStatic(el, options);
        this._initInteractive();
        this._createCacheCanvas();
      },
      uniformScaling: true,
      uniScaleKey: "shiftKey",
      centeredScaling: false,
      centeredRotation: false,
      centeredKey: "altKey",
      altActionKey: "shiftKey",
      interactive: true,
      selection: true,
      selectionKey: "shiftKey",
      altSelectionKey: null,
      selectionColor: "rgba(100, 100, 255, 0.3)",
      selectionDashArray: [],
      selectionBorderColor: "rgba(255, 255, 255, 0.3)",
      selectionLineWidth: 1,
      selectionFullyContained: false,
      hoverCursor: "move",
      moveCursor: "move",
      defaultCursor: "default",
      freeDrawingCursor: "crosshair",
      rotationCursor: "crosshair",
      notAllowedCursor: "not-allowed",
      containerClass: "canvas-container",
      perPixelTargetFind: false,
      targetFindTolerance: 0,
      skipTargetFind: false,
      isDrawingMode: false,
      preserveObjectStacking: false,
      snapAngle: 0,
      snapThreshold: null,
      stopContextMenu: false,
      fireRightClick: false,
      fireMiddleClick: false,
      targets: [],
      _hoveredTarget: null,
      _hoveredTargets: [],
      _initInteractive: function() {
        this._currentTransform = null;
        this._groupSelector = null;
        this._initWrapperElement();
        this._createUpperCanvas();
        this._initEventListeners();
        this._initRetinaScaling();
        this.freeDrawingBrush = fabric2.PencilBrush && new fabric2.PencilBrush(this);
        this.calcOffset();
      },
      _chooseObjectsToRender: function() {
        var activeObjects = this.getActiveObjects(), object, objsToRender, activeGroupObjects;
        if (activeObjects.length > 0 && !this.preserveObjectStacking) {
          objsToRender = [];
          activeGroupObjects = [];
          for (var i2 = 0, length = this._objects.length; i2 < length; i2++) {
            object = this._objects[i2];
            if (activeObjects.indexOf(object) === -1) {
              objsToRender.push(object);
            } else {
              activeGroupObjects.push(object);
            }
          }
          if (activeObjects.length > 1) {
            this._activeObject._objects = activeGroupObjects;
          }
          objsToRender.push.apply(objsToRender, activeGroupObjects);
        } else {
          objsToRender = this._objects;
        }
        return objsToRender;
      },
      renderAll: function() {
        if (this.contextTopDirty && !this._groupSelector && !this.isDrawingMode) {
          this.clearContext(this.contextTop);
          this.contextTopDirty = false;
        }
        if (this.hasLostContext) {
          this.renderTopLayer(this.contextTop);
        }
        var canvasToDrawOn = this.contextContainer;
        this.renderCanvas(canvasToDrawOn, this._chooseObjectsToRender());
        return this;
      },
      renderTopLayer: function(ctx) {
        ctx.save();
        if (this.isDrawingMode && this._isCurrentlyDrawing) {
          this.freeDrawingBrush && this.freeDrawingBrush._render();
          this.contextTopDirty = true;
        }
        if (this.selection && this._groupSelector) {
          this._drawSelection(ctx);
          this.contextTopDirty = true;
        }
        ctx.restore();
      },
      renderTop: function() {
        var ctx = this.contextTop;
        this.clearContext(ctx);
        this.renderTopLayer(ctx);
        this.fire("after:render");
        return this;
      },
      _normalizePointer: function(object, pointer) {
        var m2 = object.calcTransformMatrix(), invertedM = fabric2.util.invertTransform(m2), vptPointer = this.restorePointerVpt(pointer);
        return fabric2.util.transformPoint(vptPointer, invertedM);
      },
      isTargetTransparent: function(target, x2, y2) {
        if (target.shouldCache() && target._cacheCanvas && target !== this._activeObject) {
          var normalizedPointer = this._normalizePointer(target, { x: x2, y: y2 }), targetRelativeX = Math.max(target.cacheTranslationX + normalizedPointer.x * target.zoomX, 0), targetRelativeY = Math.max(target.cacheTranslationY + normalizedPointer.y * target.zoomY, 0);
          var isTransparent = fabric2.util.isTransparent(target._cacheContext, Math.round(targetRelativeX), Math.round(targetRelativeY), this.targetFindTolerance);
          return isTransparent;
        }
        var ctx = this.contextCache, originalColor = target.selectionBackgroundColor, v2 = this.viewportTransform;
        target.selectionBackgroundColor = "";
        this.clearContext(ctx);
        ctx.save();
        ctx.transform(v2[0], v2[1], v2[2], v2[3], v2[4], v2[5]);
        target.render(ctx);
        ctx.restore();
        target.selectionBackgroundColor = originalColor;
        var isTransparent = fabric2.util.isTransparent(ctx, x2, y2, this.targetFindTolerance);
        return isTransparent;
      },
      _isSelectionKeyPressed: function(e2) {
        var selectionKeyPressed = false;
        if (Object.prototype.toString.call(this.selectionKey) === "[object Array]") {
          selectionKeyPressed = !!this.selectionKey.find(function(key) {
            return e2[key] === true;
          });
        } else {
          selectionKeyPressed = e2[this.selectionKey];
        }
        return selectionKeyPressed;
      },
      _shouldClearSelection: function(e2, target) {
        var activeObjects = this.getActiveObjects(), activeObject = this._activeObject;
        return !target || target && activeObject && activeObjects.length > 1 && activeObjects.indexOf(target) === -1 && activeObject !== target && !this._isSelectionKeyPressed(e2) || target && !target.evented || target && !target.selectable && activeObject && activeObject !== target;
      },
      _shouldCenterTransform: function(target, action, altKey) {
        if (!target) {
          return;
        }
        var centerTransform;
        if (action === "scale" || action === "scaleX" || action === "scaleY" || action === "resizing") {
          centerTransform = this.centeredScaling || target.centeredScaling;
        } else if (action === "rotate") {
          centerTransform = this.centeredRotation || target.centeredRotation;
        }
        return centerTransform ? !altKey : altKey;
      },
      _getOriginFromCorner: function(target, corner) {
        var origin = {
          x: target.originX,
          y: target.originY
        };
        if (corner === "ml" || corner === "tl" || corner === "bl") {
          origin.x = "right";
        } else if (corner === "mr" || corner === "tr" || corner === "br") {
          origin.x = "left";
        }
        if (corner === "tl" || corner === "mt" || corner === "tr") {
          origin.y = "bottom";
        } else if (corner === "bl" || corner === "mb" || corner === "br") {
          origin.y = "top";
        }
        return origin;
      },
      _getActionFromCorner: function(alreadySelected, corner, e2, target) {
        if (!corner || !alreadySelected) {
          return "drag";
        }
        var control = target.controls[corner];
        return control.getActionName(e2, control, target);
      },
      _setupCurrentTransform: function(e2, target, alreadySelected) {
        if (!target) {
          return;
        }
        var pointer = this.getPointer(e2), corner = target.__corner, control = target.controls[corner], actionHandler = alreadySelected && corner ? control.getActionHandler(e2, target, control) : fabric2.controlsUtils.dragHandler, action = this._getActionFromCorner(alreadySelected, corner, e2, target), origin = this._getOriginFromCorner(target, corner), altKey = e2[this.centeredKey], transform2 = {
          target,
          action,
          actionHandler,
          corner,
          scaleX: target.scaleX,
          scaleY: target.scaleY,
          skewX: target.skewX,
          skewY: target.skewY,
          offsetX: pointer.x - target.left,
          offsetY: pointer.y - target.top,
          originX: origin.x,
          originY: origin.y,
          ex: pointer.x,
          ey: pointer.y,
          lastX: pointer.x,
          lastY: pointer.y,
          theta: degreesToRadians(target.angle),
          width: target.width * target.scaleX,
          shiftKey: e2.shiftKey,
          altKey,
          original: fabric2.util.saveObjectTransform(target)
        };
        if (this._shouldCenterTransform(target, action, altKey)) {
          transform2.originX = "center";
          transform2.originY = "center";
        }
        transform2.original.originX = origin.x;
        transform2.original.originY = origin.y;
        this._currentTransform = transform2;
        this._beforeTransform(e2);
      },
      setCursor: function(value) {
        this.upperCanvasEl.style.cursor = value;
      },
      _drawSelection: function(ctx) {
        var selector = this._groupSelector, viewportStart = new fabric2.Point(selector.ex, selector.ey), start = fabric2.util.transformPoint(viewportStart, this.viewportTransform), viewportExtent = new fabric2.Point(selector.ex + selector.left, selector.ey + selector.top), extent = fabric2.util.transformPoint(viewportExtent, this.viewportTransform), minX = Math.min(start.x, extent.x), minY = Math.min(start.y, extent.y), maxX = Math.max(start.x, extent.x), maxY = Math.max(start.y, extent.y), strokeOffset = this.selectionLineWidth / 2;
        if (this.selectionColor) {
          ctx.fillStyle = this.selectionColor;
          ctx.fillRect(minX, minY, maxX - minX, maxY - minY);
        }
        if (!this.selectionLineWidth || !this.selectionBorderColor) {
          return;
        }
        ctx.lineWidth = this.selectionLineWidth;
        ctx.strokeStyle = this.selectionBorderColor;
        minX += strokeOffset;
        minY += strokeOffset;
        maxX -= strokeOffset;
        maxY -= strokeOffset;
        fabric2.Object.prototype._setLineDash.call(this, ctx, this.selectionDashArray);
        ctx.strokeRect(minX, minY, maxX - minX, maxY - minY);
      },
      findTarget: function(e2, skipGroup) {
        if (this.skipTargetFind) {
          return;
        }
        var ignoreZoom = true, pointer = this.getPointer(e2, ignoreZoom), activeObject = this._activeObject, aObjects = this.getActiveObjects(), activeTarget, activeTargetSubs, isTouch2 = isTouchEvent2(e2), shouldLookForActive = aObjects.length > 1 && !skipGroup || aObjects.length === 1;
        this.targets = [];
        if (shouldLookForActive && activeObject._findTargetCorner(pointer, isTouch2)) {
          return activeObject;
        }
        if (aObjects.length > 1 && !skipGroup && activeObject === this._searchPossibleTargets([activeObject], pointer)) {
          return activeObject;
        }
        if (aObjects.length === 1 && activeObject === this._searchPossibleTargets([activeObject], pointer)) {
          if (!this.preserveObjectStacking) {
            return activeObject;
          } else {
            activeTarget = activeObject;
            activeTargetSubs = this.targets;
            this.targets = [];
          }
        }
        var target = this._searchPossibleTargets(this._objects, pointer);
        if (e2[this.altSelectionKey] && target && activeTarget && target !== activeTarget) {
          target = activeTarget;
          this.targets = activeTargetSubs;
        }
        return target;
      },
      _checkTarget: function(pointer, obj, globalPointer) {
        if (obj && obj.visible && obj.evented && obj.containsPoint(pointer)) {
          if ((this.perPixelTargetFind || obj.perPixelTargetFind) && !obj.isEditing) {
            var isTransparent = this.isTargetTransparent(obj, globalPointer.x, globalPointer.y);
            if (!isTransparent) {
              return true;
            }
          } else {
            return true;
          }
        }
      },
      _searchPossibleTargets: function(objects, pointer) {
        var target, i2 = objects.length, subTarget;
        while (i2--) {
          var objToCheck = objects[i2];
          var pointerToUse = objToCheck.group ? this._normalizePointer(objToCheck.group, pointer) : pointer;
          if (this._checkTarget(pointerToUse, objToCheck, pointer)) {
            target = objects[i2];
            if (target.subTargetCheck && target instanceof fabric2.Group) {
              subTarget = this._searchPossibleTargets(target._objects, pointer);
              subTarget && this.targets.push(subTarget);
            }
            break;
          }
        }
        return target;
      },
      restorePointerVpt: function(pointer) {
        return fabric2.util.transformPoint(pointer, fabric2.util.invertTransform(this.viewportTransform));
      },
      getPointer: function(e2, ignoreZoom) {
        if (this._absolutePointer && !ignoreZoom) {
          return this._absolutePointer;
        }
        if (this._pointer && ignoreZoom) {
          return this._pointer;
        }
        var pointer = getPointer(e2), upperCanvasEl = this.upperCanvasEl, bounds = upperCanvasEl.getBoundingClientRect(), boundsWidth = bounds.width || 0, boundsHeight = bounds.height || 0, cssScale;
        if (!boundsWidth || !boundsHeight) {
          if ("top" in bounds && "bottom" in bounds) {
            boundsHeight = Math.abs(bounds.top - bounds.bottom);
          }
          if ("right" in bounds && "left" in bounds) {
            boundsWidth = Math.abs(bounds.right - bounds.left);
          }
        }
        this.calcOffset();
        pointer.x = pointer.x - this._offset.left;
        pointer.y = pointer.y - this._offset.top;
        if (!ignoreZoom) {
          pointer = this.restorePointerVpt(pointer);
        }
        var retinaScaling = this.getRetinaScaling();
        if (retinaScaling !== 1) {
          pointer.x /= retinaScaling;
          pointer.y /= retinaScaling;
        }
        if (boundsWidth === 0 || boundsHeight === 0) {
          cssScale = { width: 1, height: 1 };
        } else {
          cssScale = {
            width: upperCanvasEl.width / boundsWidth,
            height: upperCanvasEl.height / boundsHeight
          };
        }
        return {
          x: pointer.x * cssScale.width,
          y: pointer.y * cssScale.height
        };
      },
      _createUpperCanvas: function() {
        var lowerCanvasClass = this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/, ""), lowerCanvasEl = this.lowerCanvasEl, upperCanvasEl = this.upperCanvasEl;
        if (upperCanvasEl) {
          upperCanvasEl.className = "";
        } else {
          upperCanvasEl = this._createCanvasElement();
          this.upperCanvasEl = upperCanvasEl;
        }
        fabric2.util.addClass(upperCanvasEl, "upper-canvas " + lowerCanvasClass);
        this.wrapperEl.appendChild(upperCanvasEl);
        this._copyCanvasStyle(lowerCanvasEl, upperCanvasEl);
        this._applyCanvasStyle(upperCanvasEl);
        this.contextTop = upperCanvasEl.getContext("2d");
      },
      _createCacheCanvas: function() {
        this.cacheCanvasEl = this._createCanvasElement();
        this.cacheCanvasEl.setAttribute("width", this.width);
        this.cacheCanvasEl.setAttribute("height", this.height);
        this.contextCache = this.cacheCanvasEl.getContext("2d");
      },
      _initWrapperElement: function() {
        this.wrapperEl = fabric2.util.wrapElement(this.lowerCanvasEl, "div", {
          "class": this.containerClass
        });
        fabric2.util.setStyle(this.wrapperEl, {
          width: this.width + "px",
          height: this.height + "px",
          position: "relative"
        });
        fabric2.util.makeElementUnselectable(this.wrapperEl);
      },
      _applyCanvasStyle: function(element) {
        var width = this.width || element.width, height = this.height || element.height;
        fabric2.util.setStyle(element, {
          position: "absolute",
          width: width + "px",
          height: height + "px",
          left: 0,
          top: 0,
          "touch-action": this.allowTouchScrolling ? "manipulation" : "none",
          "-ms-touch-action": this.allowTouchScrolling ? "manipulation" : "none"
        });
        element.width = width;
        element.height = height;
        fabric2.util.makeElementUnselectable(element);
      },
      _copyCanvasStyle: function(fromEl, toEl) {
        toEl.style.cssText = fromEl.style.cssText;
      },
      getSelectionContext: function() {
        return this.contextTop;
      },
      getSelectionElement: function() {
        return this.upperCanvasEl;
      },
      getActiveObject: function() {
        return this._activeObject;
      },
      getActiveObjects: function() {
        var active = this._activeObject;
        if (active) {
          if (active.type === "activeSelection" && active._objects) {
            return active._objects.slice(0);
          } else {
            return [active];
          }
        }
        return [];
      },
      _onObjectRemoved: function(obj) {
        if (obj === this._activeObject) {
          this.fire("before:selection:cleared", { target: obj });
          this._discardActiveObject();
          this.fire("selection:cleared", { target: obj });
          obj.fire("deselected");
        }
        if (obj === this._hoveredTarget) {
          this._hoveredTarget = null;
          this._hoveredTargets = [];
        }
        this.callSuper("_onObjectRemoved", obj);
      },
      _fireSelectionEvents: function(oldObjects, e2) {
        var somethingChanged = false, objects = this.getActiveObjects(), added = [], removed = [];
        oldObjects.forEach(function(oldObject) {
          if (objects.indexOf(oldObject) === -1) {
            somethingChanged = true;
            oldObject.fire("deselected", {
              e: e2,
              target: oldObject
            });
            removed.push(oldObject);
          }
        });
        objects.forEach(function(object) {
          if (oldObjects.indexOf(object) === -1) {
            somethingChanged = true;
            object.fire("selected", {
              e: e2,
              target: object
            });
            added.push(object);
          }
        });
        if (oldObjects.length > 0 && objects.length > 0) {
          somethingChanged && this.fire("selection:updated", {
            e: e2,
            selected: added,
            deselected: removed,
            updated: added[0] || removed[0],
            target: this._activeObject
          });
        } else if (objects.length > 0) {
          this.fire("selection:created", {
            e: e2,
            selected: added,
            target: this._activeObject
          });
        } else if (oldObjects.length > 0) {
          this.fire("selection:cleared", {
            e: e2,
            deselected: removed
          });
        }
      },
      setActiveObject: function(object, e2) {
        var currentActives = this.getActiveObjects();
        this._setActiveObject(object, e2);
        this._fireSelectionEvents(currentActives, e2);
        return this;
      },
      _setActiveObject: function(object, e2) {
        if (this._activeObject === object) {
          return false;
        }
        if (!this._discardActiveObject(e2, object)) {
          return false;
        }
        if (object.onSelect({ e: e2 })) {
          return false;
        }
        this._activeObject = object;
        return true;
      },
      _discardActiveObject: function(e2, object) {
        var obj = this._activeObject;
        if (obj) {
          if (obj.onDeselect({ e: e2, object })) {
            return false;
          }
          this._activeObject = null;
        }
        return true;
      },
      discardActiveObject: function(e2) {
        var currentActives = this.getActiveObjects(), activeObject = this.getActiveObject();
        if (currentActives.length) {
          this.fire("before:selection:cleared", { target: activeObject, e: e2 });
        }
        this._discardActiveObject(e2);
        this._fireSelectionEvents(currentActives, e2);
        return this;
      },
      dispose: function() {
        var wrapper = this.wrapperEl;
        this.removeListeners();
        wrapper.removeChild(this.upperCanvasEl);
        wrapper.removeChild(this.lowerCanvasEl);
        this.contextCache = null;
        this.contextTop = null;
        ["upperCanvasEl", "cacheCanvasEl"].forEach(function(element) {
          fabric2.util.cleanUpJsdomNode(this[element]);
          this[element] = void 0;
        }.bind(this));
        if (wrapper.parentNode) {
          wrapper.parentNode.replaceChild(this.lowerCanvasEl, this.wrapperEl);
        }
        delete this.wrapperEl;
        fabric2.StaticCanvas.prototype.dispose.call(this);
        return this;
      },
      clear: function() {
        this.discardActiveObject();
        this.clearContext(this.contextTop);
        return this.callSuper("clear");
      },
      drawControls: function(ctx) {
        var activeObject = this._activeObject;
        if (activeObject) {
          activeObject._renderControls(ctx);
        }
      },
      _toObject: function(instance, methodName, propertiesToInclude) {
        var originalProperties = this._realizeGroupTransformOnObject(instance), object = this.callSuper("_toObject", instance, methodName, propertiesToInclude);
        this._unwindGroupTransformOnObject(instance, originalProperties);
        return object;
      },
      _realizeGroupTransformOnObject: function(instance) {
        if (instance.group && instance.group.type === "activeSelection" && this._activeObject === instance.group) {
          var layoutProps = ["angle", "flipX", "flipY", "left", "scaleX", "scaleY", "skewX", "skewY", "top"];
          var originalValues = {};
          layoutProps.forEach(function(prop2) {
            originalValues[prop2] = instance[prop2];
          });
          fabric2.util.addTransformToObject(instance, this._activeObject.calcOwnMatrix());
          return originalValues;
        } else {
          return null;
        }
      },
      _unwindGroupTransformOnObject: function(instance, originalValues) {
        if (originalValues) {
          instance.set(originalValues);
        }
      },
      _setSVGObject: function(markup, instance, reviver) {
        var originalProperties = this._realizeGroupTransformOnObject(instance);
        this.callSuper("_setSVGObject", markup, instance, reviver);
        this._unwindGroupTransformOnObject(instance, originalProperties);
      },
      setViewportTransform: function(vpt) {
        if (this.renderOnAddRemove && this._activeObject && this._activeObject.isEditing) {
          this._activeObject.clearContextTop();
        }
        fabric2.StaticCanvas.prototype.setViewportTransform.call(this, vpt);
      }
    });
    for (var prop in fabric2.StaticCanvas) {
      if (prop !== "prototype") {
        fabric2.Canvas[prop] = fabric2.StaticCanvas[prop];
      }
    }
  })();
  (function() {
    var addListener = fabric2.util.addListener, removeListener = fabric2.util.removeListener, RIGHT_CLICK = 3, MIDDLE_CLICK = 2, LEFT_CLICK = 1, addEventOptions = { passive: false };
    function checkClick(e2, value) {
      return e2.button && e2.button === value - 1;
    }
    fabric2.util.object.extend(fabric2.Canvas.prototype, {
      mainTouchId: null,
      _initEventListeners: function() {
        this.removeListeners();
        this._bindEvents();
        this.addOrRemove(addListener, "add");
      },
      _getEventPrefix: function() {
        return this.enablePointerEvents ? "pointer" : "mouse";
      },
      addOrRemove: function(functor, eventjsFunctor) {
        var canvasElement = this.upperCanvasEl, eventTypePrefix = this._getEventPrefix();
        functor(fabric2.window, "resize", this._onResize);
        functor(canvasElement, eventTypePrefix + "down", this._onMouseDown);
        functor(canvasElement, eventTypePrefix + "move", this._onMouseMove, addEventOptions);
        functor(canvasElement, eventTypePrefix + "out", this._onMouseOut);
        functor(canvasElement, eventTypePrefix + "enter", this._onMouseEnter);
        functor(canvasElement, "wheel", this._onMouseWheel);
        functor(canvasElement, "contextmenu", this._onContextMenu);
        functor(canvasElement, "dblclick", this._onDoubleClick);
        functor(canvasElement, "dragover", this._onDragOver);
        functor(canvasElement, "dragenter", this._onDragEnter);
        functor(canvasElement, "dragleave", this._onDragLeave);
        functor(canvasElement, "drop", this._onDrop);
        if (!this.enablePointerEvents) {
          functor(canvasElement, "touchstart", this._onTouchStart, addEventOptions);
        }
        if (typeof eventjs !== "undefined" && eventjsFunctor in eventjs) {
          eventjs[eventjsFunctor](canvasElement, "gesture", this._onGesture);
          eventjs[eventjsFunctor](canvasElement, "drag", this._onDrag);
          eventjs[eventjsFunctor](canvasElement, "orientation", this._onOrientationChange);
          eventjs[eventjsFunctor](canvasElement, "shake", this._onShake);
          eventjs[eventjsFunctor](canvasElement, "longpress", this._onLongPress);
        }
      },
      removeListeners: function() {
        this.addOrRemove(removeListener, "remove");
        var eventTypePrefix = this._getEventPrefix();
        removeListener(fabric2.document, eventTypePrefix + "up", this._onMouseUp);
        removeListener(fabric2.document, "touchend", this._onTouchEnd, addEventOptions);
        removeListener(fabric2.document, eventTypePrefix + "move", this._onMouseMove, addEventOptions);
        removeListener(fabric2.document, "touchmove", this._onMouseMove, addEventOptions);
      },
      _bindEvents: function() {
        if (this.eventsBound) {
          return;
        }
        this._onMouseDown = this._onMouseDown.bind(this);
        this._onTouchStart = this._onTouchStart.bind(this);
        this._onMouseMove = this._onMouseMove.bind(this);
        this._onMouseUp = this._onMouseUp.bind(this);
        this._onTouchEnd = this._onTouchEnd.bind(this);
        this._onResize = this._onResize.bind(this);
        this._onGesture = this._onGesture.bind(this);
        this._onDrag = this._onDrag.bind(this);
        this._onShake = this._onShake.bind(this);
        this._onLongPress = this._onLongPress.bind(this);
        this._onOrientationChange = this._onOrientationChange.bind(this);
        this._onMouseWheel = this._onMouseWheel.bind(this);
        this._onMouseOut = this._onMouseOut.bind(this);
        this._onMouseEnter = this._onMouseEnter.bind(this);
        this._onContextMenu = this._onContextMenu.bind(this);
        this._onDoubleClick = this._onDoubleClick.bind(this);
        this._onDragOver = this._onDragOver.bind(this);
        this._onDragEnter = this._simpleEventHandler.bind(this, "dragenter");
        this._onDragLeave = this._simpleEventHandler.bind(this, "dragleave");
        this._onDrop = this._simpleEventHandler.bind(this, "drop");
        this.eventsBound = true;
      },
      _onGesture: function(e2, self2) {
        this.__onTransformGesture && this.__onTransformGesture(e2, self2);
      },
      _onDrag: function(e2, self2) {
        this.__onDrag && this.__onDrag(e2, self2);
      },
      _onMouseWheel: function(e2) {
        this.__onMouseWheel(e2);
      },
      _onMouseOut: function(e2) {
        var target = this._hoveredTarget;
        this.fire("mouse:out", { target, e: e2 });
        this._hoveredTarget = null;
        target && target.fire("mouseout", { e: e2 });
        var _this = this;
        this._hoveredTargets.forEach(function(_target) {
          _this.fire("mouse:out", { target, e: e2 });
          _target && target.fire("mouseout", { e: e2 });
        });
        this._hoveredTargets = [];
        if (this._iTextInstances) {
          this._iTextInstances.forEach(function(obj) {
            if (obj.isEditing) {
              obj.hiddenTextarea.focus();
            }
          });
        }
      },
      _onMouseEnter: function(e2) {
        if (!this._currentTransform && !this.findTarget(e2)) {
          this.fire("mouse:over", { target: null, e: e2 });
          this._hoveredTarget = null;
          this._hoveredTargets = [];
        }
      },
      _onOrientationChange: function(e2, self2) {
        this.__onOrientationChange && this.__onOrientationChange(e2, self2);
      },
      _onShake: function(e2, self2) {
        this.__onShake && this.__onShake(e2, self2);
      },
      _onLongPress: function(e2, self2) {
        this.__onLongPress && this.__onLongPress(e2, self2);
      },
      _onDragOver: function(e2) {
        e2.preventDefault();
        var target = this._simpleEventHandler("dragover", e2);
        this._fireEnterLeaveEvents(target, e2);
      },
      _onContextMenu: function(e2) {
        if (this.stopContextMenu) {
          e2.stopPropagation();
          e2.preventDefault();
        }
        return false;
      },
      _onDoubleClick: function(e2) {
        this._cacheTransformEventData(e2);
        this._handleEvent(e2, "dblclick");
        this._resetTransformEventData(e2);
      },
      getPointerId: function(evt) {
        var changedTouches = evt.changedTouches;
        if (changedTouches) {
          return changedTouches[0] && changedTouches[0].identifier;
        }
        if (this.enablePointerEvents) {
          return evt.pointerId;
        }
        return -1;
      },
      _isMainEvent: function(evt) {
        if (evt.isPrimary === true) {
          return true;
        }
        if (evt.isPrimary === false) {
          return false;
        }
        if (evt.type === "touchend" && evt.touches.length === 0) {
          return true;
        }
        if (evt.changedTouches) {
          return evt.changedTouches[0].identifier === this.mainTouchId;
        }
        return true;
      },
      _onTouchStart: function(e2) {
        e2.preventDefault();
        if (this.mainTouchId === null) {
          this.mainTouchId = this.getPointerId(e2);
        }
        this.__onMouseDown(e2);
        this._resetTransformEventData();
        var canvasElement = this.upperCanvasEl, eventTypePrefix = this._getEventPrefix();
        addListener(fabric2.document, "touchend", this._onTouchEnd, addEventOptions);
        addListener(fabric2.document, "touchmove", this._onMouseMove, addEventOptions);
        removeListener(canvasElement, eventTypePrefix + "down", this._onMouseDown);
      },
      _onMouseDown: function(e2) {
        this.__onMouseDown(e2);
        this._resetTransformEventData();
        var canvasElement = this.upperCanvasEl, eventTypePrefix = this._getEventPrefix();
        removeListener(canvasElement, eventTypePrefix + "move", this._onMouseMove, addEventOptions);
        addListener(fabric2.document, eventTypePrefix + "up", this._onMouseUp);
        addListener(fabric2.document, eventTypePrefix + "move", this._onMouseMove, addEventOptions);
      },
      _onTouchEnd: function(e2) {
        if (e2.touches.length > 0) {
          return;
        }
        this.__onMouseUp(e2);
        this._resetTransformEventData();
        this.mainTouchId = null;
        var eventTypePrefix = this._getEventPrefix();
        removeListener(fabric2.document, "touchend", this._onTouchEnd, addEventOptions);
        removeListener(fabric2.document, "touchmove", this._onMouseMove, addEventOptions);
        var _this = this;
        if (this._willAddMouseDown) {
          clearTimeout(this._willAddMouseDown);
        }
        this._willAddMouseDown = setTimeout(function() {
          addListener(_this.upperCanvasEl, eventTypePrefix + "down", _this._onMouseDown);
          _this._willAddMouseDown = 0;
        }, 400);
      },
      _onMouseUp: function(e2) {
        this.__onMouseUp(e2);
        this._resetTransformEventData();
        var canvasElement = this.upperCanvasEl, eventTypePrefix = this._getEventPrefix();
        if (this._isMainEvent(e2)) {
          removeListener(fabric2.document, eventTypePrefix + "up", this._onMouseUp);
          removeListener(fabric2.document, eventTypePrefix + "move", this._onMouseMove, addEventOptions);
          addListener(canvasElement, eventTypePrefix + "move", this._onMouseMove, addEventOptions);
        }
      },
      _onMouseMove: function(e2) {
        !this.allowTouchScrolling && e2.preventDefault && e2.preventDefault();
        this.__onMouseMove(e2);
      },
      _onResize: function() {
        this.calcOffset();
      },
      _shouldRender: function(target) {
        var activeObject = this._activeObject;
        if (!!activeObject !== !!target || activeObject && target && activeObject !== target) {
          return true;
        } else if (activeObject && activeObject.isEditing) {
          return false;
        }
        return false;
      },
      __onMouseUp: function(e2) {
        var target, transform2 = this._currentTransform, groupSelector = this._groupSelector, shouldRender = false, isClick = !groupSelector || groupSelector.left === 0 && groupSelector.top === 0;
        this._cacheTransformEventData(e2);
        target = this._target;
        this._handleEvent(e2, "up:before");
        if (checkClick(e2, RIGHT_CLICK)) {
          if (this.fireRightClick) {
            this._handleEvent(e2, "up", RIGHT_CLICK, isClick);
          }
          return;
        }
        if (checkClick(e2, MIDDLE_CLICK)) {
          if (this.fireMiddleClick) {
            this._handleEvent(e2, "up", MIDDLE_CLICK, isClick);
          }
          this._resetTransformEventData();
          return;
        }
        if (this.isDrawingMode && this._isCurrentlyDrawing) {
          this._onMouseUpInDrawingMode(e2);
          return;
        }
        if (!this._isMainEvent(e2)) {
          return;
        }
        if (transform2) {
          this._finalizeCurrentTransform(e2);
          shouldRender = transform2.actionPerformed;
        }
        if (!isClick) {
          var targetWasActive = target === this._activeObject;
          this._maybeGroupObjects(e2);
          if (!shouldRender) {
            shouldRender = this._shouldRender(target) || !targetWasActive && target === this._activeObject;
          }
        }
        if (target) {
          if (target.selectable && target !== this._activeObject && target.activeOn === "up") {
            this.setActiveObject(target, e2);
            shouldRender = true;
          } else {
            var corner = target._findTargetCorner(this.getPointer(e2, true), fabric2.util.isTouchEvent(e2));
            var control = target.controls[corner], mouseUpHandler = control && control.getMouseUpHandler(e2, target, control);
            if (mouseUpHandler) {
              var pointer = this.getPointer(e2);
              mouseUpHandler(e2, transform2, pointer.x, pointer.y);
            }
          }
          target.isMoving = false;
        }
        this._setCursorFromEvent(e2, target);
        this._handleEvent(e2, "up", LEFT_CLICK, isClick);
        this._groupSelector = null;
        this._currentTransform = null;
        target && (target.__corner = 0);
        if (shouldRender) {
          this.requestRenderAll();
        } else if (!isClick) {
          this.renderTop();
        }
      },
      _simpleEventHandler: function(eventType, e2) {
        var target = this.findTarget(e2), targets = this.targets, options = {
          e: e2,
          target,
          subTargets: targets
        };
        this.fire(eventType, options);
        target && target.fire(eventType, options);
        if (!targets) {
          return target;
        }
        for (var i2 = 0; i2 < targets.length; i2++) {
          targets[i2].fire(eventType, options);
        }
        return target;
      },
      _handleEvent: function(e2, eventType, button, isClick) {
        var target = this._target, targets = this.targets || [], options = {
          e: e2,
          target,
          subTargets: targets,
          button: button || LEFT_CLICK,
          isClick: isClick || false,
          pointer: this._pointer,
          absolutePointer: this._absolutePointer,
          transform: this._currentTransform
        };
        if (eventType === "up") {
          options.currentTarget = this.findTarget(e2);
          options.currentSubTargets = this.targets;
        }
        this.fire("mouse:" + eventType, options);
        target && target.fire("mouse" + eventType, options);
        for (var i2 = 0; i2 < targets.length; i2++) {
          targets[i2].fire("mouse" + eventType, options);
        }
      },
      _finalizeCurrentTransform: function(e2) {
        var transform2 = this._currentTransform, target = transform2.target, eventName, options = {
          e: e2,
          target,
          transform: transform2,
          action: transform2.action
        };
        if (target._scaling) {
          target._scaling = false;
        }
        target.setCoords();
        if (transform2.actionPerformed || this.stateful && target.hasStateChanged()) {
          if (transform2.actionPerformed) {
            eventName = this._addEventOptions(options, transform2);
            this._fire(eventName, options);
          }
          this._fire("modified", options);
        }
      },
      _addEventOptions: function(options, transform2) {
        var eventName, by;
        switch (transform2.action) {
          case "scaleX":
            eventName = "scaled";
            by = "x";
            break;
          case "scaleY":
            eventName = "scaled";
            by = "y";
            break;
          case "skewX":
            eventName = "skewed";
            by = "x";
            break;
          case "skewY":
            eventName = "skewed";
            by = "y";
            break;
          case "scale":
            eventName = "scaled";
            by = "equally";
            break;
          case "rotate":
            eventName = "rotated";
            break;
          case "drag":
            eventName = "moved";
            break;
        }
        options.by = by;
        return eventName;
      },
      _onMouseDownInDrawingMode: function(e2) {
        this._isCurrentlyDrawing = true;
        if (this.getActiveObject()) {
          this.discardActiveObject(e2).requestRenderAll();
        }
        var pointer = this.getPointer(e2);
        this.freeDrawingBrush.onMouseDown(pointer, { e: e2, pointer });
        this._handleEvent(e2, "down");
      },
      _onMouseMoveInDrawingMode: function(e2) {
        if (this._isCurrentlyDrawing) {
          var pointer = this.getPointer(e2);
          this.freeDrawingBrush.onMouseMove(pointer, { e: e2, pointer });
        }
        this.setCursor(this.freeDrawingCursor);
        this._handleEvent(e2, "move");
      },
      _onMouseUpInDrawingMode: function(e2) {
        var pointer = this.getPointer(e2);
        this._isCurrentlyDrawing = this.freeDrawingBrush.onMouseUp({ e: e2, pointer });
        this._handleEvent(e2, "up");
      },
      __onMouseDown: function(e2) {
        this._cacheTransformEventData(e2);
        this._handleEvent(e2, "down:before");
        var target = this._target;
        if (checkClick(e2, RIGHT_CLICK)) {
          if (this.fireRightClick) {
            this._handleEvent(e2, "down", RIGHT_CLICK);
          }
          return;
        }
        if (checkClick(e2, MIDDLE_CLICK)) {
          if (this.fireMiddleClick) {
            this._handleEvent(e2, "down", MIDDLE_CLICK);
          }
          return;
        }
        if (this.isDrawingMode) {
          this._onMouseDownInDrawingMode(e2);
          return;
        }
        if (!this._isMainEvent(e2)) {
          return;
        }
        if (this._currentTransform) {
          return;
        }
        var pointer = this._pointer;
        this._previousPointer = pointer;
        var shouldRender = this._shouldRender(target), shouldGroup = this._shouldGroup(e2, target);
        if (this._shouldClearSelection(e2, target)) {
          this.discardActiveObject(e2);
        } else if (shouldGroup) {
          this._handleGrouping(e2, target);
          target = this._activeObject;
        }
        if (this.selection && (!target || !target.selectable && !target.isEditing && target !== this._activeObject)) {
          this._groupSelector = {
            ex: this._absolutePointer.x,
            ey: this._absolutePointer.y,
            top: 0,
            left: 0
          };
        }
        if (target) {
          var alreadySelected = target === this._activeObject;
          if (target.selectable && target.activeOn === "down") {
            this.setActiveObject(target, e2);
          }
          var corner = target._findTargetCorner(this.getPointer(e2, true), fabric2.util.isTouchEvent(e2));
          target.__corner = corner;
          if (target === this._activeObject && (corner || !shouldGroup)) {
            this._setupCurrentTransform(e2, target, alreadySelected);
            var control = target.controls[corner], pointer = this.getPointer(e2), mouseDownHandler = control && control.getMouseDownHandler(e2, target, control);
            if (mouseDownHandler) {
              mouseDownHandler(e2, this._currentTransform, pointer.x, pointer.y);
            }
          }
        }
        this._handleEvent(e2, "down");
        (shouldRender || shouldGroup) && this.requestRenderAll();
      },
      _resetTransformEventData: function() {
        this._target = null;
        this._pointer = null;
        this._absolutePointer = null;
      },
      _cacheTransformEventData: function(e2) {
        this._resetTransformEventData();
        this._pointer = this.getPointer(e2, true);
        this._absolutePointer = this.restorePointerVpt(this._pointer);
        this._target = this._currentTransform ? this._currentTransform.target : this.findTarget(e2) || null;
      },
      _beforeTransform: function(e2) {
        var t2 = this._currentTransform;
        this.stateful && t2.target.saveState();
        this.fire("before:transform", {
          e: e2,
          transform: t2
        });
      },
      __onMouseMove: function(e2) {
        this._handleEvent(e2, "move:before");
        this._cacheTransformEventData(e2);
        var target, pointer;
        if (this.isDrawingMode) {
          this._onMouseMoveInDrawingMode(e2);
          return;
        }
        if (!this._isMainEvent(e2)) {
          return;
        }
        var groupSelector = this._groupSelector;
        if (groupSelector) {
          pointer = this._absolutePointer;
          groupSelector.left = pointer.x - groupSelector.ex;
          groupSelector.top = pointer.y - groupSelector.ey;
          this.renderTop();
        } else if (!this._currentTransform) {
          target = this.findTarget(e2) || null;
          this._setCursorFromEvent(e2, target);
          this._fireOverOutEvents(target, e2);
        } else {
          this._transformObject(e2);
        }
        this._handleEvent(e2, "move");
        this._resetTransformEventData();
      },
      _fireOverOutEvents: function(target, e2) {
        var _hoveredTarget = this._hoveredTarget, _hoveredTargets = this._hoveredTargets, targets = this.targets, length = Math.max(_hoveredTargets.length, targets.length);
        this.fireSyntheticInOutEvents(target, e2, {
          oldTarget: _hoveredTarget,
          evtOut: "mouseout",
          canvasEvtOut: "mouse:out",
          evtIn: "mouseover",
          canvasEvtIn: "mouse:over"
        });
        for (var i2 = 0; i2 < length; i2++) {
          this.fireSyntheticInOutEvents(targets[i2], e2, {
            oldTarget: _hoveredTargets[i2],
            evtOut: "mouseout",
            evtIn: "mouseover"
          });
        }
        this._hoveredTarget = target;
        this._hoveredTargets = this.targets.concat();
      },
      _fireEnterLeaveEvents: function(target, e2) {
        var _draggedoverTarget = this._draggedoverTarget, _hoveredTargets = this._hoveredTargets, targets = this.targets, length = Math.max(_hoveredTargets.length, targets.length);
        this.fireSyntheticInOutEvents(target, e2, {
          oldTarget: _draggedoverTarget,
          evtOut: "dragleave",
          evtIn: "dragenter"
        });
        for (var i2 = 0; i2 < length; i2++) {
          this.fireSyntheticInOutEvents(targets[i2], e2, {
            oldTarget: _hoveredTargets[i2],
            evtOut: "dragleave",
            evtIn: "dragenter"
          });
        }
        this._draggedoverTarget = target;
      },
      fireSyntheticInOutEvents: function(target, e2, config) {
        var inOpt, outOpt, oldTarget = config.oldTarget, outFires, inFires, targetChanged = oldTarget !== target, canvasEvtIn = config.canvasEvtIn, canvasEvtOut = config.canvasEvtOut;
        if (targetChanged) {
          inOpt = { e: e2, target, previousTarget: oldTarget };
          outOpt = { e: e2, target: oldTarget, nextTarget: target };
        }
        inFires = target && targetChanged;
        outFires = oldTarget && targetChanged;
        if (outFires) {
          canvasEvtOut && this.fire(canvasEvtOut, outOpt);
          oldTarget.fire(config.evtOut, outOpt);
        }
        if (inFires) {
          canvasEvtIn && this.fire(canvasEvtIn, inOpt);
          target.fire(config.evtIn, inOpt);
        }
      },
      __onMouseWheel: function(e2) {
        this._cacheTransformEventData(e2);
        this._handleEvent(e2, "wheel");
        this._resetTransformEventData();
      },
      _transformObject: function(e2) {
        var pointer = this.getPointer(e2), transform2 = this._currentTransform;
        transform2.reset = false;
        transform2.shiftKey = e2.shiftKey;
        transform2.altKey = e2[this.centeredKey];
        this._performTransformAction(e2, transform2, pointer);
        transform2.actionPerformed && this.requestRenderAll();
      },
      _performTransformAction: function(e2, transform2, pointer) {
        var x2 = pointer.x, y2 = pointer.y, action = transform2.action, actionPerformed = false, actionHandler = transform2.actionHandler;
        if (actionHandler) {
          actionPerformed = actionHandler(e2, transform2, x2, y2);
        }
        if (action === "drag" && actionPerformed) {
          transform2.target.isMoving = true;
          this.setCursor(transform2.target.moveCursor || this.moveCursor);
        }
        transform2.actionPerformed = transform2.actionPerformed || actionPerformed;
      },
      _fire: fabric2.controlsUtils.fireEvent,
      _setCursorFromEvent: function(e2, target) {
        if (!target) {
          this.setCursor(this.defaultCursor);
          return false;
        }
        var hoverCursor = target.hoverCursor || this.hoverCursor, activeSelection = this._activeObject && this._activeObject.type === "activeSelection" ? this._activeObject : null, corner = (!activeSelection || !activeSelection.contains(target)) && target._findTargetCorner(this.getPointer(e2, true));
        if (!corner) {
          if (target.subTargetCheck) {
            this.targets.concat().reverse().map(function(_target) {
              hoverCursor = _target.hoverCursor || hoverCursor;
            });
          }
          this.setCursor(hoverCursor);
        } else {
          this.setCursor(this.getCornerCursor(corner, target, e2));
        }
      },
      getCornerCursor: function(corner, target, e2) {
        var control = target.controls[corner];
        return control.cursorStyleHandler(e2, control, target);
      }
    });
  })();
  (function() {
    var min = Math.min, max = Math.max;
    fabric2.util.object.extend(fabric2.Canvas.prototype, {
      _shouldGroup: function(e2, target) {
        var activeObject = this._activeObject;
        return activeObject && this._isSelectionKeyPressed(e2) && target && target.selectable && this.selection && (activeObject !== target || activeObject.type === "activeSelection") && !target.onSelect({ e: e2 });
      },
      _handleGrouping: function(e2, target) {
        var activeObject = this._activeObject;
        if (activeObject.__corner) {
          return;
        }
        if (target === activeObject) {
          target = this.findTarget(e2, true);
          if (!target || !target.selectable) {
            return;
          }
        }
        if (activeObject && activeObject.type === "activeSelection") {
          this._updateActiveSelection(target, e2);
        } else {
          this._createActiveSelection(target, e2);
        }
      },
      _updateActiveSelection: function(target, e2) {
        var activeSelection = this._activeObject, currentActiveObjects = activeSelection._objects.slice(0);
        if (activeSelection.contains(target)) {
          activeSelection.removeWithUpdate(target);
          this._hoveredTarget = target;
          this._hoveredTargets = this.targets.concat();
          if (activeSelection.size() === 1) {
            this._setActiveObject(activeSelection.item(0), e2);
          }
        } else {
          activeSelection.addWithUpdate(target);
          this._hoveredTarget = activeSelection;
          this._hoveredTargets = this.targets.concat();
        }
        this._fireSelectionEvents(currentActiveObjects, e2);
      },
      _createActiveSelection: function(target, e2) {
        var currentActives = this.getActiveObjects(), group = this._createGroup(target);
        this._hoveredTarget = group;
        this._setActiveObject(group, e2);
        this._fireSelectionEvents(currentActives, e2);
      },
      _createGroup: function(target) {
        var objects = this._objects, isActiveLower = objects.indexOf(this._activeObject) < objects.indexOf(target), groupObjects = isActiveLower ? [this._activeObject, target] : [target, this._activeObject];
        this._activeObject.isEditing && this._activeObject.exitEditing();
        return new fabric2.ActiveSelection(groupObjects, {
          canvas: this
        });
      },
      _groupSelectedObjects: function(e2) {
        var group = this._collectObjects(e2), aGroup;
        if (group.length === 1) {
          this.setActiveObject(group[0], e2);
        } else if (group.length > 1) {
          aGroup = new fabric2.ActiveSelection(group.reverse(), {
            canvas: this
          });
          this.setActiveObject(aGroup, e2);
        }
      },
      _collectObjects: function(e2) {
        var group = [], currentObject, x1 = this._groupSelector.ex, y1 = this._groupSelector.ey, x2 = x1 + this._groupSelector.left, y2 = y1 + this._groupSelector.top, selectionX1Y1 = new fabric2.Point(min(x1, x2), min(y1, y2)), selectionX2Y2 = new fabric2.Point(max(x1, x2), max(y1, y2)), allowIntersect = !this.selectionFullyContained, isClick = x1 === x2 && y1 === y2;
        for (var i2 = this._objects.length; i2--; ) {
          currentObject = this._objects[i2];
          if (!currentObject || !currentObject.selectable || !currentObject.visible) {
            continue;
          }
          if (allowIntersect && currentObject.intersectsWithRect(selectionX1Y1, selectionX2Y2, true) || currentObject.isContainedWithinRect(selectionX1Y1, selectionX2Y2, true) || allowIntersect && currentObject.containsPoint(selectionX1Y1, null, true) || allowIntersect && currentObject.containsPoint(selectionX2Y2, null, true)) {
            group.push(currentObject);
            if (isClick) {
              break;
            }
          }
        }
        if (group.length > 1) {
          group = group.filter(function(object) {
            return !object.onSelect({ e: e2 });
          });
        }
        return group;
      },
      _maybeGroupObjects: function(e2) {
        if (this.selection && this._groupSelector) {
          this._groupSelectedObjects(e2);
        }
        this.setCursor(this.defaultCursor);
        this._groupSelector = null;
      }
    });
  })();
  (function() {
    fabric2.util.object.extend(fabric2.StaticCanvas.prototype, {
      toDataURL: function(options) {
        options || (options = {});
        var format = options.format || "png", quality = options.quality || 1, multiplier = (options.multiplier || 1) * (options.enableRetinaScaling ? this.getRetinaScaling() : 1), canvasEl = this.toCanvasElement(multiplier, options);
        return fabric2.util.toDataURL(canvasEl, format, quality);
      },
      toCanvasElement: function(multiplier, cropping) {
        multiplier = multiplier || 1;
        cropping = cropping || {};
        var scaledWidth = (cropping.width || this.width) * multiplier, scaledHeight = (cropping.height || this.height) * multiplier, zoom = this.getZoom(), originalWidth = this.width, originalHeight = this.height, newZoom = zoom * multiplier, vp = this.viewportTransform, translateX = (vp[4] - (cropping.left || 0)) * multiplier, translateY = (vp[5] - (cropping.top || 0)) * multiplier, originalInteractive = this.interactive, newVp = [newZoom, 0, 0, newZoom, translateX, translateY], originalRetina = this.enableRetinaScaling, canvasEl = fabric2.util.createCanvasElement(), originalContextTop = this.contextTop;
        canvasEl.width = scaledWidth;
        canvasEl.height = scaledHeight;
        this.contextTop = null;
        this.enableRetinaScaling = false;
        this.interactive = false;
        this.viewportTransform = newVp;
        this.width = scaledWidth;
        this.height = scaledHeight;
        this.calcViewportBoundaries();
        this.renderCanvas(canvasEl.getContext("2d"), this._objects);
        this.viewportTransform = vp;
        this.width = originalWidth;
        this.height = originalHeight;
        this.calcViewportBoundaries();
        this.interactive = originalInteractive;
        this.enableRetinaScaling = originalRetina;
        this.contextTop = originalContextTop;
        return canvasEl;
      }
    });
  })();
  fabric2.util.object.extend(fabric2.StaticCanvas.prototype, {
    loadFromJSON: function(json, callback, reviver) {
      if (!json) {
        return;
      }
      var serialized = typeof json === "string" ? JSON.parse(json) : fabric2.util.object.clone(json);
      var _this = this, clipPath = serialized.clipPath, renderOnAddRemove = this.renderOnAddRemove;
      this.renderOnAddRemove = false;
      delete serialized.clipPath;
      this._enlivenObjects(serialized.objects, function(enlivenedObjects) {
        _this.clear();
        _this._setBgOverlay(serialized, function() {
          if (clipPath) {
            _this._enlivenObjects([clipPath], function(enlivenedCanvasClip) {
              _this.clipPath = enlivenedCanvasClip[0];
              _this.__setupCanvas.call(_this, serialized, enlivenedObjects, renderOnAddRemove, callback);
            });
          } else {
            _this.__setupCanvas.call(_this, serialized, enlivenedObjects, renderOnAddRemove, callback);
          }
        });
      }, reviver);
      return this;
    },
    __setupCanvas: function(serialized, enlivenedObjects, renderOnAddRemove, callback) {
      var _this = this;
      enlivenedObjects.forEach(function(obj, index2) {
        _this.insertAt(obj, index2);
      });
      this.renderOnAddRemove = renderOnAddRemove;
      delete serialized.objects;
      delete serialized.backgroundImage;
      delete serialized.overlayImage;
      delete serialized.background;
      delete serialized.overlay;
      this._setOptions(serialized);
      this.renderAll();
      callback && callback();
    },
    _setBgOverlay: function(serialized, callback) {
      var loaded = {
        backgroundColor: false,
        overlayColor: false,
        backgroundImage: false,
        overlayImage: false
      };
      if (!serialized.backgroundImage && !serialized.overlayImage && !serialized.background && !serialized.overlay) {
        callback && callback();
        return;
      }
      var cbIfLoaded = function() {
        if (loaded.backgroundImage && loaded.overlayImage && loaded.backgroundColor && loaded.overlayColor) {
          callback && callback();
        }
      };
      this.__setBgOverlay("backgroundImage", serialized.backgroundImage, loaded, cbIfLoaded);
      this.__setBgOverlay("overlayImage", serialized.overlayImage, loaded, cbIfLoaded);
      this.__setBgOverlay("backgroundColor", serialized.background, loaded, cbIfLoaded);
      this.__setBgOverlay("overlayColor", serialized.overlay, loaded, cbIfLoaded);
    },
    __setBgOverlay: function(property, value, loaded, callback) {
      var _this = this;
      if (!value) {
        loaded[property] = true;
        callback && callback();
        return;
      }
      if (property === "backgroundImage" || property === "overlayImage") {
        fabric2.util.enlivenObjects([value], function(enlivedObject) {
          _this[property] = enlivedObject[0];
          loaded[property] = true;
          callback && callback();
        });
      } else {
        this["set" + fabric2.util.string.capitalize(property, true)](value, function() {
          loaded[property] = true;
          callback && callback();
        });
      }
    },
    _enlivenObjects: function(objects, callback, reviver) {
      if (!objects || objects.length === 0) {
        callback && callback([]);
        return;
      }
      fabric2.util.enlivenObjects(objects, function(enlivenedObjects) {
        callback && callback(enlivenedObjects);
      }, null, reviver);
    },
    _toDataURL: function(format, callback) {
      this.clone(function(clone) {
        callback(clone.toDataURL(format));
      });
    },
    _toDataURLWithMultiplier: function(format, multiplier, callback) {
      this.clone(function(clone) {
        callback(clone.toDataURLWithMultiplier(format, multiplier));
      });
    },
    clone: function(callback, properties2) {
      var data = JSON.stringify(this.toJSON(properties2));
      this.cloneWithoutData(function(clone) {
        clone.loadFromJSON(data, function() {
          callback && callback(clone);
        });
      });
    },
    cloneWithoutData: function(callback) {
      var el = fabric2.util.createCanvasElement();
      el.width = this.width;
      el.height = this.height;
      var clone = new fabric2.Canvas(el);
      if (this.backgroundImage) {
        clone.setBackgroundImage(this.backgroundImage.src, function() {
          clone.renderAll();
          callback && callback(clone);
        });
        clone.backgroundImageOpacity = this.backgroundImageOpacity;
        clone.backgroundImageStretch = this.backgroundImageStretch;
      } else {
        callback && callback(clone);
      }
    }
  });
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {}), extend = fabric3.util.object.extend, clone = fabric3.util.object.clone, toFixed = fabric3.util.toFixed, capitalize2 = fabric3.util.string.capitalize, degreesToRadians = fabric3.util.degreesToRadians, objectCaching = !fabric3.isLikelyNode, ALIASING_LIMIT = 2;
    if (fabric3.Object) {
      return;
    }
    fabric3.Object = fabric3.util.createClass(fabric3.CommonMethods, {
      type: "object",
      originX: "left",
      originY: "top",
      top: 0,
      left: 0,
      width: 0,
      height: 0,
      scaleX: 1,
      scaleY: 1,
      flipX: false,
      flipY: false,
      opacity: 1,
      angle: 0,
      skewX: 0,
      skewY: 0,
      cornerSize: 13,
      touchCornerSize: 24,
      transparentCorners: true,
      hoverCursor: null,
      moveCursor: null,
      padding: 0,
      borderColor: "rgb(178,204,255)",
      borderDashArray: null,
      cornerColor: "rgb(178,204,255)",
      cornerStrokeColor: null,
      cornerStyle: "rect",
      cornerDashArray: null,
      centeredScaling: false,
      centeredRotation: true,
      fill: "rgb(0,0,0)",
      fillRule: "nonzero",
      globalCompositeOperation: "source-over",
      backgroundColor: "",
      selectionBackgroundColor: "",
      stroke: null,
      strokeWidth: 1,
      strokeDashArray: null,
      strokeDashOffset: 0,
      strokeLineCap: "butt",
      strokeLineJoin: "miter",
      strokeMiterLimit: 4,
      shadow: null,
      borderOpacityWhenMoving: 0.4,
      borderScaleFactor: 1,
      minScaleLimit: 0,
      selectable: true,
      evented: true,
      visible: true,
      hasControls: true,
      hasBorders: true,
      perPixelTargetFind: false,
      includeDefaultValues: true,
      lockMovementX: false,
      lockMovementY: false,
      lockRotation: false,
      lockScalingX: false,
      lockScalingY: false,
      lockSkewingX: false,
      lockSkewingY: false,
      lockScalingFlip: false,
      excludeFromExport: false,
      objectCaching,
      statefullCache: false,
      noScaleCache: true,
      strokeUniform: false,
      dirty: true,
      __corner: 0,
      paintFirst: "fill",
      activeOn: "down",
      stateProperties: "top left width height scaleX scaleY flipX flipY originX originY transformMatrix stroke strokeWidth strokeDashArray strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit angle opacity fill globalCompositeOperation shadow visible backgroundColor skewX skewY fillRule paintFirst clipPath strokeUniform".split(" "),
      cacheProperties: "fill stroke strokeWidth strokeDashArray width height paintFirst strokeUniform strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit backgroundColor clipPath".split(" "),
      colorProperties: "fill stroke backgroundColor".split(" "),
      clipPath: void 0,
      inverted: false,
      absolutePositioned: false,
      initialize: function(options) {
        if (options) {
          this.setOptions(options);
        }
      },
      _createCacheCanvas: function() {
        this._cacheProperties = {};
        this._cacheCanvas = fabric3.util.createCanvasElement();
        this._cacheContext = this._cacheCanvas.getContext("2d");
        this._updateCacheCanvas();
        this.dirty = true;
      },
      _limitCacheSize: function(dims) {
        var perfLimitSizeTotal = fabric3.perfLimitSizeTotal, width = dims.width, height = dims.height, max = fabric3.maxCacheSideLimit, min = fabric3.minCacheSideLimit;
        if (width <= max && height <= max && width * height <= perfLimitSizeTotal) {
          if (width < min) {
            dims.width = min;
          }
          if (height < min) {
            dims.height = min;
          }
          return dims;
        }
        var ar = width / height, limitedDims = fabric3.util.limitDimsByArea(ar, perfLimitSizeTotal), capValue = fabric3.util.capValue, x2 = capValue(min, limitedDims.x, max), y2 = capValue(min, limitedDims.y, max);
        if (width > x2) {
          dims.zoomX /= width / x2;
          dims.width = x2;
          dims.capped = true;
        }
        if (height > y2) {
          dims.zoomY /= height / y2;
          dims.height = y2;
          dims.capped = true;
        }
        return dims;
      },
      _getCacheCanvasDimensions: function() {
        var objectScale = this.getTotalObjectScaling(), dim = this._getTransformedDimensions(0, 0), neededX = dim.x * objectScale.scaleX / this.scaleX, neededY = dim.y * objectScale.scaleY / this.scaleY;
        return {
          width: neededX + ALIASING_LIMIT,
          height: neededY + ALIASING_LIMIT,
          zoomX: objectScale.scaleX,
          zoomY: objectScale.scaleY,
          x: neededX,
          y: neededY
        };
      },
      _updateCacheCanvas: function() {
        var targetCanvas = this.canvas;
        if (this.noScaleCache && targetCanvas && targetCanvas._currentTransform) {
          var target = targetCanvas._currentTransform.target, action = targetCanvas._currentTransform.action;
          if (this === target && action.slice && action.slice(0, 5) === "scale") {
            return false;
          }
        }
        var canvas = this._cacheCanvas, dims = this._limitCacheSize(this._getCacheCanvasDimensions()), minCacheSize = fabric3.minCacheSideLimit, width = dims.width, height = dims.height, drawingWidth, drawingHeight, zoomX = dims.zoomX, zoomY = dims.zoomY, dimensionsChanged = width !== this.cacheWidth || height !== this.cacheHeight, zoomChanged = this.zoomX !== zoomX || this.zoomY !== zoomY, shouldRedraw = dimensionsChanged || zoomChanged, additionalWidth = 0, additionalHeight = 0, shouldResizeCanvas = false;
        if (dimensionsChanged) {
          var canvasWidth = this._cacheCanvas.width, canvasHeight = this._cacheCanvas.height, sizeGrowing = width > canvasWidth || height > canvasHeight, sizeShrinking = (width < canvasWidth * 0.9 || height < canvasHeight * 0.9) && canvasWidth > minCacheSize && canvasHeight > minCacheSize;
          shouldResizeCanvas = sizeGrowing || sizeShrinking;
          if (sizeGrowing && !dims.capped && (width > minCacheSize || height > minCacheSize)) {
            additionalWidth = width * 0.1;
            additionalHeight = height * 0.1;
          }
        }
        if (this instanceof fabric3.Text && this.path) {
          shouldRedraw = true;
          shouldResizeCanvas = true;
          additionalWidth += this.getHeightOfLine(0) * this.zoomX;
          additionalHeight += this.getHeightOfLine(0) * this.zoomY;
        }
        if (shouldRedraw) {
          if (shouldResizeCanvas) {
            canvas.width = Math.ceil(width + additionalWidth);
            canvas.height = Math.ceil(height + additionalHeight);
          } else {
            this._cacheContext.setTransform(1, 0, 0, 1, 0, 0);
            this._cacheContext.clearRect(0, 0, canvas.width, canvas.height);
          }
          drawingWidth = dims.x / 2;
          drawingHeight = dims.y / 2;
          this.cacheTranslationX = Math.round(canvas.width / 2 - drawingWidth) + drawingWidth;
          this.cacheTranslationY = Math.round(canvas.height / 2 - drawingHeight) + drawingHeight;
          this.cacheWidth = width;
          this.cacheHeight = height;
          this._cacheContext.translate(this.cacheTranslationX, this.cacheTranslationY);
          this._cacheContext.scale(zoomX, zoomY);
          this.zoomX = zoomX;
          this.zoomY = zoomY;
          return true;
        }
        return false;
      },
      setOptions: function(options) {
        this._setOptions(options);
        this._initGradient(options.fill, "fill");
        this._initGradient(options.stroke, "stroke");
        this._initPattern(options.fill, "fill");
        this._initPattern(options.stroke, "stroke");
      },
      transform: function(ctx) {
        var needFullTransform = this.group && !this.group._transformDone || this.group && this.canvas && ctx === this.canvas.contextTop;
        var m2 = this.calcTransformMatrix(!needFullTransform);
        ctx.transform(m2[0], m2[1], m2[2], m2[3], m2[4], m2[5]);
      },
      toObject: function(propertiesToInclude) {
        var NUM_FRACTION_DIGITS = fabric3.Object.NUM_FRACTION_DIGITS, object = {
          type: this.type,
          version: fabric3.version,
          originX: this.originX,
          originY: this.originY,
          left: toFixed(this.left, NUM_FRACTION_DIGITS),
          top: toFixed(this.top, NUM_FRACTION_DIGITS),
          width: toFixed(this.width, NUM_FRACTION_DIGITS),
          height: toFixed(this.height, NUM_FRACTION_DIGITS),
          fill: this.fill && this.fill.toObject ? this.fill.toObject() : this.fill,
          stroke: this.stroke && this.stroke.toObject ? this.stroke.toObject() : this.stroke,
          strokeWidth: toFixed(this.strokeWidth, NUM_FRACTION_DIGITS),
          strokeDashArray: this.strokeDashArray ? this.strokeDashArray.concat() : this.strokeDashArray,
          strokeLineCap: this.strokeLineCap,
          strokeDashOffset: this.strokeDashOffset,
          strokeLineJoin: this.strokeLineJoin,
          strokeUniform: this.strokeUniform,
          strokeMiterLimit: toFixed(this.strokeMiterLimit, NUM_FRACTION_DIGITS),
          scaleX: toFixed(this.scaleX, NUM_FRACTION_DIGITS),
          scaleY: toFixed(this.scaleY, NUM_FRACTION_DIGITS),
          angle: toFixed(this.angle, NUM_FRACTION_DIGITS),
          flipX: this.flipX,
          flipY: this.flipY,
          opacity: toFixed(this.opacity, NUM_FRACTION_DIGITS),
          shadow: this.shadow && this.shadow.toObject ? this.shadow.toObject() : this.shadow,
          visible: this.visible,
          backgroundColor: this.backgroundColor,
          fillRule: this.fillRule,
          paintFirst: this.paintFirst,
          globalCompositeOperation: this.globalCompositeOperation,
          skewX: toFixed(this.skewX, NUM_FRACTION_DIGITS),
          skewY: toFixed(this.skewY, NUM_FRACTION_DIGITS)
        };
        if (this.clipPath && !this.clipPath.excludeFromExport) {
          object.clipPath = this.clipPath.toObject(propertiesToInclude);
          object.clipPath.inverted = this.clipPath.inverted;
          object.clipPath.absolutePositioned = this.clipPath.absolutePositioned;
        }
        fabric3.util.populateWithProperties(this, object, propertiesToInclude);
        if (!this.includeDefaultValues) {
          object = this._removeDefaultValues(object);
        }
        return object;
      },
      toDatalessObject: function(propertiesToInclude) {
        return this.toObject(propertiesToInclude);
      },
      _removeDefaultValues: function(object) {
        var prototype = fabric3.util.getKlass(object.type).prototype, stateProperties = prototype.stateProperties;
        stateProperties.forEach(function(prop) {
          if (prop === "left" || prop === "top") {
            return;
          }
          if (object[prop] === prototype[prop]) {
            delete object[prop];
          }
          var isArray = Object.prototype.toString.call(object[prop]) === "[object Array]" && Object.prototype.toString.call(prototype[prop]) === "[object Array]";
          if (isArray && object[prop].length === 0 && prototype[prop].length === 0) {
            delete object[prop];
          }
        });
        return object;
      },
      toString: function() {
        return "#<fabric." + capitalize2(this.type) + ">";
      },
      getObjectScaling: function() {
        if (!this.group) {
          return {
            scaleX: this.scaleX,
            scaleY: this.scaleY
          };
        }
        var options = fabric3.util.qrDecompose(this.calcTransformMatrix());
        return { scaleX: Math.abs(options.scaleX), scaleY: Math.abs(options.scaleY) };
      },
      getTotalObjectScaling: function() {
        var scale2 = this.getObjectScaling(), scaleX = scale2.scaleX, scaleY = scale2.scaleY;
        if (this.canvas) {
          var zoom = this.canvas.getZoom();
          var retina = this.canvas.getRetinaScaling();
          scaleX *= zoom * retina;
          scaleY *= zoom * retina;
        }
        return { scaleX, scaleY };
      },
      getObjectOpacity: function() {
        var opacity = this.opacity;
        if (this.group) {
          opacity *= this.group.getObjectOpacity();
        }
        return opacity;
      },
      _set: function(key, value) {
        var shouldConstrainValue = key === "scaleX" || key === "scaleY", isChanged = this[key] !== value, groupNeedsUpdate = false;
        if (shouldConstrainValue) {
          value = this._constrainScale(value);
        }
        if (key === "scaleX" && value < 0) {
          this.flipX = !this.flipX;
          value *= -1;
        } else if (key === "scaleY" && value < 0) {
          this.flipY = !this.flipY;
          value *= -1;
        } else if (key === "shadow" && value && !(value instanceof fabric3.Shadow)) {
          value = new fabric3.Shadow(value);
        } else if (key === "dirty" && this.group) {
          this.group.set("dirty", value);
        }
        this[key] = value;
        if (isChanged) {
          groupNeedsUpdate = this.group && this.group.isOnACache();
          if (this.cacheProperties.indexOf(key) > -1) {
            this.dirty = true;
            groupNeedsUpdate && this.group.set("dirty", true);
          } else if (groupNeedsUpdate && this.stateProperties.indexOf(key) > -1) {
            this.group.set("dirty", true);
          }
        }
        return this;
      },
      setOnGroup: function() {
      },
      getViewportTransform: function() {
        if (this.canvas && this.canvas.viewportTransform) {
          return this.canvas.viewportTransform;
        }
        return fabric3.iMatrix.concat();
      },
      isNotVisible: function() {
        return this.opacity === 0 || !this.width && !this.height && this.strokeWidth === 0 || !this.visible;
      },
      render: function(ctx) {
        if (this.isNotVisible()) {
          return;
        }
        if (this.canvas && this.canvas.skipOffscreen && !this.group && !this.isOnScreen()) {
          return;
        }
        ctx.save();
        this._setupCompositeOperation(ctx);
        this.drawSelectionBackground(ctx);
        this.transform(ctx);
        this._setOpacity(ctx);
        this._setShadow(ctx, this);
        if (this.shouldCache()) {
          this.renderCache();
          this.drawCacheOnCanvas(ctx);
        } else {
          this._removeCacheCanvas();
          this.dirty = false;
          this.drawObject(ctx);
          if (this.objectCaching && this.statefullCache) {
            this.saveState({ propertySet: "cacheProperties" });
          }
        }
        ctx.restore();
      },
      renderCache: function(options) {
        options = options || {};
        if (!this._cacheCanvas) {
          this._createCacheCanvas();
        }
        if (this.isCacheDirty()) {
          this.statefullCache && this.saveState({ propertySet: "cacheProperties" });
          this.drawObject(this._cacheContext, options.forClipping);
          this.dirty = false;
        }
      },
      _removeCacheCanvas: function() {
        this._cacheCanvas = null;
        this.cacheWidth = 0;
        this.cacheHeight = 0;
      },
      hasStroke: function() {
        return this.stroke && this.stroke !== "transparent" && this.strokeWidth !== 0;
      },
      hasFill: function() {
        return this.fill && this.fill !== "transparent";
      },
      needsItsOwnCache: function() {
        if (this.paintFirst === "stroke" && this.hasFill() && this.hasStroke() && typeof this.shadow === "object") {
          return true;
        }
        if (this.clipPath) {
          return true;
        }
        return false;
      },
      shouldCache: function() {
        this.ownCaching = this.needsItsOwnCache() || this.objectCaching && (!this.group || !this.group.isOnACache());
        return this.ownCaching;
      },
      willDrawShadow: function() {
        return !!this.shadow && (this.shadow.offsetX !== 0 || this.shadow.offsetY !== 0);
      },
      drawClipPathOnCache: function(ctx) {
        var path = this.clipPath;
        ctx.save();
        if (path.inverted) {
          ctx.globalCompositeOperation = "destination-out";
        } else {
          ctx.globalCompositeOperation = "destination-in";
        }
        if (path.absolutePositioned) {
          var m2 = fabric3.util.invertTransform(this.calcTransformMatrix());
          ctx.transform(m2[0], m2[1], m2[2], m2[3], m2[4], m2[5]);
        }
        path.transform(ctx);
        ctx.scale(1 / path.zoomX, 1 / path.zoomY);
        ctx.drawImage(path._cacheCanvas, -path.cacheTranslationX, -path.cacheTranslationY);
        ctx.restore();
      },
      drawObject: function(ctx, forClipping) {
        var originalFill = this.fill, originalStroke = this.stroke;
        if (forClipping) {
          this.fill = "black";
          this.stroke = "";
          this._setClippingProperties(ctx);
        } else {
          this._renderBackground(ctx);
        }
        this._render(ctx);
        this._drawClipPath(ctx);
        this.fill = originalFill;
        this.stroke = originalStroke;
      },
      _drawClipPath: function(ctx) {
        var path = this.clipPath;
        if (!path) {
          return;
        }
        path.canvas = this.canvas;
        path.shouldCache();
        path._transformDone = true;
        path.renderCache({ forClipping: true });
        this.drawClipPathOnCache(ctx);
      },
      drawCacheOnCanvas: function(ctx) {
        ctx.scale(1 / this.zoomX, 1 / this.zoomY);
        ctx.drawImage(this._cacheCanvas, -this.cacheTranslationX, -this.cacheTranslationY);
      },
      isCacheDirty: function(skipCanvas) {
        if (this.isNotVisible()) {
          return false;
        }
        if (this._cacheCanvas && !skipCanvas && this._updateCacheCanvas()) {
          return true;
        } else {
          if (this.dirty || this.clipPath && this.clipPath.absolutePositioned || this.statefullCache && this.hasStateChanged("cacheProperties")) {
            if (this._cacheCanvas && !skipCanvas) {
              var width = this.cacheWidth / this.zoomX;
              var height = this.cacheHeight / this.zoomY;
              this._cacheContext.clearRect(-width / 2, -height / 2, width, height);
            }
            return true;
          }
        }
        return false;
      },
      _renderBackground: function(ctx) {
        if (!this.backgroundColor) {
          return;
        }
        var dim = this._getNonTransformedDimensions();
        ctx.fillStyle = this.backgroundColor;
        ctx.fillRect(-dim.x / 2, -dim.y / 2, dim.x, dim.y);
        this._removeShadow(ctx);
      },
      _setOpacity: function(ctx) {
        if (this.group && !this.group._transformDone) {
          ctx.globalAlpha = this.getObjectOpacity();
        } else {
          ctx.globalAlpha *= this.opacity;
        }
      },
      _setStrokeStyles: function(ctx, decl) {
        var stroke = decl.stroke;
        if (stroke) {
          ctx.lineWidth = decl.strokeWidth;
          ctx.lineCap = decl.strokeLineCap;
          ctx.lineDashOffset = decl.strokeDashOffset;
          ctx.lineJoin = decl.strokeLineJoin;
          ctx.miterLimit = decl.strokeMiterLimit;
          if (stroke.toLive) {
            if (stroke.gradientUnits === "percentage" || stroke.gradientTransform || stroke.patternTransform) {
              this._applyPatternForTransformedGradient(ctx, stroke);
            } else {
              ctx.strokeStyle = stroke.toLive(ctx, this);
              this._applyPatternGradientTransform(ctx, stroke);
            }
          } else {
            ctx.strokeStyle = decl.stroke;
          }
        }
      },
      _setFillStyles: function(ctx, decl) {
        var fill2 = decl.fill;
        if (fill2) {
          if (fill2.toLive) {
            ctx.fillStyle = fill2.toLive(ctx, this);
            this._applyPatternGradientTransform(ctx, decl.fill);
          } else {
            ctx.fillStyle = fill2;
          }
        }
      },
      _setClippingProperties: function(ctx) {
        ctx.globalAlpha = 1;
        ctx.strokeStyle = "transparent";
        ctx.fillStyle = "#000000";
      },
      _setLineDash: function(ctx, dashArray) {
        if (!dashArray || dashArray.length === 0) {
          return;
        }
        if (1 & dashArray.length) {
          dashArray.push.apply(dashArray, dashArray);
        }
        ctx.setLineDash(dashArray);
      },
      _renderControls: function(ctx, styleOverride) {
        var vpt = this.getViewportTransform(), matrix = this.calcTransformMatrix(), options, drawBorders, drawControls;
        styleOverride = styleOverride || {};
        drawBorders = typeof styleOverride.hasBorders !== "undefined" ? styleOverride.hasBorders : this.hasBorders;
        drawControls = typeof styleOverride.hasControls !== "undefined" ? styleOverride.hasControls : this.hasControls;
        matrix = fabric3.util.multiplyTransformMatrices(vpt, matrix);
        options = fabric3.util.qrDecompose(matrix);
        ctx.save();
        ctx.translate(options.translateX, options.translateY);
        ctx.lineWidth = 1 * this.borderScaleFactor;
        if (!this.group) {
          ctx.globalAlpha = this.isMoving ? this.borderOpacityWhenMoving : 1;
        }
        ctx.rotate(degreesToRadians(options.angle));
        if (styleOverride.forActiveSelection || this.group) {
          drawBorders && this.drawBordersInGroup(ctx, options, styleOverride);
        } else {
          drawBorders && this.drawBorders(ctx, styleOverride);
        }
        drawControls && this.drawControls(ctx, styleOverride);
        ctx.restore();
      },
      _setShadow: function(ctx) {
        if (!this.shadow) {
          return;
        }
        var shadow = this.shadow, canvas = this.canvas, scaling, multX = canvas && canvas.viewportTransform[0] || 1, multY = canvas && canvas.viewportTransform[3] || 1;
        if (shadow.nonScaling) {
          scaling = { scaleX: 1, scaleY: 1 };
        } else {
          scaling = this.getObjectScaling();
        }
        if (canvas && canvas._isRetinaScaling()) {
          multX *= fabric3.devicePixelRatio;
          multY *= fabric3.devicePixelRatio;
        }
        ctx.shadowColor = shadow.color;
        ctx.shadowBlur = shadow.blur * fabric3.browserShadowBlurConstant * (multX + multY) * (scaling.scaleX + scaling.scaleY) / 4;
        ctx.shadowOffsetX = shadow.offsetX * multX * scaling.scaleX;
        ctx.shadowOffsetY = shadow.offsetY * multY * scaling.scaleY;
      },
      _removeShadow: function(ctx) {
        if (!this.shadow) {
          return;
        }
        ctx.shadowColor = "";
        ctx.shadowBlur = ctx.shadowOffsetX = ctx.shadowOffsetY = 0;
      },
      _applyPatternGradientTransform: function(ctx, filler) {
        if (!filler || !filler.toLive) {
          return { offsetX: 0, offsetY: 0 };
        }
        var t2 = filler.gradientTransform || filler.patternTransform;
        var offsetX = -this.width / 2 + filler.offsetX || 0, offsetY = -this.height / 2 + filler.offsetY || 0;
        if (filler.gradientUnits === "percentage") {
          ctx.transform(this.width, 0, 0, this.height, offsetX, offsetY);
        } else {
          ctx.transform(1, 0, 0, 1, offsetX, offsetY);
        }
        if (t2) {
          ctx.transform(t2[0], t2[1], t2[2], t2[3], t2[4], t2[5]);
        }
        return { offsetX, offsetY };
      },
      _renderPaintInOrder: function(ctx) {
        if (this.paintFirst === "stroke") {
          this._renderStroke(ctx);
          this._renderFill(ctx);
        } else {
          this._renderFill(ctx);
          this._renderStroke(ctx);
        }
      },
      _render: function() {
      },
      _renderFill: function(ctx) {
        if (!this.fill) {
          return;
        }
        ctx.save();
        this._setFillStyles(ctx, this);
        if (this.fillRule === "evenodd") {
          ctx.fill("evenodd");
        } else {
          ctx.fill();
        }
        ctx.restore();
      },
      _renderStroke: function(ctx) {
        if (!this.stroke || this.strokeWidth === 0) {
          return;
        }
        if (this.shadow && !this.shadow.affectStroke) {
          this._removeShadow(ctx);
        }
        ctx.save();
        if (this.strokeUniform && this.group) {
          var scaling = this.getObjectScaling();
          ctx.scale(1 / scaling.scaleX, 1 / scaling.scaleY);
        } else if (this.strokeUniform) {
          ctx.scale(1 / this.scaleX, 1 / this.scaleY);
        }
        this._setLineDash(ctx, this.strokeDashArray);
        this._setStrokeStyles(ctx, this);
        ctx.stroke();
        ctx.restore();
      },
      _applyPatternForTransformedGradient: function(ctx, filler) {
        var dims = this._limitCacheSize(this._getCacheCanvasDimensions()), pCanvas = fabric3.util.createCanvasElement(), pCtx, retinaScaling = this.canvas.getRetinaScaling(), width = dims.x / this.scaleX / retinaScaling, height = dims.y / this.scaleY / retinaScaling;
        pCanvas.width = width;
        pCanvas.height = height;
        pCtx = pCanvas.getContext("2d");
        pCtx.beginPath();
        pCtx.moveTo(0, 0);
        pCtx.lineTo(width, 0);
        pCtx.lineTo(width, height);
        pCtx.lineTo(0, height);
        pCtx.closePath();
        pCtx.translate(width / 2, height / 2);
        pCtx.scale(dims.zoomX / this.scaleX / retinaScaling, dims.zoomY / this.scaleY / retinaScaling);
        this._applyPatternGradientTransform(pCtx, filler);
        pCtx.fillStyle = filler.toLive(ctx);
        pCtx.fill();
        ctx.translate(-this.width / 2 - this.strokeWidth / 2, -this.height / 2 - this.strokeWidth / 2);
        ctx.scale(retinaScaling * this.scaleX / dims.zoomX, retinaScaling * this.scaleY / dims.zoomY);
        ctx.strokeStyle = pCtx.createPattern(pCanvas, "no-repeat");
      },
      _findCenterFromElement: function() {
        return { x: this.left + this.width / 2, y: this.top + this.height / 2 };
      },
      _assignTransformMatrixProps: function() {
        if (this.transformMatrix) {
          var options = fabric3.util.qrDecompose(this.transformMatrix);
          this.flipX = false;
          this.flipY = false;
          this.set("scaleX", options.scaleX);
          this.set("scaleY", options.scaleY);
          this.angle = options.angle;
          this.skewX = options.skewX;
          this.skewY = 0;
        }
      },
      _removeTransformMatrix: function(preserveAspectRatioOptions) {
        var center = this._findCenterFromElement();
        if (this.transformMatrix) {
          this._assignTransformMatrixProps();
          center = fabric3.util.transformPoint(center, this.transformMatrix);
        }
        this.transformMatrix = null;
        if (preserveAspectRatioOptions) {
          this.scaleX *= preserveAspectRatioOptions.scaleX;
          this.scaleY *= preserveAspectRatioOptions.scaleY;
          this.cropX = preserveAspectRatioOptions.cropX;
          this.cropY = preserveAspectRatioOptions.cropY;
          center.x += preserveAspectRatioOptions.offsetLeft;
          center.y += preserveAspectRatioOptions.offsetTop;
          this.width = preserveAspectRatioOptions.width;
          this.height = preserveAspectRatioOptions.height;
        }
        this.setPositionByOrigin(center, "center", "center");
      },
      clone: function(callback, propertiesToInclude) {
        var objectForm = this.toObject(propertiesToInclude);
        if (this.constructor.fromObject) {
          this.constructor.fromObject(objectForm, callback);
        } else {
          fabric3.Object._fromObject("Object", objectForm, callback);
        }
      },
      cloneAsImage: function(callback, options) {
        var canvasEl = this.toCanvasElement(options);
        if (callback) {
          callback(new fabric3.Image(canvasEl));
        }
        return this;
      },
      toCanvasElement: function(options) {
        options || (options = {});
        var utils = fabric3.util, origParams = utils.saveObjectTransform(this), originalGroup = this.group, originalShadow = this.shadow, abs = Math.abs, multiplier = (options.multiplier || 1) * (options.enableRetinaScaling ? fabric3.devicePixelRatio : 1);
        delete this.group;
        if (options.withoutTransform) {
          utils.resetObjectTransform(this);
        }
        if (options.withoutShadow) {
          this.shadow = null;
        }
        var el = fabric3.util.createCanvasElement(), boundingRect = this.getBoundingRect(true, true), shadow = this.shadow, scaling, shadowOffset = { x: 0, y: 0 }, shadowBlur, width, height;
        if (shadow) {
          shadowBlur = shadow.blur;
          if (shadow.nonScaling) {
            scaling = { scaleX: 1, scaleY: 1 };
          } else {
            scaling = this.getObjectScaling();
          }
          shadowOffset.x = 2 * Math.round(abs(shadow.offsetX) + shadowBlur) * abs(scaling.scaleX);
          shadowOffset.y = 2 * Math.round(abs(shadow.offsetY) + shadowBlur) * abs(scaling.scaleY);
        }
        width = boundingRect.width + shadowOffset.x;
        height = boundingRect.height + shadowOffset.y;
        el.width = Math.ceil(width);
        el.height = Math.ceil(height);
        var canvas = new fabric3.StaticCanvas(el, {
          enableRetinaScaling: false,
          renderOnAddRemove: false,
          skipOffscreen: false
        });
        if (options.format === "jpeg") {
          canvas.backgroundColor = "#fff";
        }
        this.setPositionByOrigin(new fabric3.Point(canvas.width / 2, canvas.height / 2), "center", "center");
        var originalCanvas = this.canvas;
        canvas.add(this);
        var canvasEl = canvas.toCanvasElement(multiplier || 1, options);
        this.shadow = originalShadow;
        this.set("canvas", originalCanvas);
        if (originalGroup) {
          this.group = originalGroup;
        }
        this.set(origParams).setCoords();
        canvas._objects = [];
        canvas.dispose();
        canvas = null;
        return canvasEl;
      },
      toDataURL: function(options) {
        options || (options = {});
        return fabric3.util.toDataURL(this.toCanvasElement(options), options.format || "png", options.quality || 1);
      },
      isType: function(type) {
        return this.type === type;
      },
      complexity: function() {
        return 1;
      },
      toJSON: function(propertiesToInclude) {
        return this.toObject(propertiesToInclude);
      },
      rotate: function(angle) {
        var shouldCenterOrigin = (this.originX !== "center" || this.originY !== "center") && this.centeredRotation;
        if (shouldCenterOrigin) {
          this._setOriginToCenter();
        }
        this.set("angle", angle);
        if (shouldCenterOrigin) {
          this._resetOrigin();
        }
        return this;
      },
      centerH: function() {
        this.canvas && this.canvas.centerObjectH(this);
        return this;
      },
      viewportCenterH: function() {
        this.canvas && this.canvas.viewportCenterObjectH(this);
        return this;
      },
      centerV: function() {
        this.canvas && this.canvas.centerObjectV(this);
        return this;
      },
      viewportCenterV: function() {
        this.canvas && this.canvas.viewportCenterObjectV(this);
        return this;
      },
      center: function() {
        this.canvas && this.canvas.centerObject(this);
        return this;
      },
      viewportCenter: function() {
        this.canvas && this.canvas.viewportCenterObject(this);
        return this;
      },
      getLocalPointer: function(e2, pointer) {
        pointer = pointer || this.canvas.getPointer(e2);
        var pClicked = new fabric3.Point(pointer.x, pointer.y), objectLeftTop = this._getLeftTopCoords();
        if (this.angle) {
          pClicked = fabric3.util.rotatePoint(pClicked, objectLeftTop, degreesToRadians(-this.angle));
        }
        return {
          x: pClicked.x - objectLeftTop.x,
          y: pClicked.y - objectLeftTop.y
        };
      },
      _setupCompositeOperation: function(ctx) {
        if (this.globalCompositeOperation) {
          ctx.globalCompositeOperation = this.globalCompositeOperation;
        }
      }
    });
    fabric3.util.createAccessors && fabric3.util.createAccessors(fabric3.Object);
    extend(fabric3.Object.prototype, fabric3.Observable);
    fabric3.Object.NUM_FRACTION_DIGITS = 2;
    fabric3.Object._fromObject = function(className, object, callback, extraParam) {
      var klass = fabric3[className];
      object = clone(object, true);
      fabric3.util.enlivenPatterns([object.fill, object.stroke], function(patterns) {
        if (typeof patterns[0] !== "undefined") {
          object.fill = patterns[0];
        }
        if (typeof patterns[1] !== "undefined") {
          object.stroke = patterns[1];
        }
        fabric3.util.enlivenObjects([object.clipPath], function(enlivedProps) {
          object.clipPath = enlivedProps[0];
          var instance = extraParam ? new klass(object[extraParam], object) : new klass(object);
          callback && callback(instance);
        });
      });
    };
    fabric3.Object.__uid = 0;
  })(exports2);
  (function() {
    var degreesToRadians = fabric2.util.degreesToRadians, originXOffset = {
      left: -0.5,
      center: 0,
      right: 0.5
    }, originYOffset = {
      top: -0.5,
      center: 0,
      bottom: 0.5
    };
    fabric2.util.object.extend(fabric2.Object.prototype, {
      translateToGivenOrigin: function(point, fromOriginX, fromOriginY, toOriginX, toOriginY) {
        var x2 = point.x, y2 = point.y, offsetX, offsetY, dim;
        if (typeof fromOriginX === "string") {
          fromOriginX = originXOffset[fromOriginX];
        } else {
          fromOriginX -= 0.5;
        }
        if (typeof toOriginX === "string") {
          toOriginX = originXOffset[toOriginX];
        } else {
          toOriginX -= 0.5;
        }
        offsetX = toOriginX - fromOriginX;
        if (typeof fromOriginY === "string") {
          fromOriginY = originYOffset[fromOriginY];
        } else {
          fromOriginY -= 0.5;
        }
        if (typeof toOriginY === "string") {
          toOriginY = originYOffset[toOriginY];
        } else {
          toOriginY -= 0.5;
        }
        offsetY = toOriginY - fromOriginY;
        if (offsetX || offsetY) {
          dim = this._getTransformedDimensions();
          x2 = point.x + offsetX * dim.x;
          y2 = point.y + offsetY * dim.y;
        }
        return new fabric2.Point(x2, y2);
      },
      translateToCenterPoint: function(point, originX, originY) {
        var p2 = this.translateToGivenOrigin(point, originX, originY, "center", "center");
        if (this.angle) {
          return fabric2.util.rotatePoint(p2, point, degreesToRadians(this.angle));
        }
        return p2;
      },
      translateToOriginPoint: function(center, originX, originY) {
        var p2 = this.translateToGivenOrigin(center, "center", "center", originX, originY);
        if (this.angle) {
          return fabric2.util.rotatePoint(p2, center, degreesToRadians(this.angle));
        }
        return p2;
      },
      getCenterPoint: function() {
        var leftTop = new fabric2.Point(this.left, this.top);
        return this.translateToCenterPoint(leftTop, this.originX, this.originY);
      },
      getPointByOrigin: function(originX, originY) {
        var center = this.getCenterPoint();
        return this.translateToOriginPoint(center, originX, originY);
      },
      toLocalPoint: function(point, originX, originY) {
        var center = this.getCenterPoint(), p2, p22;
        if (typeof originX !== "undefined" && typeof originY !== "undefined") {
          p2 = this.translateToGivenOrigin(center, "center", "center", originX, originY);
        } else {
          p2 = new fabric2.Point(this.left, this.top);
        }
        p22 = new fabric2.Point(point.x, point.y);
        if (this.angle) {
          p22 = fabric2.util.rotatePoint(p22, center, -degreesToRadians(this.angle));
        }
        return p22.subtractEquals(p2);
      },
      setPositionByOrigin: function(pos, originX, originY) {
        var center = this.translateToCenterPoint(pos, originX, originY), position2 = this.translateToOriginPoint(center, this.originX, this.originY);
        this.set("left", position2.x);
        this.set("top", position2.y);
      },
      adjustPosition: function(to) {
        var angle = degreesToRadians(this.angle), hypotFull = this.getScaledWidth(), xFull = fabric2.util.cos(angle) * hypotFull, yFull = fabric2.util.sin(angle) * hypotFull, offsetFrom, offsetTo;
        if (typeof this.originX === "string") {
          offsetFrom = originXOffset[this.originX];
        } else {
          offsetFrom = this.originX - 0.5;
        }
        if (typeof to === "string") {
          offsetTo = originXOffset[to];
        } else {
          offsetTo = to - 0.5;
        }
        this.left += xFull * (offsetTo - offsetFrom);
        this.top += yFull * (offsetTo - offsetFrom);
        this.setCoords();
        this.originX = to;
      },
      _setOriginToCenter: function() {
        this._originalOriginX = this.originX;
        this._originalOriginY = this.originY;
        var center = this.getCenterPoint();
        this.originX = "center";
        this.originY = "center";
        this.left = center.x;
        this.top = center.y;
      },
      _resetOrigin: function() {
        var originPoint = this.translateToOriginPoint(this.getCenterPoint(), this._originalOriginX, this._originalOriginY);
        this.originX = this._originalOriginX;
        this.originY = this._originalOriginY;
        this.left = originPoint.x;
        this.top = originPoint.y;
        this._originalOriginX = null;
        this._originalOriginY = null;
      },
      _getLeftTopCoords: function() {
        return this.translateToOriginPoint(this.getCenterPoint(), "left", "top");
      }
    });
  })();
  (function() {
    function arrayFromCoords(coords) {
      return [
        new fabric2.Point(coords.tl.x, coords.tl.y),
        new fabric2.Point(coords.tr.x, coords.tr.y),
        new fabric2.Point(coords.br.x, coords.br.y),
        new fabric2.Point(coords.bl.x, coords.bl.y)
      ];
    }
    var util = fabric2.util, degreesToRadians = util.degreesToRadians, multiplyMatrices = util.multiplyTransformMatrices, transformPoint = util.transformPoint;
    util.object.extend(fabric2.Object.prototype, {
      oCoords: null,
      aCoords: null,
      lineCoords: null,
      ownMatrixCache: null,
      matrixCache: null,
      controls: {},
      _getCoords: function(absolute, calculate) {
        if (calculate) {
          return absolute ? this.calcACoords() : this.calcLineCoords();
        }
        if (!this.aCoords || !this.lineCoords) {
          this.setCoords(true);
        }
        return absolute ? this.aCoords : this.lineCoords;
      },
      getCoords: function(absolute, calculate) {
        return arrayFromCoords(this._getCoords(absolute, calculate));
      },
      intersectsWithRect: function(pointTL, pointBR, absolute, calculate) {
        var coords = this.getCoords(absolute, calculate), intersection = fabric2.Intersection.intersectPolygonRectangle(coords, pointTL, pointBR);
        return intersection.status === "Intersection";
      },
      intersectsWithObject: function(other, absolute, calculate) {
        var intersection = fabric2.Intersection.intersectPolygonPolygon(this.getCoords(absolute, calculate), other.getCoords(absolute, calculate));
        return intersection.status === "Intersection" || other.isContainedWithinObject(this, absolute, calculate) || this.isContainedWithinObject(other, absolute, calculate);
      },
      isContainedWithinObject: function(other, absolute, calculate) {
        var points = this.getCoords(absolute, calculate), otherCoords = absolute ? other.aCoords : other.lineCoords, i2 = 0, lines = other._getImageLines(otherCoords);
        for (; i2 < 4; i2++) {
          if (!other.containsPoint(points[i2], lines)) {
            return false;
          }
        }
        return true;
      },
      isContainedWithinRect: function(pointTL, pointBR, absolute, calculate) {
        var boundingRect = this.getBoundingRect(absolute, calculate);
        return boundingRect.left >= pointTL.x && boundingRect.left + boundingRect.width <= pointBR.x && boundingRect.top >= pointTL.y && boundingRect.top + boundingRect.height <= pointBR.y;
      },
      containsPoint: function(point, lines, absolute, calculate) {
        var coords = this._getCoords(absolute, calculate), lines = lines || this._getImageLines(coords), xPoints = this._findCrossPoints(point, lines);
        return xPoints !== 0 && xPoints % 2 === 1;
      },
      isOnScreen: function(calculate) {
        if (!this.canvas) {
          return false;
        }
        var pointTL = this.canvas.vptCoords.tl, pointBR = this.canvas.vptCoords.br;
        var points = this.getCoords(true, calculate);
        if (points.some(function(point) {
          return point.x <= pointBR.x && point.x >= pointTL.x && point.y <= pointBR.y && point.y >= pointTL.y;
        })) {
          return true;
        }
        if (this.intersectsWithRect(pointTL, pointBR, true, calculate)) {
          return true;
        }
        return this._containsCenterOfCanvas(pointTL, pointBR, calculate);
      },
      _containsCenterOfCanvas: function(pointTL, pointBR, calculate) {
        var centerPoint = { x: (pointTL.x + pointBR.x) / 2, y: (pointTL.y + pointBR.y) / 2 };
        if (this.containsPoint(centerPoint, null, true, calculate)) {
          return true;
        }
        return false;
      },
      isPartiallyOnScreen: function(calculate) {
        if (!this.canvas) {
          return false;
        }
        var pointTL = this.canvas.vptCoords.tl, pointBR = this.canvas.vptCoords.br;
        if (this.intersectsWithRect(pointTL, pointBR, true, calculate)) {
          return true;
        }
        var allPointsAreOutside = this.getCoords(true, calculate).every(function(point) {
          return (point.x >= pointBR.x || point.x <= pointTL.x) && (point.y >= pointBR.y || point.y <= pointTL.y);
        });
        return allPointsAreOutside && this._containsCenterOfCanvas(pointTL, pointBR, calculate);
      },
      _getImageLines: function(oCoords) {
        var lines = {
          topline: {
            o: oCoords.tl,
            d: oCoords.tr
          },
          rightline: {
            o: oCoords.tr,
            d: oCoords.br
          },
          bottomline: {
            o: oCoords.br,
            d: oCoords.bl
          },
          leftline: {
            o: oCoords.bl,
            d: oCoords.tl
          }
        };
        return lines;
      },
      _findCrossPoints: function(point, lines) {
        var b1, b2, a1, a2, xi, xcount = 0, iLine;
        for (var lineKey in lines) {
          iLine = lines[lineKey];
          if (iLine.o.y < point.y && iLine.d.y < point.y) {
            continue;
          }
          if (iLine.o.y >= point.y && iLine.d.y >= point.y) {
            continue;
          }
          if (iLine.o.x === iLine.d.x && iLine.o.x >= point.x) {
            xi = iLine.o.x;
          } else {
            b1 = 0;
            b2 = (iLine.d.y - iLine.o.y) / (iLine.d.x - iLine.o.x);
            a1 = point.y - b1 * point.x;
            a2 = iLine.o.y - b2 * iLine.o.x;
            xi = -(a1 - a2) / (b1 - b2);
          }
          if (xi >= point.x) {
            xcount += 1;
          }
          if (xcount === 2) {
            break;
          }
        }
        return xcount;
      },
      getBoundingRect: function(absolute, calculate) {
        var coords = this.getCoords(absolute, calculate);
        return util.makeBoundingBoxFromPoints(coords);
      },
      getScaledWidth: function() {
        return this._getTransformedDimensions().x;
      },
      getScaledHeight: function() {
        return this._getTransformedDimensions().y;
      },
      _constrainScale: function(value) {
        if (Math.abs(value) < this.minScaleLimit) {
          if (value < 0) {
            return -this.minScaleLimit;
          } else {
            return this.minScaleLimit;
          }
        } else if (value === 0) {
          return 1e-4;
        }
        return value;
      },
      scale: function(value) {
        this._set("scaleX", value);
        this._set("scaleY", value);
        return this.setCoords();
      },
      scaleToWidth: function(value, absolute) {
        var boundingRectFactor = this.getBoundingRect(absolute).width / this.getScaledWidth();
        return this.scale(value / this.width / boundingRectFactor);
      },
      scaleToHeight: function(value, absolute) {
        var boundingRectFactor = this.getBoundingRect(absolute).height / this.getScaledHeight();
        return this.scale(value / this.height / boundingRectFactor);
      },
      calcCoords: function(absolute) {
        if (absolute) {
          return this.calcACoords();
        }
        return this.calcOCoords();
      },
      calcLineCoords: function() {
        var vpt = this.getViewportTransform(), padding = this.padding, angle = degreesToRadians(this.angle), cos = util.cos(angle), sin = util.sin(angle), cosP = cos * padding, sinP = sin * padding, cosPSinP = cosP + sinP, cosPMinusSinP = cosP - sinP, aCoords = this.calcACoords();
        var lineCoords = {
          tl: transformPoint(aCoords.tl, vpt),
          tr: transformPoint(aCoords.tr, vpt),
          bl: transformPoint(aCoords.bl, vpt),
          br: transformPoint(aCoords.br, vpt)
        };
        if (padding) {
          lineCoords.tl.x -= cosPMinusSinP;
          lineCoords.tl.y -= cosPSinP;
          lineCoords.tr.x += cosPSinP;
          lineCoords.tr.y -= cosPMinusSinP;
          lineCoords.bl.x -= cosPSinP;
          lineCoords.bl.y += cosPMinusSinP;
          lineCoords.br.x += cosPMinusSinP;
          lineCoords.br.y += cosPSinP;
        }
        return lineCoords;
      },
      calcOCoords: function() {
        var rotateMatrix = this._calcRotateMatrix(), translateMatrix = this._calcTranslateMatrix(), vpt = this.getViewportTransform(), startMatrix = multiplyMatrices(vpt, translateMatrix), finalMatrix = multiplyMatrices(startMatrix, rotateMatrix), finalMatrix = multiplyMatrices(finalMatrix, [1 / vpt[0], 0, 0, 1 / vpt[3], 0, 0]), dim = this._calculateCurrentDimensions(), coords = {};
        this.forEachControl(function(control, key, fabricObject) {
          coords[key] = control.positionHandler(dim, finalMatrix, fabricObject);
        });
        return coords;
      },
      calcACoords: function() {
        var rotateMatrix = this._calcRotateMatrix(), translateMatrix = this._calcTranslateMatrix(), finalMatrix = multiplyMatrices(translateMatrix, rotateMatrix), dim = this._getTransformedDimensions(), w2 = dim.x / 2, h2 = dim.y / 2;
        return {
          tl: transformPoint({ x: -w2, y: -h2 }, finalMatrix),
          tr: transformPoint({ x: w2, y: -h2 }, finalMatrix),
          bl: transformPoint({ x: -w2, y: h2 }, finalMatrix),
          br: transformPoint({ x: w2, y: h2 }, finalMatrix)
        };
      },
      setCoords: function(skipCorners) {
        this.aCoords = this.calcACoords();
        this.lineCoords = this.group ? this.aCoords : this.calcLineCoords();
        if (skipCorners) {
          return this;
        }
        this.oCoords = this.calcOCoords();
        this._setCornerCoords && this._setCornerCoords();
        return this;
      },
      _calcRotateMatrix: function() {
        return util.calcRotateMatrix(this);
      },
      _calcTranslateMatrix: function() {
        var center = this.getCenterPoint();
        return [1, 0, 0, 1, center.x, center.y];
      },
      transformMatrixKey: function(skipGroup) {
        var sep = "_", prefix2 = "";
        if (!skipGroup && this.group) {
          prefix2 = this.group.transformMatrixKey(skipGroup) + sep;
        }
        return prefix2 + this.top + sep + this.left + sep + this.scaleX + sep + this.scaleY + sep + this.skewX + sep + this.skewY + sep + this.angle + sep + this.originX + sep + this.originY + sep + this.width + sep + this.height + sep + this.strokeWidth + this.flipX + this.flipY;
      },
      calcTransformMatrix: function(skipGroup) {
        var matrix = this.calcOwnMatrix();
        if (skipGroup || !this.group) {
          return matrix;
        }
        var key = this.transformMatrixKey(skipGroup), cache = this.matrixCache || (this.matrixCache = {});
        if (cache.key === key) {
          return cache.value;
        }
        if (this.group) {
          matrix = multiplyMatrices(this.group.calcTransformMatrix(false), matrix);
        }
        cache.key = key;
        cache.value = matrix;
        return matrix;
      },
      calcOwnMatrix: function() {
        var key = this.transformMatrixKey(true), cache = this.ownMatrixCache || (this.ownMatrixCache = {});
        if (cache.key === key) {
          return cache.value;
        }
        var tMatrix = this._calcTranslateMatrix(), options = {
          angle: this.angle,
          translateX: tMatrix[4],
          translateY: tMatrix[5],
          scaleX: this.scaleX,
          scaleY: this.scaleY,
          skewX: this.skewX,
          skewY: this.skewY,
          flipX: this.flipX,
          flipY: this.flipY
        };
        cache.key = key;
        cache.value = util.composeMatrix(options);
        return cache.value;
      },
      _calcDimensionsTransformMatrix: function(skewX, skewY, flipping) {
        return util.calcDimensionsMatrix({
          skewX,
          skewY,
          scaleX: this.scaleX * (flipping && this.flipX ? -1 : 1),
          scaleY: this.scaleY * (flipping && this.flipY ? -1 : 1)
        });
      },
      _getNonTransformedDimensions: function() {
        var strokeWidth = this.strokeWidth, w2 = this.width + strokeWidth, h2 = this.height + strokeWidth;
        return { x: w2, y: h2 };
      },
      _getTransformedDimensions: function(skewX, skewY) {
        if (typeof skewX === "undefined") {
          skewX = this.skewX;
        }
        if (typeof skewY === "undefined") {
          skewY = this.skewY;
        }
        var dimensions, dimX, dimY, noSkew = skewX === 0 && skewY === 0;
        if (this.strokeUniform) {
          dimX = this.width;
          dimY = this.height;
        } else {
          dimensions = this._getNonTransformedDimensions();
          dimX = dimensions.x;
          dimY = dimensions.y;
        }
        if (noSkew) {
          return this._finalizeDimensions(dimX * this.scaleX, dimY * this.scaleY);
        }
        var bbox = util.sizeAfterTransform(dimX, dimY, {
          scaleX: this.scaleX,
          scaleY: this.scaleY,
          skewX,
          skewY
        });
        return this._finalizeDimensions(bbox.x, bbox.y);
      },
      _finalizeDimensions: function(width, height) {
        return this.strokeUniform ? { x: width + this.strokeWidth, y: height + this.strokeWidth } : { x: width, y: height };
      },
      _calculateCurrentDimensions: function() {
        var vpt = this.getViewportTransform(), dim = this._getTransformedDimensions(), p2 = transformPoint(dim, vpt, true);
        return p2.scalarAdd(2 * this.padding);
      }
    });
  })();
  fabric2.util.object.extend(fabric2.Object.prototype, {
    sendToBack: function() {
      if (this.group) {
        fabric2.StaticCanvas.prototype.sendToBack.call(this.group, this);
      } else if (this.canvas) {
        this.canvas.sendToBack(this);
      }
      return this;
    },
    bringToFront: function() {
      if (this.group) {
        fabric2.StaticCanvas.prototype.bringToFront.call(this.group, this);
      } else if (this.canvas) {
        this.canvas.bringToFront(this);
      }
      return this;
    },
    sendBackwards: function(intersecting) {
      if (this.group) {
        fabric2.StaticCanvas.prototype.sendBackwards.call(this.group, this, intersecting);
      } else if (this.canvas) {
        this.canvas.sendBackwards(this, intersecting);
      }
      return this;
    },
    bringForward: function(intersecting) {
      if (this.group) {
        fabric2.StaticCanvas.prototype.bringForward.call(this.group, this, intersecting);
      } else if (this.canvas) {
        this.canvas.bringForward(this, intersecting);
      }
      return this;
    },
    moveTo: function(index2) {
      if (this.group && this.group.type !== "activeSelection") {
        fabric2.StaticCanvas.prototype.moveTo.call(this.group, this, index2);
      } else if (this.canvas) {
        this.canvas.moveTo(this, index2);
      }
      return this;
    }
  });
  (function() {
    function getSvgColorString(prop, value) {
      if (!value) {
        return prop + ": none; ";
      } else if (value.toLive) {
        return prop + ": url(#SVGID_" + value.id + "); ";
      } else {
        var color2 = new fabric2.Color(value), str = prop + ": " + color2.toRgb() + "; ", opacity = color2.getAlpha();
        if (opacity !== 1) {
          str += prop + "-opacity: " + opacity.toString() + "; ";
        }
        return str;
      }
    }
    var toFixed = fabric2.util.toFixed;
    fabric2.util.object.extend(fabric2.Object.prototype, {
      getSvgStyles: function(skipShadow) {
        var fillRule = this.fillRule ? this.fillRule : "nonzero", strokeWidth = this.strokeWidth ? this.strokeWidth : "0", strokeDashArray = this.strokeDashArray ? this.strokeDashArray.join(" ") : "none", strokeDashOffset = this.strokeDashOffset ? this.strokeDashOffset : "0", strokeLineCap = this.strokeLineCap ? this.strokeLineCap : "butt", strokeLineJoin = this.strokeLineJoin ? this.strokeLineJoin : "miter", strokeMiterLimit = this.strokeMiterLimit ? this.strokeMiterLimit : "4", opacity = typeof this.opacity !== "undefined" ? this.opacity : "1", visibility = this.visible ? "" : " visibility: hidden;", filter2 = skipShadow ? "" : this.getSvgFilter(), fill2 = getSvgColorString("fill", this.fill), stroke = getSvgColorString("stroke", this.stroke);
        return [
          stroke,
          "stroke-width: ",
          strokeWidth,
          "; ",
          "stroke-dasharray: ",
          strokeDashArray,
          "; ",
          "stroke-linecap: ",
          strokeLineCap,
          "; ",
          "stroke-dashoffset: ",
          strokeDashOffset,
          "; ",
          "stroke-linejoin: ",
          strokeLineJoin,
          "; ",
          "stroke-miterlimit: ",
          strokeMiterLimit,
          "; ",
          fill2,
          "fill-rule: ",
          fillRule,
          "; ",
          "opacity: ",
          opacity,
          ";",
          filter2,
          visibility
        ].join("");
      },
      getSvgSpanStyles: function(style2, useWhiteSpace) {
        var term = "; ";
        var fontFamily = style2.fontFamily ? "font-family: " + (style2.fontFamily.indexOf("'") === -1 && style2.fontFamily.indexOf('"') === -1 ? "'" + style2.fontFamily + "'" : style2.fontFamily) + term : "";
        var strokeWidth = style2.strokeWidth ? "stroke-width: " + style2.strokeWidth + term : "", fontFamily = fontFamily, fontSize = style2.fontSize ? "font-size: " + style2.fontSize + "px" + term : "", fontStyle = style2.fontStyle ? "font-style: " + style2.fontStyle + term : "", fontWeight = style2.fontWeight ? "font-weight: " + style2.fontWeight + term : "", fill2 = style2.fill ? getSvgColorString("fill", style2.fill) : "", stroke = style2.stroke ? getSvgColorString("stroke", style2.stroke) : "", textDecoration = this.getSvgTextDecoration(style2), deltaY = style2.deltaY ? "baseline-shift: " + -style2.deltaY + "; " : "";
        if (textDecoration) {
          textDecoration = "text-decoration: " + textDecoration + term;
        }
        return [
          stroke,
          strokeWidth,
          fontFamily,
          fontSize,
          fontStyle,
          fontWeight,
          textDecoration,
          fill2,
          deltaY,
          useWhiteSpace ? "white-space: pre; " : ""
        ].join("");
      },
      getSvgTextDecoration: function(style2) {
        return ["overline", "underline", "line-through"].filter(function(decoration) {
          return style2[decoration.replace("-", "")];
        }).join(" ");
      },
      getSvgFilter: function() {
        return this.shadow ? "filter: url(#SVGID_" + this.shadow.id + ");" : "";
      },
      getSvgCommons: function() {
        return [
          this.id ? 'id="' + this.id + '" ' : "",
          this.clipPath ? 'clip-path="url(#' + this.clipPath.clipPathId + ')" ' : ""
        ].join("");
      },
      getSvgTransform: function(full, additionalTransform) {
        var transform2 = full ? this.calcTransformMatrix() : this.calcOwnMatrix(), svgTransform = 'transform="' + fabric2.util.matrixToSVG(transform2);
        return svgTransform + (additionalTransform || "") + '" ';
      },
      _setSVGBg: function(textBgRects) {
        if (this.backgroundColor) {
          var NUM_FRACTION_DIGITS = fabric2.Object.NUM_FRACTION_DIGITS;
          textBgRects.push("		<rect ", this._getFillAttributes(this.backgroundColor), ' x="', toFixed(-this.width / 2, NUM_FRACTION_DIGITS), '" y="', toFixed(-this.height / 2, NUM_FRACTION_DIGITS), '" width="', toFixed(this.width, NUM_FRACTION_DIGITS), '" height="', toFixed(this.height, NUM_FRACTION_DIGITS), '"></rect>\n');
        }
      },
      toSVG: function(reviver) {
        return this._createBaseSVGMarkup(this._toSVG(reviver), { reviver });
      },
      toClipPathSVG: function(reviver) {
        return "	" + this._createBaseClipPathSVGMarkup(this._toSVG(reviver), { reviver });
      },
      _createBaseClipPathSVGMarkup: function(objectMarkup, options) {
        options = options || {};
        var reviver = options.reviver, additionalTransform = options.additionalTransform || "", commonPieces = [
          this.getSvgTransform(true, additionalTransform),
          this.getSvgCommons()
        ].join(""), index2 = objectMarkup.indexOf("COMMON_PARTS");
        objectMarkup[index2] = commonPieces;
        return reviver ? reviver(objectMarkup.join("")) : objectMarkup.join("");
      },
      _createBaseSVGMarkup: function(objectMarkup, options) {
        options = options || {};
        var noStyle = options.noStyle, reviver = options.reviver, styleInfo = noStyle ? "" : 'style="' + this.getSvgStyles() + '" ', shadowInfo = options.withShadow ? 'style="' + this.getSvgFilter() + '" ' : "", clipPath = this.clipPath, vectorEffect = this.strokeUniform ? 'vector-effect="non-scaling-stroke" ' : "", absoluteClipPath = clipPath && clipPath.absolutePositioned, stroke = this.stroke, fill2 = this.fill, shadow = this.shadow, commonPieces, markup = [], clipPathMarkup, index2 = objectMarkup.indexOf("COMMON_PARTS"), additionalTransform = options.additionalTransform;
        if (clipPath) {
          clipPath.clipPathId = "CLIPPATH_" + fabric2.Object.__uid++;
          clipPathMarkup = '<clipPath id="' + clipPath.clipPathId + '" >\n' + clipPath.toClipPathSVG(reviver) + "</clipPath>\n";
        }
        if (absoluteClipPath) {
          markup.push("<g ", shadowInfo, this.getSvgCommons(), " >\n");
        }
        markup.push("<g ", this.getSvgTransform(false), !absoluteClipPath ? shadowInfo + this.getSvgCommons() : "", " >\n");
        commonPieces = [
          styleInfo,
          vectorEffect,
          noStyle ? "" : this.addPaintOrder(),
          " ",
          additionalTransform ? 'transform="' + additionalTransform + '" ' : ""
        ].join("");
        objectMarkup[index2] = commonPieces;
        if (fill2 && fill2.toLive) {
          markup.push(fill2.toSVG(this));
        }
        if (stroke && stroke.toLive) {
          markup.push(stroke.toSVG(this));
        }
        if (shadow) {
          markup.push(shadow.toSVG(this));
        }
        if (clipPath) {
          markup.push(clipPathMarkup);
        }
        markup.push(objectMarkup.join(""));
        markup.push("</g>\n");
        absoluteClipPath && markup.push("</g>\n");
        return reviver ? reviver(markup.join("")) : markup.join("");
      },
      addPaintOrder: function() {
        return this.paintFirst !== "fill" ? ' paint-order="' + this.paintFirst + '" ' : "";
      }
    });
  })();
  (function() {
    var extend = fabric2.util.object.extend, originalSet = "stateProperties";
    function saveProps(origin, destination, props2) {
      var tmpObj = {}, deep = true;
      props2.forEach(function(prop) {
        tmpObj[prop] = origin[prop];
      });
      extend(origin[destination], tmpObj, deep);
    }
    function _isEqual(origValue, currentValue, firstPass) {
      if (origValue === currentValue) {
        return true;
      } else if (Array.isArray(origValue)) {
        if (!Array.isArray(currentValue) || origValue.length !== currentValue.length) {
          return false;
        }
        for (var i2 = 0, len = origValue.length; i2 < len; i2++) {
          if (!_isEqual(origValue[i2], currentValue[i2])) {
            return false;
          }
        }
        return true;
      } else if (origValue && typeof origValue === "object") {
        var keys = Object.keys(origValue), key;
        if (!currentValue || typeof currentValue !== "object" || !firstPass && keys.length !== Object.keys(currentValue).length) {
          return false;
        }
        for (var i2 = 0, len = keys.length; i2 < len; i2++) {
          key = keys[i2];
          if (key === "canvas" || key === "group") {
            continue;
          }
          if (!_isEqual(origValue[key], currentValue[key])) {
            return false;
          }
        }
        return true;
      }
    }
    fabric2.util.object.extend(fabric2.Object.prototype, {
      hasStateChanged: function(propertySet) {
        propertySet = propertySet || originalSet;
        var dashedPropertySet = "_" + propertySet;
        if (Object.keys(this[dashedPropertySet]).length < this[propertySet].length) {
          return true;
        }
        return !_isEqual(this[dashedPropertySet], this, true);
      },
      saveState: function(options) {
        var propertySet = options && options.propertySet || originalSet, destination = "_" + propertySet;
        if (!this[destination]) {
          return this.setupState(options);
        }
        saveProps(this, destination, this[propertySet]);
        if (options && options.stateProperties) {
          saveProps(this, destination, options.stateProperties);
        }
        return this;
      },
      setupState: function(options) {
        options = options || {};
        var propertySet = options.propertySet || originalSet;
        options.propertySet = propertySet;
        this["_" + propertySet] = {};
        this.saveState(options);
        return this;
      }
    });
  })();
  (function() {
    var degreesToRadians = fabric2.util.degreesToRadians;
    fabric2.util.object.extend(fabric2.Object.prototype, {
      _findTargetCorner: function(pointer, forTouch) {
        if (!this.hasControls || this.group || (!this.canvas || this.canvas._activeObject !== this)) {
          return false;
        }
        var ex = pointer.x, ey = pointer.y, xPoints, lines, keys = Object.keys(this.oCoords), j2 = keys.length - 1, i2;
        this.__corner = 0;
        for (; j2 >= 0; j2--) {
          i2 = keys[j2];
          if (!this.isControlVisible(i2)) {
            continue;
          }
          lines = this._getImageLines(forTouch ? this.oCoords[i2].touchCorner : this.oCoords[i2].corner);
          xPoints = this._findCrossPoints({ x: ex, y: ey }, lines);
          if (xPoints !== 0 && xPoints % 2 === 1) {
            this.__corner = i2;
            return i2;
          }
        }
        return false;
      },
      forEachControl: function(fn2) {
        for (var i2 in this.controls) {
          fn2(this.controls[i2], i2, this);
        }
      },
      _setCornerCoords: function() {
        var coords = this.oCoords;
        for (var control in coords) {
          var controlObject = this.controls[control];
          coords[control].corner = controlObject.calcCornerCoords(this.angle, this.cornerSize, coords[control].x, coords[control].y, false);
          coords[control].touchCorner = controlObject.calcCornerCoords(this.angle, this.touchCornerSize, coords[control].x, coords[control].y, true);
        }
      },
      drawSelectionBackground: function(ctx) {
        if (!this.selectionBackgroundColor || this.canvas && !this.canvas.interactive || this.canvas && this.canvas._activeObject !== this) {
          return this;
        }
        ctx.save();
        var center = this.getCenterPoint(), wh = this._calculateCurrentDimensions(), vpt = this.canvas.viewportTransform;
        ctx.translate(center.x, center.y);
        ctx.scale(1 / vpt[0], 1 / vpt[3]);
        ctx.rotate(degreesToRadians(this.angle));
        ctx.fillStyle = this.selectionBackgroundColor;
        ctx.fillRect(-wh.x / 2, -wh.y / 2, wh.x, wh.y);
        ctx.restore();
        return this;
      },
      drawBorders: function(ctx, styleOverride) {
        styleOverride = styleOverride || {};
        var wh = this._calculateCurrentDimensions(), strokeWidth = this.borderScaleFactor, width = wh.x + strokeWidth, height = wh.y + strokeWidth, hasControls = typeof styleOverride.hasControls !== "undefined" ? styleOverride.hasControls : this.hasControls, shouldStroke = false;
        ctx.save();
        ctx.strokeStyle = styleOverride.borderColor || this.borderColor;
        this._setLineDash(ctx, styleOverride.borderDashArray || this.borderDashArray);
        ctx.strokeRect(-width / 2, -height / 2, width, height);
        if (hasControls) {
          ctx.beginPath();
          this.forEachControl(function(control, key, fabricObject) {
            if (control.withConnection && control.getVisibility(fabricObject, key)) {
              shouldStroke = true;
              ctx.moveTo(control.x * width, control.y * height);
              ctx.lineTo(control.x * width + control.offsetX, control.y * height + control.offsetY);
            }
          });
          if (shouldStroke) {
            ctx.stroke();
          }
        }
        ctx.restore();
        return this;
      },
      drawBordersInGroup: function(ctx, options, styleOverride) {
        styleOverride = styleOverride || {};
        var bbox = fabric2.util.sizeAfterTransform(this.width, this.height, options), strokeWidth = this.strokeWidth, strokeUniform = this.strokeUniform, borderScaleFactor = this.borderScaleFactor, width = bbox.x + strokeWidth * (strokeUniform ? this.canvas.getZoom() : options.scaleX) + borderScaleFactor, height = bbox.y + strokeWidth * (strokeUniform ? this.canvas.getZoom() : options.scaleY) + borderScaleFactor;
        ctx.save();
        this._setLineDash(ctx, styleOverride.borderDashArray || this.borderDashArray);
        ctx.strokeStyle = styleOverride.borderColor || this.borderColor;
        ctx.strokeRect(-width / 2, -height / 2, width, height);
        ctx.restore();
        return this;
      },
      drawControls: function(ctx, styleOverride) {
        styleOverride = styleOverride || {};
        ctx.save();
        var retinaScaling = this.canvas.getRetinaScaling(), matrix, p2;
        ctx.setTransform(retinaScaling, 0, 0, retinaScaling, 0, 0);
        ctx.strokeStyle = ctx.fillStyle = styleOverride.cornerColor || this.cornerColor;
        if (!this.transparentCorners) {
          ctx.strokeStyle = styleOverride.cornerStrokeColor || this.cornerStrokeColor;
        }
        this._setLineDash(ctx, styleOverride.cornerDashArray || this.cornerDashArray);
        this.setCoords();
        if (this.group) {
          matrix = this.group.calcTransformMatrix();
        }
        this.forEachControl(function(control, key, fabricObject) {
          p2 = fabricObject.oCoords[key];
          if (control.getVisibility(fabricObject, key)) {
            if (matrix) {
              p2 = fabric2.util.transformPoint(p2, matrix);
            }
            control.render(ctx, p2.x, p2.y, styleOverride, fabricObject);
          }
        });
        ctx.restore();
        return this;
      },
      isControlVisible: function(controlKey) {
        return this.controls[controlKey] && this.controls[controlKey].getVisibility(this, controlKey);
      },
      setControlVisible: function(controlKey, visible) {
        if (!this._controlsVisibility) {
          this._controlsVisibility = {};
        }
        this._controlsVisibility[controlKey] = visible;
        return this;
      },
      setControlsVisibility: function(options) {
        options || (options = {});
        for (var p2 in options) {
          this.setControlVisible(p2, options[p2]);
        }
        return this;
      },
      onDeselect: function() {
      },
      onSelect: function() {
      }
    });
  })();
  fabric2.util.object.extend(fabric2.StaticCanvas.prototype, {
    FX_DURATION: 500,
    fxCenterObjectH: function(object, callbacks) {
      callbacks = callbacks || {};
      var empty = function() {
      }, onComplete = callbacks.onComplete || empty, onChange = callbacks.onChange || empty, _this = this;
      fabric2.util.animate({
        startValue: object.left,
        endValue: this.getCenter().left,
        duration: this.FX_DURATION,
        onChange: function(value) {
          object.set("left", value);
          _this.requestRenderAll();
          onChange();
        },
        onComplete: function() {
          object.setCoords();
          onComplete();
        }
      });
      return this;
    },
    fxCenterObjectV: function(object, callbacks) {
      callbacks = callbacks || {};
      var empty = function() {
      }, onComplete = callbacks.onComplete || empty, onChange = callbacks.onChange || empty, _this = this;
      fabric2.util.animate({
        startValue: object.top,
        endValue: this.getCenter().top,
        duration: this.FX_DURATION,
        onChange: function(value) {
          object.set("top", value);
          _this.requestRenderAll();
          onChange();
        },
        onComplete: function() {
          object.setCoords();
          onComplete();
        }
      });
      return this;
    },
    fxRemove: function(object, callbacks) {
      callbacks = callbacks || {};
      var empty = function() {
      }, onComplete = callbacks.onComplete || empty, onChange = callbacks.onChange || empty, _this = this;
      fabric2.util.animate({
        startValue: object.opacity,
        endValue: 0,
        duration: this.FX_DURATION,
        onChange: function(value) {
          object.set("opacity", value);
          _this.requestRenderAll();
          onChange();
        },
        onComplete: function() {
          _this.remove(object);
          onComplete();
        }
      });
      return this;
    }
  });
  fabric2.util.object.extend(fabric2.Object.prototype, {
    animate: function() {
      if (arguments[0] && typeof arguments[0] === "object") {
        var propsToAnimate = [], prop, skipCallbacks;
        for (prop in arguments[0]) {
          propsToAnimate.push(prop);
        }
        for (var i2 = 0, len = propsToAnimate.length; i2 < len; i2++) {
          prop = propsToAnimate[i2];
          skipCallbacks = i2 !== len - 1;
          this._animate(prop, arguments[0][prop], arguments[1], skipCallbacks);
        }
      } else {
        this._animate.apply(this, arguments);
      }
      return this;
    },
    _animate: function(property, to, options, skipCallbacks) {
      var _this = this, propPair;
      to = to.toString();
      if (!options) {
        options = {};
      } else {
        options = fabric2.util.object.clone(options);
      }
      if (~property.indexOf(".")) {
        propPair = property.split(".");
      }
      var propIsColor = _this.colorProperties.indexOf(property) > -1 || propPair && _this.colorProperties.indexOf(propPair[1]) > -1;
      var currentValue = propPair ? this.get(propPair[0])[propPair[1]] : this.get(property);
      if (!("from" in options)) {
        options.from = currentValue;
      }
      if (!propIsColor) {
        if (~to.indexOf("=")) {
          to = currentValue + parseFloat(to.replace("=", ""));
        } else {
          to = parseFloat(to);
        }
      }
      var _options = {
        startValue: options.from,
        endValue: to,
        byValue: options.by,
        easing: options.easing,
        duration: options.duration,
        abort: options.abort && function(value, valueProgress, timeProgress) {
          return options.abort.call(_this, value, valueProgress, timeProgress);
        },
        onChange: function(value, valueProgress, timeProgress) {
          if (propPair) {
            _this[propPair[0]][propPair[1]] = value;
          } else {
            _this.set(property, value);
          }
          if (skipCallbacks) {
            return;
          }
          options.onChange && options.onChange(value, valueProgress, timeProgress);
        },
        onComplete: function(value, valueProgress, timeProgress) {
          if (skipCallbacks) {
            return;
          }
          _this.setCoords();
          options.onComplete && options.onComplete(value, valueProgress, timeProgress);
        }
      };
      if (propIsColor) {
        return fabric2.util.animateColor(_options.startValue, _options.endValue, _options.duration, _options);
      } else {
        return fabric2.util.animate(_options);
      }
    }
  });
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {}), extend = fabric3.util.object.extend, clone = fabric3.util.object.clone, coordProps = { x1: 1, x2: 1, y1: 1, y2: 1 };
    if (fabric3.Line) {
      fabric3.warn("fabric.Line is already defined");
      return;
    }
    fabric3.Line = fabric3.util.createClass(fabric3.Object, {
      type: "line",
      x1: 0,
      y1: 0,
      x2: 0,
      y2: 0,
      cacheProperties: fabric3.Object.prototype.cacheProperties.concat("x1", "x2", "y1", "y2"),
      initialize: function(points, options) {
        if (!points) {
          points = [0, 0, 0, 0];
        }
        this.callSuper("initialize", options);
        this.set("x1", points[0]);
        this.set("y1", points[1]);
        this.set("x2", points[2]);
        this.set("y2", points[3]);
        this._setWidthHeight(options);
      },
      _setWidthHeight: function(options) {
        options || (options = {});
        this.width = Math.abs(this.x2 - this.x1);
        this.height = Math.abs(this.y2 - this.y1);
        this.left = "left" in options ? options.left : this._getLeftToOriginX();
        this.top = "top" in options ? options.top : this._getTopToOriginY();
      },
      _set: function(key, value) {
        this.callSuper("_set", key, value);
        if (typeof coordProps[key] !== "undefined") {
          this._setWidthHeight();
        }
        return this;
      },
      _getLeftToOriginX: makeEdgeToOriginGetter({
        origin: "originX",
        axis1: "x1",
        axis2: "x2",
        dimension: "width"
      }, {
        nearest: "left",
        center: "center",
        farthest: "right"
      }),
      _getTopToOriginY: makeEdgeToOriginGetter({
        origin: "originY",
        axis1: "y1",
        axis2: "y2",
        dimension: "height"
      }, {
        nearest: "top",
        center: "center",
        farthest: "bottom"
      }),
      _render: function(ctx) {
        ctx.beginPath();
        var p2 = this.calcLinePoints();
        ctx.moveTo(p2.x1, p2.y1);
        ctx.lineTo(p2.x2, p2.y2);
        ctx.lineWidth = this.strokeWidth;
        var origStrokeStyle = ctx.strokeStyle;
        ctx.strokeStyle = this.stroke || ctx.fillStyle;
        this.stroke && this._renderStroke(ctx);
        ctx.strokeStyle = origStrokeStyle;
      },
      _findCenterFromElement: function() {
        return {
          x: (this.x1 + this.x2) / 2,
          y: (this.y1 + this.y2) / 2
        };
      },
      toObject: function(propertiesToInclude) {
        return extend(this.callSuper("toObject", propertiesToInclude), this.calcLinePoints());
      },
      _getNonTransformedDimensions: function() {
        var dim = this.callSuper("_getNonTransformedDimensions");
        if (this.strokeLineCap === "butt") {
          if (this.width === 0) {
            dim.y -= this.strokeWidth;
          }
          if (this.height === 0) {
            dim.x -= this.strokeWidth;
          }
        }
        return dim;
      },
      calcLinePoints: function() {
        var xMult = this.x1 <= this.x2 ? -1 : 1, yMult = this.y1 <= this.y2 ? -1 : 1, x1 = xMult * this.width * 0.5, y1 = yMult * this.height * 0.5, x2 = xMult * this.width * -0.5, y2 = yMult * this.height * -0.5;
        return {
          x1,
          x2,
          y1,
          y2
        };
      },
      _toSVG: function() {
        var p2 = this.calcLinePoints();
        return [
          "<line ",
          "COMMON_PARTS",
          'x1="',
          p2.x1,
          '" y1="',
          p2.y1,
          '" x2="',
          p2.x2,
          '" y2="',
          p2.y2,
          '" />\n'
        ];
      }
    });
    fabric3.Line.ATTRIBUTE_NAMES = fabric3.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" "));
    fabric3.Line.fromElement = function(element, callback, options) {
      options = options || {};
      var parsedAttributes = fabric3.parseAttributes(element, fabric3.Line.ATTRIBUTE_NAMES), points = [
        parsedAttributes.x1 || 0,
        parsedAttributes.y1 || 0,
        parsedAttributes.x2 || 0,
        parsedAttributes.y2 || 0
      ];
      callback(new fabric3.Line(points, extend(parsedAttributes, options)));
    };
    fabric3.Line.fromObject = function(object, callback) {
      function _callback(instance) {
        delete instance.points;
        callback && callback(instance);
      }
      var options = clone(object, true);
      options.points = [object.x1, object.y1, object.x2, object.y2];
      fabric3.Object._fromObject("Line", options, _callback, "points");
    };
    function makeEdgeToOriginGetter(propertyNames, originValues) {
      var origin = propertyNames.origin, axis1 = propertyNames.axis1, axis2 = propertyNames.axis2, dimension = propertyNames.dimension, nearest = originValues.nearest, center = originValues.center, farthest = originValues.farthest;
      return function() {
        switch (this.get(origin)) {
          case nearest:
            return Math.min(this.get(axis1), this.get(axis2));
          case center:
            return Math.min(this.get(axis1), this.get(axis2)) + 0.5 * this.get(dimension);
          case farthest:
            return Math.max(this.get(axis1), this.get(axis2));
        }
      };
    }
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {}), pi = Math.PI;
    if (fabric3.Circle) {
      fabric3.warn("fabric.Circle is already defined.");
      return;
    }
    fabric3.Circle = fabric3.util.createClass(fabric3.Object, {
      type: "circle",
      radius: 0,
      startAngle: 0,
      endAngle: pi * 2,
      cacheProperties: fabric3.Object.prototype.cacheProperties.concat("radius", "startAngle", "endAngle"),
      _set: function(key, value) {
        this.callSuper("_set", key, value);
        if (key === "radius") {
          this.setRadius(value);
        }
        return this;
      },
      toObject: function(propertiesToInclude) {
        return this.callSuper("toObject", ["radius", "startAngle", "endAngle"].concat(propertiesToInclude));
      },
      _toSVG: function() {
        var svgString, x2 = 0, y2 = 0, angle = (this.endAngle - this.startAngle) % (2 * pi);
        if (angle === 0) {
          svgString = [
            "<circle ",
            "COMMON_PARTS",
            'cx="' + x2 + '" cy="' + y2 + '" ',
            'r="',
            this.radius,
            '" />\n'
          ];
        } else {
          var startX = fabric3.util.cos(this.startAngle) * this.radius, startY = fabric3.util.sin(this.startAngle) * this.radius, endX = fabric3.util.cos(this.endAngle) * this.radius, endY = fabric3.util.sin(this.endAngle) * this.radius, largeFlag = angle > pi ? "1" : "0";
          svgString = [
            '<path d="M ' + startX + " " + startY,
            " A " + this.radius + " " + this.radius,
            " 0 ",
            +largeFlag + " 1",
            " " + endX + " " + endY,
            '" ',
            "COMMON_PARTS",
            " />\n"
          ];
        }
        return svgString;
      },
      _render: function(ctx) {
        ctx.beginPath();
        ctx.arc(0, 0, this.radius, this.startAngle, this.endAngle, false);
        this._renderPaintInOrder(ctx);
      },
      getRadiusX: function() {
        return this.get("radius") * this.get("scaleX");
      },
      getRadiusY: function() {
        return this.get("radius") * this.get("scaleY");
      },
      setRadius: function(value) {
        this.radius = value;
        return this.set("width", value * 2).set("height", value * 2);
      }
    });
    fabric3.Circle.ATTRIBUTE_NAMES = fabric3.SHARED_ATTRIBUTES.concat("cx cy r".split(" "));
    fabric3.Circle.fromElement = function(element, callback) {
      var parsedAttributes = fabric3.parseAttributes(element, fabric3.Circle.ATTRIBUTE_NAMES);
      if (!isValidRadius(parsedAttributes)) {
        throw new Error("value of `r` attribute is required and can not be negative");
      }
      parsedAttributes.left = (parsedAttributes.left || 0) - parsedAttributes.radius;
      parsedAttributes.top = (parsedAttributes.top || 0) - parsedAttributes.radius;
      callback(new fabric3.Circle(parsedAttributes));
    };
    function isValidRadius(attributes) {
      return "radius" in attributes && attributes.radius >= 0;
    }
    fabric3.Circle.fromObject = function(object, callback) {
      fabric3.Object._fromObject("Circle", object, callback);
    };
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {});
    if (fabric3.Triangle) {
      fabric3.warn("fabric.Triangle is already defined");
      return;
    }
    fabric3.Triangle = fabric3.util.createClass(fabric3.Object, {
      type: "triangle",
      width: 100,
      height: 100,
      _render: function(ctx) {
        var widthBy2 = this.width / 2, heightBy2 = this.height / 2;
        ctx.beginPath();
        ctx.moveTo(-widthBy2, heightBy2);
        ctx.lineTo(0, -heightBy2);
        ctx.lineTo(widthBy2, heightBy2);
        ctx.closePath();
        this._renderPaintInOrder(ctx);
      },
      _toSVG: function() {
        var widthBy2 = this.width / 2, heightBy2 = this.height / 2, points = [
          -widthBy2 + " " + heightBy2,
          "0 " + -heightBy2,
          widthBy2 + " " + heightBy2
        ].join(",");
        return [
          "<polygon ",
          "COMMON_PARTS",
          'points="',
          points,
          '" />'
        ];
      }
    });
    fabric3.Triangle.fromObject = function(object, callback) {
      return fabric3.Object._fromObject("Triangle", object, callback);
    };
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {}), piBy2 = Math.PI * 2;
    if (fabric3.Ellipse) {
      fabric3.warn("fabric.Ellipse is already defined.");
      return;
    }
    fabric3.Ellipse = fabric3.util.createClass(fabric3.Object, {
      type: "ellipse",
      rx: 0,
      ry: 0,
      cacheProperties: fabric3.Object.prototype.cacheProperties.concat("rx", "ry"),
      initialize: function(options) {
        this.callSuper("initialize", options);
        this.set("rx", options && options.rx || 0);
        this.set("ry", options && options.ry || 0);
      },
      _set: function(key, value) {
        this.callSuper("_set", key, value);
        switch (key) {
          case "rx":
            this.rx = value;
            this.set("width", value * 2);
            break;
          case "ry":
            this.ry = value;
            this.set("height", value * 2);
            break;
        }
        return this;
      },
      getRx: function() {
        return this.get("rx") * this.get("scaleX");
      },
      getRy: function() {
        return this.get("ry") * this.get("scaleY");
      },
      toObject: function(propertiesToInclude) {
        return this.callSuper("toObject", ["rx", "ry"].concat(propertiesToInclude));
      },
      _toSVG: function() {
        return [
          "<ellipse ",
          "COMMON_PARTS",
          'cx="0" cy="0" ',
          'rx="',
          this.rx,
          '" ry="',
          this.ry,
          '" />\n'
        ];
      },
      _render: function(ctx) {
        ctx.beginPath();
        ctx.save();
        ctx.transform(1, 0, 0, this.ry / this.rx, 0, 0);
        ctx.arc(0, 0, this.rx, 0, piBy2, false);
        ctx.restore();
        this._renderPaintInOrder(ctx);
      }
    });
    fabric3.Ellipse.ATTRIBUTE_NAMES = fabric3.SHARED_ATTRIBUTES.concat("cx cy rx ry".split(" "));
    fabric3.Ellipse.fromElement = function(element, callback) {
      var parsedAttributes = fabric3.parseAttributes(element, fabric3.Ellipse.ATTRIBUTE_NAMES);
      parsedAttributes.left = (parsedAttributes.left || 0) - parsedAttributes.rx;
      parsedAttributes.top = (parsedAttributes.top || 0) - parsedAttributes.ry;
      callback(new fabric3.Ellipse(parsedAttributes));
    };
    fabric3.Ellipse.fromObject = function(object, callback) {
      fabric3.Object._fromObject("Ellipse", object, callback);
    };
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {}), extend = fabric3.util.object.extend;
    if (fabric3.Rect) {
      fabric3.warn("fabric.Rect is already defined");
      return;
    }
    fabric3.Rect = fabric3.util.createClass(fabric3.Object, {
      stateProperties: fabric3.Object.prototype.stateProperties.concat("rx", "ry"),
      type: "rect",
      rx: 0,
      ry: 0,
      cacheProperties: fabric3.Object.prototype.cacheProperties.concat("rx", "ry"),
      initialize: function(options) {
        this.callSuper("initialize", options);
        this._initRxRy();
      },
      _initRxRy: function() {
        if (this.rx && !this.ry) {
          this.ry = this.rx;
        } else if (this.ry && !this.rx) {
          this.rx = this.ry;
        }
      },
      _render: function(ctx) {
        var rx = this.rx ? Math.min(this.rx, this.width / 2) : 0, ry = this.ry ? Math.min(this.ry, this.height / 2) : 0, w2 = this.width, h2 = this.height, x2 = -this.width / 2, y2 = -this.height / 2, isRounded = rx !== 0 || ry !== 0, k2 = 1 - 0.5522847498;
        ctx.beginPath();
        ctx.moveTo(x2 + rx, y2);
        ctx.lineTo(x2 + w2 - rx, y2);
        isRounded && ctx.bezierCurveTo(x2 + w2 - k2 * rx, y2, x2 + w2, y2 + k2 * ry, x2 + w2, y2 + ry);
        ctx.lineTo(x2 + w2, y2 + h2 - ry);
        isRounded && ctx.bezierCurveTo(x2 + w2, y2 + h2 - k2 * ry, x2 + w2 - k2 * rx, y2 + h2, x2 + w2 - rx, y2 + h2);
        ctx.lineTo(x2 + rx, y2 + h2);
        isRounded && ctx.bezierCurveTo(x2 + k2 * rx, y2 + h2, x2, y2 + h2 - k2 * ry, x2, y2 + h2 - ry);
        ctx.lineTo(x2, y2 + ry);
        isRounded && ctx.bezierCurveTo(x2, y2 + k2 * ry, x2 + k2 * rx, y2, x2 + rx, y2);
        ctx.closePath();
        this._renderPaintInOrder(ctx);
      },
      toObject: function(propertiesToInclude) {
        return this.callSuper("toObject", ["rx", "ry"].concat(propertiesToInclude));
      },
      _toSVG: function() {
        var x2 = -this.width / 2, y2 = -this.height / 2;
        return [
          "<rect ",
          "COMMON_PARTS",
          'x="',
          x2,
          '" y="',
          y2,
          '" rx="',
          this.rx,
          '" ry="',
          this.ry,
          '" width="',
          this.width,
          '" height="',
          this.height,
          '" />\n'
        ];
      }
    });
    fabric3.Rect.ATTRIBUTE_NAMES = fabric3.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" "));
    fabric3.Rect.fromElement = function(element, callback, options) {
      if (!element) {
        return callback(null);
      }
      options = options || {};
      var parsedAttributes = fabric3.parseAttributes(element, fabric3.Rect.ATTRIBUTE_NAMES);
      parsedAttributes.left = parsedAttributes.left || 0;
      parsedAttributes.top = parsedAttributes.top || 0;
      parsedAttributes.height = parsedAttributes.height || 0;
      parsedAttributes.width = parsedAttributes.width || 0;
      var rect = new fabric3.Rect(extend(options ? fabric3.util.object.clone(options) : {}, parsedAttributes));
      rect.visible = rect.visible && rect.width > 0 && rect.height > 0;
      callback(rect);
    };
    fabric3.Rect.fromObject = function(object, callback) {
      return fabric3.Object._fromObject("Rect", object, callback);
    };
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {}), extend = fabric3.util.object.extend, min = fabric3.util.array.min, max = fabric3.util.array.max, toFixed = fabric3.util.toFixed;
    if (fabric3.Polyline) {
      fabric3.warn("fabric.Polyline is already defined");
      return;
    }
    fabric3.Polyline = fabric3.util.createClass(fabric3.Object, {
      type: "polyline",
      points: null,
      cacheProperties: fabric3.Object.prototype.cacheProperties.concat("points"),
      initialize: function(points, options) {
        options = options || {};
        this.points = points || [];
        this.callSuper("initialize", options);
        this._setPositionDimensions(options);
      },
      _setPositionDimensions: function(options) {
        var calcDim = this._calcDimensions(options), correctLeftTop;
        this.width = calcDim.width;
        this.height = calcDim.height;
        if (!options.fromSVG) {
          correctLeftTop = this.translateToGivenOrigin({ x: calcDim.left - this.strokeWidth / 2, y: calcDim.top - this.strokeWidth / 2 }, "left", "top", this.originX, this.originY);
        }
        if (typeof options.left === "undefined") {
          this.left = options.fromSVG ? calcDim.left : correctLeftTop.x;
        }
        if (typeof options.top === "undefined") {
          this.top = options.fromSVG ? calcDim.top : correctLeftTop.y;
        }
        this.pathOffset = {
          x: calcDim.left + this.width / 2,
          y: calcDim.top + this.height / 2
        };
      },
      _calcDimensions: function() {
        var points = this.points, minX = min(points, "x") || 0, minY = min(points, "y") || 0, maxX = max(points, "x") || 0, maxY = max(points, "y") || 0, width = maxX - minX, height = maxY - minY;
        return {
          left: minX,
          top: minY,
          width,
          height
        };
      },
      toObject: function(propertiesToInclude) {
        return extend(this.callSuper("toObject", propertiesToInclude), {
          points: this.points.concat()
        });
      },
      _toSVG: function() {
        var points = [], diffX = this.pathOffset.x, diffY = this.pathOffset.y, NUM_FRACTION_DIGITS = fabric3.Object.NUM_FRACTION_DIGITS;
        for (var i2 = 0, len = this.points.length; i2 < len; i2++) {
          points.push(toFixed(this.points[i2].x - diffX, NUM_FRACTION_DIGITS), ",", toFixed(this.points[i2].y - diffY, NUM_FRACTION_DIGITS), " ");
        }
        return [
          "<" + this.type + " ",
          "COMMON_PARTS",
          'points="',
          points.join(""),
          '" />\n'
        ];
      },
      commonRender: function(ctx) {
        var point, len = this.points.length, x2 = this.pathOffset.x, y2 = this.pathOffset.y;
        if (!len || isNaN(this.points[len - 1].y)) {
          return false;
        }
        ctx.beginPath();
        ctx.moveTo(this.points[0].x - x2, this.points[0].y - y2);
        for (var i2 = 0; i2 < len; i2++) {
          point = this.points[i2];
          ctx.lineTo(point.x - x2, point.y - y2);
        }
        return true;
      },
      _render: function(ctx) {
        if (!this.commonRender(ctx)) {
          return;
        }
        this._renderPaintInOrder(ctx);
      },
      complexity: function() {
        return this.get("points").length;
      }
    });
    fabric3.Polyline.ATTRIBUTE_NAMES = fabric3.SHARED_ATTRIBUTES.concat();
    fabric3.Polyline.fromElementGenerator = function(_class) {
      return function(element, callback, options) {
        if (!element) {
          return callback(null);
        }
        options || (options = {});
        var points = fabric3.parsePointsAttribute(element.getAttribute("points")), parsedAttributes = fabric3.parseAttributes(element, fabric3[_class].ATTRIBUTE_NAMES);
        parsedAttributes.fromSVG = true;
        callback(new fabric3[_class](points, extend(parsedAttributes, options)));
      };
    };
    fabric3.Polyline.fromElement = fabric3.Polyline.fromElementGenerator("Polyline");
    fabric3.Polyline.fromObject = function(object, callback) {
      return fabric3.Object._fromObject("Polyline", object, callback, "points");
    };
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {});
    if (fabric3.Polygon) {
      fabric3.warn("fabric.Polygon is already defined");
      return;
    }
    fabric3.Polygon = fabric3.util.createClass(fabric3.Polyline, {
      type: "polygon",
      _render: function(ctx) {
        if (!this.commonRender(ctx)) {
          return;
        }
        ctx.closePath();
        this._renderPaintInOrder(ctx);
      }
    });
    fabric3.Polygon.ATTRIBUTE_NAMES = fabric3.SHARED_ATTRIBUTES.concat();
    fabric3.Polygon.fromElement = fabric3.Polyline.fromElementGenerator("Polygon");
    fabric3.Polygon.fromObject = function(object, callback) {
      fabric3.Object._fromObject("Polygon", object, callback, "points");
    };
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {}), min = fabric3.util.array.min, max = fabric3.util.array.max, extend = fabric3.util.object.extend, _toString = Object.prototype.toString, toFixed = fabric3.util.toFixed;
    if (fabric3.Path) {
      fabric3.warn("fabric.Path is already defined");
      return;
    }
    fabric3.Path = fabric3.util.createClass(fabric3.Object, {
      type: "path",
      path: null,
      cacheProperties: fabric3.Object.prototype.cacheProperties.concat("path", "fillRule"),
      stateProperties: fabric3.Object.prototype.stateProperties.concat("path"),
      initialize: function(path, options) {
        options = options || {};
        this.callSuper("initialize", options);
        if (!path) {
          path = [];
        }
        var fromArray = _toString.call(path) === "[object Array]";
        this.path = fabric3.util.makePathSimpler(fromArray ? path : fabric3.util.parsePath(path));
        if (!this.path) {
          return;
        }
        fabric3.Polyline.prototype._setPositionDimensions.call(this, options);
      },
      _renderPathCommands: function(ctx) {
        var current, subpathStartX = 0, subpathStartY = 0, x2 = 0, y2 = 0, controlX = 0, controlY = 0, l2 = -this.pathOffset.x, t2 = -this.pathOffset.y;
        ctx.beginPath();
        for (var i2 = 0, len = this.path.length; i2 < len; ++i2) {
          current = this.path[i2];
          switch (current[0]) {
            case "L":
              x2 = current[1];
              y2 = current[2];
              ctx.lineTo(x2 + l2, y2 + t2);
              break;
            case "M":
              x2 = current[1];
              y2 = current[2];
              subpathStartX = x2;
              subpathStartY = y2;
              ctx.moveTo(x2 + l2, y2 + t2);
              break;
            case "C":
              x2 = current[5];
              y2 = current[6];
              controlX = current[3];
              controlY = current[4];
              ctx.bezierCurveTo(current[1] + l2, current[2] + t2, controlX + l2, controlY + t2, x2 + l2, y2 + t2);
              break;
            case "Q":
              ctx.quadraticCurveTo(current[1] + l2, current[2] + t2, current[3] + l2, current[4] + t2);
              x2 = current[3];
              y2 = current[4];
              controlX = current[1];
              controlY = current[2];
              break;
            case "z":
            case "Z":
              x2 = subpathStartX;
              y2 = subpathStartY;
              ctx.closePath();
              break;
          }
        }
      },
      _render: function(ctx) {
        this._renderPathCommands(ctx);
        this._renderPaintInOrder(ctx);
      },
      toString: function() {
        return "#<fabric.Path (" + this.complexity() + '): { "top": ' + this.top + ', "left": ' + this.left + " }>";
      },
      toObject: function(propertiesToInclude) {
        return extend(this.callSuper("toObject", propertiesToInclude), {
          path: this.path.map(function(item) {
            return item.slice();
          })
        });
      },
      toDatalessObject: function(propertiesToInclude) {
        var o2 = this.toObject(["sourcePath"].concat(propertiesToInclude));
        if (o2.sourcePath) {
          delete o2.path;
        }
        return o2;
      },
      _toSVG: function() {
        var path = fabric3.util.joinPath(this.path);
        return [
          "<path ",
          "COMMON_PARTS",
          'd="',
          path,
          '" stroke-linecap="round" ',
          "/>\n"
        ];
      },
      _getOffsetTransform: function() {
        var digits = fabric3.Object.NUM_FRACTION_DIGITS;
        return " translate(" + toFixed(-this.pathOffset.x, digits) + ", " + toFixed(-this.pathOffset.y, digits) + ")";
      },
      toClipPathSVG: function(reviver) {
        var additionalTransform = this._getOffsetTransform();
        return "	" + this._createBaseClipPathSVGMarkup(this._toSVG(), { reviver, additionalTransform });
      },
      toSVG: function(reviver) {
        var additionalTransform = this._getOffsetTransform();
        return this._createBaseSVGMarkup(this._toSVG(), { reviver, additionalTransform });
      },
      complexity: function() {
        return this.path.length;
      },
      _calcDimensions: function() {
        var aX = [], aY = [], current, subpathStartX = 0, subpathStartY = 0, x2 = 0, y2 = 0, bounds;
        for (var i2 = 0, len = this.path.length; i2 < len; ++i2) {
          current = this.path[i2];
          switch (current[0]) {
            case "L":
              x2 = current[1];
              y2 = current[2];
              bounds = [];
              break;
            case "M":
              x2 = current[1];
              y2 = current[2];
              subpathStartX = x2;
              subpathStartY = y2;
              bounds = [];
              break;
            case "C":
              bounds = fabric3.util.getBoundsOfCurve(x2, y2, current[1], current[2], current[3], current[4], current[5], current[6]);
              x2 = current[5];
              y2 = current[6];
              break;
            case "Q":
              bounds = fabric3.util.getBoundsOfCurve(x2, y2, current[1], current[2], current[1], current[2], current[3], current[4]);
              x2 = current[3];
              y2 = current[4];
              break;
            case "z":
            case "Z":
              x2 = subpathStartX;
              y2 = subpathStartY;
              break;
          }
          bounds.forEach(function(point) {
            aX.push(point.x);
            aY.push(point.y);
          });
          aX.push(x2);
          aY.push(y2);
        }
        var minX = min(aX) || 0, minY = min(aY) || 0, maxX = max(aX) || 0, maxY = max(aY) || 0, deltaX = maxX - minX, deltaY = maxY - minY;
        return {
          left: minX,
          top: minY,
          width: deltaX,
          height: deltaY
        };
      }
    });
    fabric3.Path.fromObject = function(object, callback) {
      if (typeof object.sourcePath === "string") {
        var pathUrl = object.sourcePath;
        fabric3.loadSVGFromURL(pathUrl, function(elements) {
          var path = elements[0];
          path.setOptions(object);
          callback && callback(path);
        });
      } else {
        fabric3.Object._fromObject("Path", object, callback, "path");
      }
    };
    fabric3.Path.ATTRIBUTE_NAMES = fabric3.SHARED_ATTRIBUTES.concat(["d"]);
    fabric3.Path.fromElement = function(element, callback, options) {
      var parsedAttributes = fabric3.parseAttributes(element, fabric3.Path.ATTRIBUTE_NAMES);
      parsedAttributes.fromSVG = true;
      callback(new fabric3.Path(parsedAttributes.d, extend(parsedAttributes, options)));
    };
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {}), min = fabric3.util.array.min, max = fabric3.util.array.max;
    if (fabric3.Group) {
      return;
    }
    fabric3.Group = fabric3.util.createClass(fabric3.Object, fabric3.Collection, {
      type: "group",
      strokeWidth: 0,
      subTargetCheck: false,
      cacheProperties: [],
      useSetOnGroup: false,
      initialize: function(objects, options, isAlreadyGrouped) {
        options = options || {};
        this._objects = [];
        isAlreadyGrouped && this.callSuper("initialize", options);
        this._objects = objects || [];
        for (var i2 = this._objects.length; i2--; ) {
          this._objects[i2].group = this;
        }
        if (!isAlreadyGrouped) {
          var center = options && options.centerPoint;
          if (options.originX !== void 0) {
            this.originX = options.originX;
          }
          if (options.originY !== void 0) {
            this.originY = options.originY;
          }
          center || this._calcBounds();
          this._updateObjectsCoords(center);
          delete options.centerPoint;
          this.callSuper("initialize", options);
        } else {
          this._updateObjectsACoords();
        }
        this.setCoords();
      },
      _updateObjectsACoords: function() {
        var skipControls = true;
        for (var i2 = this._objects.length; i2--; ) {
          this._objects[i2].setCoords(skipControls);
        }
      },
      _updateObjectsCoords: function(center) {
        var center = center || this.getCenterPoint();
        for (var i2 = this._objects.length; i2--; ) {
          this._updateObjectCoords(this._objects[i2], center);
        }
      },
      _updateObjectCoords: function(object, center) {
        var objectLeft = object.left, objectTop = object.top, skipControls = true;
        object.set({
          left: objectLeft - center.x,
          top: objectTop - center.y
        });
        object.group = this;
        object.setCoords(skipControls);
      },
      toString: function() {
        return "#<fabric.Group: (" + this.complexity() + ")>";
      },
      addWithUpdate: function(object) {
        var nested = !!this.group;
        this._restoreObjectsState();
        fabric3.util.resetObjectTransform(this);
        if (object) {
          if (nested) {
            fabric3.util.removeTransformFromObject(object, this.group.calcTransformMatrix());
          }
          this._objects.push(object);
          object.group = this;
          object._set("canvas", this.canvas);
        }
        this._calcBounds();
        this._updateObjectsCoords();
        this.dirty = true;
        if (nested) {
          this.group.addWithUpdate();
        } else {
          this.setCoords();
        }
        return this;
      },
      removeWithUpdate: function(object) {
        this._restoreObjectsState();
        fabric3.util.resetObjectTransform(this);
        this.remove(object);
        this._calcBounds();
        this._updateObjectsCoords();
        this.setCoords();
        this.dirty = true;
        return this;
      },
      _onObjectAdded: function(object) {
        this.dirty = true;
        object.group = this;
        object._set("canvas", this.canvas);
      },
      _onObjectRemoved: function(object) {
        this.dirty = true;
        delete object.group;
      },
      _set: function(key, value) {
        var i2 = this._objects.length;
        if (this.useSetOnGroup) {
          while (i2--) {
            this._objects[i2].setOnGroup(key, value);
          }
        }
        if (key === "canvas") {
          while (i2--) {
            this._objects[i2]._set(key, value);
          }
        }
        fabric3.Object.prototype._set.call(this, key, value);
      },
      toObject: function(propertiesToInclude) {
        var _includeDefaultValues = this.includeDefaultValues;
        var objsToObject = this._objects.filter(function(obj2) {
          return !obj2.excludeFromExport;
        }).map(function(obj2) {
          var originalDefaults = obj2.includeDefaultValues;
          obj2.includeDefaultValues = _includeDefaultValues;
          var _obj = obj2.toObject(propertiesToInclude);
          obj2.includeDefaultValues = originalDefaults;
          return _obj;
        });
        var obj = fabric3.Object.prototype.toObject.call(this, propertiesToInclude);
        obj.objects = objsToObject;
        return obj;
      },
      toDatalessObject: function(propertiesToInclude) {
        var objsToObject, sourcePath = this.sourcePath;
        if (sourcePath) {
          objsToObject = sourcePath;
        } else {
          var _includeDefaultValues = this.includeDefaultValues;
          objsToObject = this._objects.map(function(obj2) {
            var originalDefaults = obj2.includeDefaultValues;
            obj2.includeDefaultValues = _includeDefaultValues;
            var _obj = obj2.toDatalessObject(propertiesToInclude);
            obj2.includeDefaultValues = originalDefaults;
            return _obj;
          });
        }
        var obj = fabric3.Object.prototype.toDatalessObject.call(this, propertiesToInclude);
        obj.objects = objsToObject;
        return obj;
      },
      render: function(ctx) {
        this._transformDone = true;
        this.callSuper("render", ctx);
        this._transformDone = false;
      },
      shouldCache: function() {
        var ownCache = fabric3.Object.prototype.shouldCache.call(this);
        if (ownCache) {
          for (var i2 = 0, len = this._objects.length; i2 < len; i2++) {
            if (this._objects[i2].willDrawShadow()) {
              this.ownCaching = false;
              return false;
            }
          }
        }
        return ownCache;
      },
      willDrawShadow: function() {
        if (fabric3.Object.prototype.willDrawShadow.call(this)) {
          return true;
        }
        for (var i2 = 0, len = this._objects.length; i2 < len; i2++) {
          if (this._objects[i2].willDrawShadow()) {
            return true;
          }
        }
        return false;
      },
      isOnACache: function() {
        return this.ownCaching || this.group && this.group.isOnACache();
      },
      drawObject: function(ctx) {
        for (var i2 = 0, len = this._objects.length; i2 < len; i2++) {
          this._objects[i2].render(ctx);
        }
        this._drawClipPath(ctx);
      },
      isCacheDirty: function(skipCanvas) {
        if (this.callSuper("isCacheDirty", skipCanvas)) {
          return true;
        }
        if (!this.statefullCache) {
          return false;
        }
        for (var i2 = 0, len = this._objects.length; i2 < len; i2++) {
          if (this._objects[i2].isCacheDirty(true)) {
            if (this._cacheCanvas) {
              var x2 = this.cacheWidth / this.zoomX, y2 = this.cacheHeight / this.zoomY;
              this._cacheContext.clearRect(-x2 / 2, -y2 / 2, x2, y2);
            }
            return true;
          }
        }
        return false;
      },
      _restoreObjectsState: function() {
        var groupMatrix = this.calcOwnMatrix();
        this._objects.forEach(function(object) {
          fabric3.util.addTransformToObject(object, groupMatrix);
          delete object.group;
          object.setCoords();
        });
        return this;
      },
      realizeTransform: function(object, parentMatrix) {
        fabric3.util.addTransformToObject(object, parentMatrix);
        return object;
      },
      destroy: function() {
        this._objects.forEach(function(object) {
          object.set("dirty", true);
        });
        return this._restoreObjectsState();
      },
      toActiveSelection: function() {
        if (!this.canvas) {
          return;
        }
        var objects = this._objects, canvas = this.canvas;
        this._objects = [];
        var options = this.toObject();
        delete options.objects;
        var activeSelection = new fabric3.ActiveSelection([]);
        activeSelection.set(options);
        activeSelection.type = "activeSelection";
        canvas.remove(this);
        objects.forEach(function(object) {
          object.group = activeSelection;
          object.dirty = true;
          canvas.add(object);
        });
        activeSelection.canvas = canvas;
        activeSelection._objects = objects;
        canvas._activeObject = activeSelection;
        activeSelection.setCoords();
        return activeSelection;
      },
      ungroupOnCanvas: function() {
        return this._restoreObjectsState();
      },
      setObjectsCoords: function() {
        var skipControls = true;
        this.forEachObject(function(object) {
          object.setCoords(skipControls);
        });
        return this;
      },
      _calcBounds: function(onlyWidthHeight) {
        var aX = [], aY = [], o2, prop, coords, props2 = ["tr", "br", "bl", "tl"], i2 = 0, iLen = this._objects.length, j2, jLen = props2.length;
        for (; i2 < iLen; ++i2) {
          o2 = this._objects[i2];
          coords = o2.calcACoords();
          for (j2 = 0; j2 < jLen; j2++) {
            prop = props2[j2];
            aX.push(coords[prop].x);
            aY.push(coords[prop].y);
          }
          o2.aCoords = coords;
        }
        this._getBounds(aX, aY, onlyWidthHeight);
      },
      _getBounds: function(aX, aY, onlyWidthHeight) {
        var minXY = new fabric3.Point(min(aX), min(aY)), maxXY = new fabric3.Point(max(aX), max(aY)), top = minXY.y || 0, left = minXY.x || 0, width = maxXY.x - minXY.x || 0, height = maxXY.y - minXY.y || 0;
        this.width = width;
        this.height = height;
        if (!onlyWidthHeight) {
          this.setPositionByOrigin({ x: left, y: top }, "left", "top");
        }
      },
      _toSVG: function(reviver) {
        var svgString = ["<g ", "COMMON_PARTS", " >\n"];
        for (var i2 = 0, len = this._objects.length; i2 < len; i2++) {
          svgString.push("		", this._objects[i2].toSVG(reviver));
        }
        svgString.push("</g>\n");
        return svgString;
      },
      getSvgStyles: function() {
        var opacity = typeof this.opacity !== "undefined" && this.opacity !== 1 ? "opacity: " + this.opacity + ";" : "", visibility = this.visible ? "" : " visibility: hidden;";
        return [
          opacity,
          this.getSvgFilter(),
          visibility
        ].join("");
      },
      toClipPathSVG: function(reviver) {
        var svgString = [];
        for (var i2 = 0, len = this._objects.length; i2 < len; i2++) {
          svgString.push("	", this._objects[i2].toClipPathSVG(reviver));
        }
        return this._createBaseClipPathSVGMarkup(svgString, { reviver });
      }
    });
    fabric3.Group.fromObject = function(object, callback) {
      var objects = object.objects, options = fabric3.util.object.clone(object, true);
      delete options.objects;
      if (typeof objects === "string") {
        fabric3.loadSVGFromURL(objects, function(elements) {
          var group = fabric3.util.groupSVGElements(elements, object, objects);
          group.set(options);
          callback && callback(group);
        });
        return;
      }
      fabric3.util.enlivenObjects(objects, function(enlivenedObjects) {
        fabric3.util.enlivenObjects([object.clipPath], function(enlivedClipPath) {
          var options2 = fabric3.util.object.clone(object, true);
          options2.clipPath = enlivedClipPath[0];
          delete options2.objects;
          callback && callback(new fabric3.Group(enlivenedObjects, options2, true));
        });
      });
    };
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {});
    if (fabric3.ActiveSelection) {
      return;
    }
    fabric3.ActiveSelection = fabric3.util.createClass(fabric3.Group, {
      type: "activeSelection",
      initialize: function(objects, options) {
        options = options || {};
        this._objects = objects || [];
        for (var i2 = this._objects.length; i2--; ) {
          this._objects[i2].group = this;
        }
        if (options.originX) {
          this.originX = options.originX;
        }
        if (options.originY) {
          this.originY = options.originY;
        }
        this._calcBounds();
        this._updateObjectsCoords();
        fabric3.Object.prototype.initialize.call(this, options);
        this.setCoords();
      },
      toGroup: function() {
        var objects = this._objects.concat();
        this._objects = [];
        var options = fabric3.Object.prototype.toObject.call(this);
        var newGroup = new fabric3.Group([]);
        delete options.type;
        newGroup.set(options);
        objects.forEach(function(object) {
          object.canvas.remove(object);
          object.group = newGroup;
        });
        newGroup._objects = objects;
        if (!this.canvas) {
          return newGroup;
        }
        var canvas = this.canvas;
        canvas.add(newGroup);
        canvas._activeObject = newGroup;
        newGroup.setCoords();
        return newGroup;
      },
      onDeselect: function() {
        this.destroy();
        return false;
      },
      toString: function() {
        return "#<fabric.ActiveSelection: (" + this.complexity() + ")>";
      },
      shouldCache: function() {
        return false;
      },
      isOnACache: function() {
        return false;
      },
      _renderControls: function(ctx, styleOverride, childrenOverride) {
        ctx.save();
        ctx.globalAlpha = this.isMoving ? this.borderOpacityWhenMoving : 1;
        this.callSuper("_renderControls", ctx, styleOverride);
        childrenOverride = childrenOverride || {};
        if (typeof childrenOverride.hasControls === "undefined") {
          childrenOverride.hasControls = false;
        }
        childrenOverride.forActiveSelection = true;
        for (var i2 = 0, len = this._objects.length; i2 < len; i2++) {
          this._objects[i2]._renderControls(ctx, childrenOverride);
        }
        ctx.restore();
      }
    });
    fabric3.ActiveSelection.fromObject = function(object, callback) {
      fabric3.util.enlivenObjects(object.objects, function(enlivenedObjects) {
        delete object.objects;
        callback && callback(new fabric3.ActiveSelection(enlivenedObjects, object, true));
      });
    };
  })(exports2);
  (function(global2) {
    var extend = fabric2.util.object.extend;
    if (!global2.fabric) {
      global2.fabric = {};
    }
    if (global2.fabric.Image) {
      fabric2.warn("fabric.Image is already defined.");
      return;
    }
    fabric2.Image = fabric2.util.createClass(fabric2.Object, {
      type: "image",
      strokeWidth: 0,
      srcFromAttribute: false,
      _lastScaleX: 1,
      _lastScaleY: 1,
      _filterScalingX: 1,
      _filterScalingY: 1,
      minimumScaleTrigger: 0.5,
      stateProperties: fabric2.Object.prototype.stateProperties.concat("cropX", "cropY"),
      cacheProperties: fabric2.Object.prototype.cacheProperties.concat("cropX", "cropY"),
      cacheKey: "",
      cropX: 0,
      cropY: 0,
      imageSmoothing: true,
      initialize: function(element, options) {
        options || (options = {});
        this.filters = [];
        this.cacheKey = "texture" + fabric2.Object.__uid++;
        this.callSuper("initialize", options);
        this._initElement(element, options);
      },
      getElement: function() {
        return this._element || {};
      },
      setElement: function(element, options) {
        this.removeTexture(this.cacheKey);
        this.removeTexture(this.cacheKey + "_filtered");
        this._element = element;
        this._originalElement = element;
        this._initConfig(options);
        if (this.filters.length !== 0) {
          this.applyFilters();
        }
        if (this.resizeFilter) {
          this.applyResizeFilters();
        }
        return this;
      },
      removeTexture: function(key) {
        var backend = fabric2.filterBackend;
        if (backend && backend.evictCachesForKey) {
          backend.evictCachesForKey(key);
        }
      },
      dispose: function() {
        this.removeTexture(this.cacheKey);
        this.removeTexture(this.cacheKey + "_filtered");
        this._cacheContext = void 0;
        ["_originalElement", "_element", "_filteredEl", "_cacheCanvas"].forEach(function(element) {
          fabric2.util.cleanUpJsdomNode(this[element]);
          this[element] = void 0;
        }.bind(this));
      },
      getCrossOrigin: function() {
        return this._originalElement && (this._originalElement.crossOrigin || null);
      },
      getOriginalSize: function() {
        var element = this.getElement();
        return {
          width: element.naturalWidth || element.width,
          height: element.naturalHeight || element.height
        };
      },
      _stroke: function(ctx) {
        if (!this.stroke || this.strokeWidth === 0) {
          return;
        }
        var w2 = this.width / 2, h2 = this.height / 2;
        ctx.beginPath();
        ctx.moveTo(-w2, -h2);
        ctx.lineTo(w2, -h2);
        ctx.lineTo(w2, h2);
        ctx.lineTo(-w2, h2);
        ctx.lineTo(-w2, -h2);
        ctx.closePath();
      },
      toObject: function(propertiesToInclude) {
        var filters = [];
        this.filters.forEach(function(filterObj) {
          if (filterObj) {
            filters.push(filterObj.toObject());
          }
        });
        var object = extend(this.callSuper("toObject", ["cropX", "cropY"].concat(propertiesToInclude)), {
          src: this.getSrc(),
          crossOrigin: this.getCrossOrigin(),
          filters
        });
        if (this.resizeFilter) {
          object.resizeFilter = this.resizeFilter.toObject();
        }
        return object;
      },
      hasCrop: function() {
        return this.cropX || this.cropY || this.width < this._element.width || this.height < this._element.height;
      },
      _toSVG: function() {
        var svgString = [], imageMarkup = [], strokeSvg, element = this._element, x2 = -this.width / 2, y2 = -this.height / 2, clipPath = "", imageRendering = "";
        if (!element) {
          return [];
        }
        if (this.hasCrop()) {
          var clipPathId = fabric2.Object.__uid++;
          svgString.push('<clipPath id="imageCrop_' + clipPathId + '">\n', '	<rect x="' + x2 + '" y="' + y2 + '" width="' + this.width + '" height="' + this.height + '" />\n', "</clipPath>\n");
          clipPath = ' clip-path="url(#imageCrop_' + clipPathId + ')" ';
        }
        if (!this.imageSmoothing) {
          imageRendering = '" image-rendering="optimizeSpeed';
        }
        imageMarkup.push("	<image ", "COMMON_PARTS", 'xlink:href="', this.getSvgSrc(true), '" x="', x2 - this.cropX, '" y="', y2 - this.cropY, '" width="', element.width || element.naturalWidth, '" height="', element.height || element.height, imageRendering, '"', clipPath, "></image>\n");
        if (this.stroke || this.strokeDashArray) {
          var origFill = this.fill;
          this.fill = null;
          strokeSvg = [
            "	<rect ",
            'x="',
            x2,
            '" y="',
            y2,
            '" width="',
            this.width,
            '" height="',
            this.height,
            '" style="',
            this.getSvgStyles(),
            '"/>\n'
          ];
          this.fill = origFill;
        }
        if (this.paintFirst !== "fill") {
          svgString = svgString.concat(strokeSvg, imageMarkup);
        } else {
          svgString = svgString.concat(imageMarkup, strokeSvg);
        }
        return svgString;
      },
      getSrc: function(filtered) {
        var element = filtered ? this._element : this._originalElement;
        if (element) {
          if (element.toDataURL) {
            return element.toDataURL();
          }
          if (this.srcFromAttribute) {
            return element.getAttribute("src");
          } else {
            return element.src;
          }
        } else {
          return this.src || "";
        }
      },
      setSrc: function(src, callback, options) {
        fabric2.util.loadImage(src, function(img, isError2) {
          this.setElement(img, options);
          this._setWidthHeight();
          callback && callback(this, isError2);
        }, this, options && options.crossOrigin);
        return this;
      },
      toString: function() {
        return '#<fabric.Image: { src: "' + this.getSrc() + '" }>';
      },
      applyResizeFilters: function() {
        var filter2 = this.resizeFilter, minimumScale = this.minimumScaleTrigger, objectScale = this.getTotalObjectScaling(), scaleX = objectScale.scaleX, scaleY = objectScale.scaleY, elementToFilter = this._filteredEl || this._originalElement;
        if (this.group) {
          this.set("dirty", true);
        }
        if (!filter2 || scaleX > minimumScale && scaleY > minimumScale) {
          this._element = elementToFilter;
          this._filterScalingX = 1;
          this._filterScalingY = 1;
          this._lastScaleX = scaleX;
          this._lastScaleY = scaleY;
          return;
        }
        if (!fabric2.filterBackend) {
          fabric2.filterBackend = fabric2.initFilterBackend();
        }
        var canvasEl = fabric2.util.createCanvasElement(), cacheKey = this._filteredEl ? this.cacheKey + "_filtered" : this.cacheKey, sourceWidth = elementToFilter.width, sourceHeight = elementToFilter.height;
        canvasEl.width = sourceWidth;
        canvasEl.height = sourceHeight;
        this._element = canvasEl;
        this._lastScaleX = filter2.scaleX = scaleX;
        this._lastScaleY = filter2.scaleY = scaleY;
        fabric2.filterBackend.applyFilters([filter2], elementToFilter, sourceWidth, sourceHeight, this._element, cacheKey);
        this._filterScalingX = canvasEl.width / this._originalElement.width;
        this._filterScalingY = canvasEl.height / this._originalElement.height;
      },
      applyFilters: function(filters) {
        filters = filters || this.filters || [];
        filters = filters.filter(function(filter2) {
          return filter2 && !filter2.isNeutralState();
        });
        this.set("dirty", true);
        this.removeTexture(this.cacheKey + "_filtered");
        if (filters.length === 0) {
          this._element = this._originalElement;
          this._filteredEl = null;
          this._filterScalingX = 1;
          this._filterScalingY = 1;
          return this;
        }
        var imgElement = this._originalElement, sourceWidth = imgElement.naturalWidth || imgElement.width, sourceHeight = imgElement.naturalHeight || imgElement.height;
        if (this._element === this._originalElement) {
          var canvasEl = fabric2.util.createCanvasElement();
          canvasEl.width = sourceWidth;
          canvasEl.height = sourceHeight;
          this._element = canvasEl;
          this._filteredEl = canvasEl;
        } else {
          this._element = this._filteredEl;
          this._filteredEl.getContext("2d").clearRect(0, 0, sourceWidth, sourceHeight);
          this._lastScaleX = 1;
          this._lastScaleY = 1;
        }
        if (!fabric2.filterBackend) {
          fabric2.filterBackend = fabric2.initFilterBackend();
        }
        fabric2.filterBackend.applyFilters(filters, this._originalElement, sourceWidth, sourceHeight, this._element, this.cacheKey);
        if (this._originalElement.width !== this._element.width || this._originalElement.height !== this._element.height) {
          this._filterScalingX = this._element.width / this._originalElement.width;
          this._filterScalingY = this._element.height / this._originalElement.height;
        }
        return this;
      },
      _render: function(ctx) {
        fabric2.util.setImageSmoothing(ctx, this.imageSmoothing);
        if (this.isMoving !== true && this.resizeFilter && this._needsResize()) {
          this.applyResizeFilters();
        }
        this._stroke(ctx);
        this._renderPaintInOrder(ctx);
      },
      drawCacheOnCanvas: function(ctx) {
        fabric2.util.setImageSmoothing(ctx, this.imageSmoothing);
        fabric2.Object.prototype.drawCacheOnCanvas.call(this, ctx);
      },
      shouldCache: function() {
        return this.needsItsOwnCache();
      },
      _renderFill: function(ctx) {
        var elementToDraw = this._element;
        if (!elementToDraw) {
          return;
        }
        var scaleX = this._filterScalingX, scaleY = this._filterScalingY, w2 = this.width, h2 = this.height, min = Math.min, max = Math.max, cropX = max(this.cropX, 0), cropY = max(this.cropY, 0), elWidth = elementToDraw.naturalWidth || elementToDraw.width, elHeight = elementToDraw.naturalHeight || elementToDraw.height, sX = cropX * scaleX, sY = cropY * scaleY, sW = min(w2 * scaleX, elWidth - sX), sH = min(h2 * scaleY, elHeight - sY), x2 = -w2 / 2, y2 = -h2 / 2, maxDestW = min(w2, elWidth / scaleX - cropX), maxDestH = min(h2, elHeight / scaleY - cropY);
        elementToDraw && ctx.drawImage(elementToDraw, sX, sY, sW, sH, x2, y2, maxDestW, maxDestH);
      },
      _needsResize: function() {
        var scale2 = this.getTotalObjectScaling();
        return scale2.scaleX !== this._lastScaleX || scale2.scaleY !== this._lastScaleY;
      },
      _resetWidthHeight: function() {
        this.set(this.getOriginalSize());
      },
      _initElement: function(element, options) {
        this.setElement(fabric2.util.getById(element), options);
        fabric2.util.addClass(this.getElement(), fabric2.Image.CSS_CANVAS);
      },
      _initConfig: function(options) {
        options || (options = {});
        this.setOptions(options);
        this._setWidthHeight(options);
      },
      _initFilters: function(filters, callback) {
        if (filters && filters.length) {
          fabric2.util.enlivenObjects(filters, function(enlivenedObjects) {
            callback && callback(enlivenedObjects);
          }, "fabric.Image.filters");
        } else {
          callback && callback();
        }
      },
      _setWidthHeight: function(options) {
        options || (options = {});
        var el = this.getElement();
        this.width = options.width || el.naturalWidth || el.width || 0;
        this.height = options.height || el.naturalHeight || el.height || 0;
      },
      parsePreserveAspectRatioAttribute: function() {
        var pAR = fabric2.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio || ""), rWidth = this._element.width, rHeight = this._element.height, scaleX = 1, scaleY = 1, offsetLeft = 0, offsetTop = 0, cropX = 0, cropY = 0, offset2, pWidth = this.width, pHeight = this.height, parsedAttributes = { width: pWidth, height: pHeight };
        if (pAR && (pAR.alignX !== "none" || pAR.alignY !== "none")) {
          if (pAR.meetOrSlice === "meet") {
            scaleX = scaleY = fabric2.util.findScaleToFit(this._element, parsedAttributes);
            offset2 = (pWidth - rWidth * scaleX) / 2;
            if (pAR.alignX === "Min") {
              offsetLeft = -offset2;
            }
            if (pAR.alignX === "Max") {
              offsetLeft = offset2;
            }
            offset2 = (pHeight - rHeight * scaleY) / 2;
            if (pAR.alignY === "Min") {
              offsetTop = -offset2;
            }
            if (pAR.alignY === "Max") {
              offsetTop = offset2;
            }
          }
          if (pAR.meetOrSlice === "slice") {
            scaleX = scaleY = fabric2.util.findScaleToCover(this._element, parsedAttributes);
            offset2 = rWidth - pWidth / scaleX;
            if (pAR.alignX === "Mid") {
              cropX = offset2 / 2;
            }
            if (pAR.alignX === "Max") {
              cropX = offset2;
            }
            offset2 = rHeight - pHeight / scaleY;
            if (pAR.alignY === "Mid") {
              cropY = offset2 / 2;
            }
            if (pAR.alignY === "Max") {
              cropY = offset2;
            }
            rWidth = pWidth / scaleX;
            rHeight = pHeight / scaleY;
          }
        } else {
          scaleX = pWidth / rWidth;
          scaleY = pHeight / rHeight;
        }
        return {
          width: rWidth,
          height: rHeight,
          scaleX,
          scaleY,
          offsetLeft,
          offsetTop,
          cropX,
          cropY
        };
      }
    });
    fabric2.Image.CSS_CANVAS = "canvas-img";
    fabric2.Image.prototype.getSvgSrc = fabric2.Image.prototype.getSrc;
    fabric2.Image.fromObject = function(_object, callback) {
      var object = fabric2.util.object.clone(_object);
      fabric2.util.loadImage(object.src, function(img, isError2) {
        if (isError2) {
          callback && callback(null, true);
          return;
        }
        fabric2.Image.prototype._initFilters.call(object, object.filters, function(filters) {
          object.filters = filters || [];
          fabric2.Image.prototype._initFilters.call(object, [object.resizeFilter], function(resizeFilters) {
            object.resizeFilter = resizeFilters[0];
            fabric2.util.enlivenObjects([object.clipPath], function(enlivedProps) {
              object.clipPath = enlivedProps[0];
              var image = new fabric2.Image(img, object);
              callback(image, false);
            });
          });
        });
      }, null, object.crossOrigin);
    };
    fabric2.Image.fromURL = function(url, callback, imgOptions) {
      fabric2.util.loadImage(url, function(img, isError2) {
        callback && callback(new fabric2.Image(img, imgOptions), isError2);
      }, null, imgOptions && imgOptions.crossOrigin);
    };
    fabric2.Image.ATTRIBUTE_NAMES = fabric2.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin image-rendering".split(" "));
    fabric2.Image.fromElement = function(element, callback, options) {
      var parsedAttributes = fabric2.parseAttributes(element, fabric2.Image.ATTRIBUTE_NAMES);
      fabric2.Image.fromURL(parsedAttributes["xlink:href"], callback, extend(options ? fabric2.util.object.clone(options) : {}, parsedAttributes));
    };
  })(exports2);
  fabric2.util.object.extend(fabric2.Object.prototype, {
    _getAngleValueForStraighten: function() {
      var angle = this.angle % 360;
      if (angle > 0) {
        return Math.round((angle - 1) / 90) * 90;
      }
      return Math.round(angle / 90) * 90;
    },
    straighten: function() {
      this.rotate(this._getAngleValueForStraighten());
      return this;
    },
    fxStraighten: function(callbacks) {
      callbacks = callbacks || {};
      var empty = function() {
      }, onComplete = callbacks.onComplete || empty, onChange = callbacks.onChange || empty, _this = this;
      fabric2.util.animate({
        startValue: this.get("angle"),
        endValue: this._getAngleValueForStraighten(),
        duration: this.FX_DURATION,
        onChange: function(value) {
          _this.rotate(value);
          onChange();
        },
        onComplete: function() {
          _this.setCoords();
          onComplete();
        }
      });
      return this;
    }
  });
  fabric2.util.object.extend(fabric2.StaticCanvas.prototype, {
    straightenObject: function(object) {
      object.straighten();
      this.requestRenderAll();
      return this;
    },
    fxStraightenObject: function(object) {
      object.fxStraighten({
        onChange: this.requestRenderAllBound
      });
      return this;
    }
  });
  (function() {
    function testPrecision(gl, precision) {
      var fragmentSource = "precision " + precision + " float;\nvoid main(){}";
      var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
      gl.shaderSource(fragmentShader, fragmentSource);
      gl.compileShader(fragmentShader);
      if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
        return false;
      }
      return true;
    }
    fabric2.isWebglSupported = function(tileSize) {
      if (fabric2.isLikelyNode) {
        return false;
      }
      tileSize = tileSize || fabric2.WebglFilterBackend.prototype.tileSize;
      var canvas = document.createElement("canvas");
      var gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
      var isSupported = false;
      if (gl) {
        fabric2.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
        isSupported = fabric2.maxTextureSize >= tileSize;
        var precisions = ["highp", "mediump", "lowp"];
        for (var i2 = 0; i2 < 3; i2++) {
          if (testPrecision(gl, precisions[i2])) {
            fabric2.webGlPrecision = precisions[i2];
            break;
          }
        }
      }
      this.isSupported = isSupported;
      return isSupported;
    };
    fabric2.WebglFilterBackend = WebglFilterBackend;
    function WebglFilterBackend(options) {
      if (options && options.tileSize) {
        this.tileSize = options.tileSize;
      }
      this.setupGLContext(this.tileSize, this.tileSize);
      this.captureGPUInfo();
    }
    WebglFilterBackend.prototype = {
      tileSize: 2048,
      resources: {},
      setupGLContext: function(width, height) {
        this.dispose();
        this.createWebGLCanvas(width, height);
        this.aPosition = new Float32Array([0, 0, 0, 1, 1, 0, 1, 1]);
        this.chooseFastestCopyGLTo2DMethod(width, height);
      },
      chooseFastestCopyGLTo2DMethod: function(width, height) {
        var canMeasurePerf = typeof window.performance !== "undefined", canUseImageData;
        try {
          new ImageData(1, 1);
          canUseImageData = true;
        } catch (e2) {
          canUseImageData = false;
        }
        var canUseArrayBuffer = typeof ArrayBuffer !== "undefined";
        var canUseUint8Clamped = typeof Uint8ClampedArray !== "undefined";
        if (!(canMeasurePerf && canUseImageData && canUseArrayBuffer && canUseUint8Clamped)) {
          return;
        }
        var targetCanvas = fabric2.util.createCanvasElement();
        var imageBuffer = new ArrayBuffer(width * height * 4);
        if (fabric2.forceGLPutImageData) {
          this.imageBuffer = imageBuffer;
          this.copyGLTo2D = copyGLTo2DPutImageData;
          return;
        }
        var testContext = {
          imageBuffer,
          destinationWidth: width,
          destinationHeight: height,
          targetCanvas
        };
        var startTime, drawImageTime, putImageDataTime;
        targetCanvas.width = width;
        targetCanvas.height = height;
        startTime = window.performance.now();
        copyGLTo2DDrawImage.call(testContext, this.gl, testContext);
        drawImageTime = window.performance.now() - startTime;
        startTime = window.performance.now();
        copyGLTo2DPutImageData.call(testContext, this.gl, testContext);
        putImageDataTime = window.performance.now() - startTime;
        if (drawImageTime > putImageDataTime) {
          this.imageBuffer = imageBuffer;
          this.copyGLTo2D = copyGLTo2DPutImageData;
        } else {
          this.copyGLTo2D = copyGLTo2DDrawImage;
        }
      },
      createWebGLCanvas: function(width, height) {
        var canvas = fabric2.util.createCanvasElement();
        canvas.width = width;
        canvas.height = height;
        var glOptions = {
          alpha: true,
          premultipliedAlpha: false,
          depth: false,
          stencil: false,
          antialias: false
        }, gl = canvas.getContext("webgl", glOptions);
        if (!gl) {
          gl = canvas.getContext("experimental-webgl", glOptions);
        }
        if (!gl) {
          return;
        }
        gl.clearColor(0, 0, 0, 0);
        this.canvas = canvas;
        this.gl = gl;
      },
      applyFilters: function(filters, source, width, height, targetCanvas, cacheKey) {
        var gl = this.gl;
        var cachedTexture;
        if (cacheKey) {
          cachedTexture = this.getCachedTexture(cacheKey, source);
        }
        var pipelineState = {
          originalWidth: source.width || source.originalWidth,
          originalHeight: source.height || source.originalHeight,
          sourceWidth: width,
          sourceHeight: height,
          destinationWidth: width,
          destinationHeight: height,
          context: gl,
          sourceTexture: this.createTexture(gl, width, height, !cachedTexture && source),
          targetTexture: this.createTexture(gl, width, height),
          originalTexture: cachedTexture || this.createTexture(gl, width, height, !cachedTexture && source),
          passes: filters.length,
          webgl: true,
          aPosition: this.aPosition,
          programCache: this.programCache,
          pass: 0,
          filterBackend: this,
          targetCanvas
        };
        var tempFbo = gl.createFramebuffer();
        gl.bindFramebuffer(gl.FRAMEBUFFER, tempFbo);
        filters.forEach(function(filter2) {
          filter2 && filter2.applyTo(pipelineState);
        });
        resizeCanvasIfNeeded(pipelineState);
        this.copyGLTo2D(gl, pipelineState);
        gl.bindTexture(gl.TEXTURE_2D, null);
        gl.deleteTexture(pipelineState.sourceTexture);
        gl.deleteTexture(pipelineState.targetTexture);
        gl.deleteFramebuffer(tempFbo);
        targetCanvas.getContext("2d").setTransform(1, 0, 0, 1, 0, 0);
        return pipelineState;
      },
      dispose: function() {
        if (this.canvas) {
          this.canvas = null;
          this.gl = null;
        }
        this.clearWebGLCaches();
      },
      clearWebGLCaches: function() {
        this.programCache = {};
        this.textureCache = {};
      },
      createTexture: function(gl, width, height, textureImageSource) {
        var texture = gl.createTexture();
        gl.bindTexture(gl.TEXTURE_2D, texture);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
        if (textureImageSource) {
          gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, textureImageSource);
        } else {
          gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
        }
        return texture;
      },
      getCachedTexture: function(uniqueId, textureImageSource) {
        if (this.textureCache[uniqueId]) {
          return this.textureCache[uniqueId];
        } else {
          var texture = this.createTexture(this.gl, textureImageSource.width, textureImageSource.height, textureImageSource);
          this.textureCache[uniqueId] = texture;
          return texture;
        }
      },
      evictCachesForKey: function(cacheKey) {
        if (this.textureCache[cacheKey]) {
          this.gl.deleteTexture(this.textureCache[cacheKey]);
          delete this.textureCache[cacheKey];
        }
      },
      copyGLTo2D: copyGLTo2DDrawImage,
      captureGPUInfo: function() {
        if (this.gpuInfo) {
          return this.gpuInfo;
        }
        var gl = this.gl, gpuInfo = { renderer: "", vendor: "" };
        if (!gl) {
          return gpuInfo;
        }
        var ext = gl.getExtension("WEBGL_debug_renderer_info");
        if (ext) {
          var renderer = gl.getParameter(ext.UNMASKED_RENDERER_WEBGL);
          var vendor = gl.getParameter(ext.UNMASKED_VENDOR_WEBGL);
          if (renderer) {
            gpuInfo.renderer = renderer.toLowerCase();
          }
          if (vendor) {
            gpuInfo.vendor = vendor.toLowerCase();
          }
        }
        this.gpuInfo = gpuInfo;
        return gpuInfo;
      }
    };
  })();
  function resizeCanvasIfNeeded(pipelineState) {
    var targetCanvas = pipelineState.targetCanvas, width = targetCanvas.width, height = targetCanvas.height, dWidth = pipelineState.destinationWidth, dHeight = pipelineState.destinationHeight;
    if (width !== dWidth || height !== dHeight) {
      targetCanvas.width = dWidth;
      targetCanvas.height = dHeight;
    }
  }
  function copyGLTo2DDrawImage(gl, pipelineState) {
    var glCanvas = gl.canvas, targetCanvas = pipelineState.targetCanvas, ctx = targetCanvas.getContext("2d");
    ctx.translate(0, targetCanvas.height);
    ctx.scale(1, -1);
    var sourceY = glCanvas.height - targetCanvas.height;
    ctx.drawImage(glCanvas, 0, sourceY, targetCanvas.width, targetCanvas.height, 0, 0, targetCanvas.width, targetCanvas.height);
  }
  function copyGLTo2DPutImageData(gl, pipelineState) {
    var targetCanvas = pipelineState.targetCanvas, ctx = targetCanvas.getContext("2d"), dWidth = pipelineState.destinationWidth, dHeight = pipelineState.destinationHeight, numBytes = dWidth * dHeight * 4;
    var u8 = new Uint8Array(this.imageBuffer, 0, numBytes);
    var u8Clamped = new Uint8ClampedArray(this.imageBuffer, 0, numBytes);
    gl.readPixels(0, 0, dWidth, dHeight, gl.RGBA, gl.UNSIGNED_BYTE, u8);
    var imgData = new ImageData(u8Clamped, dWidth, dHeight);
    ctx.putImageData(imgData, 0, 0);
  }
  (function() {
    var noop2 = function() {
    };
    fabric2.Canvas2dFilterBackend = Canvas2dFilterBackend;
    function Canvas2dFilterBackend() {
    }
    Canvas2dFilterBackend.prototype = {
      evictCachesForKey: noop2,
      dispose: noop2,
      clearWebGLCaches: noop2,
      resources: {},
      applyFilters: function(filters, sourceElement, sourceWidth, sourceHeight, targetCanvas) {
        var ctx = targetCanvas.getContext("2d");
        ctx.drawImage(sourceElement, 0, 0, sourceWidth, sourceHeight);
        var imageData = ctx.getImageData(0, 0, sourceWidth, sourceHeight);
        var originalImageData = ctx.getImageData(0, 0, sourceWidth, sourceHeight);
        var pipelineState = {
          sourceWidth,
          sourceHeight,
          imageData,
          originalEl: sourceElement,
          originalImageData,
          canvasEl: targetCanvas,
          ctx,
          filterBackend: this
        };
        filters.forEach(function(filter2) {
          filter2.applyTo(pipelineState);
        });
        if (pipelineState.imageData.width !== sourceWidth || pipelineState.imageData.height !== sourceHeight) {
          targetCanvas.width = pipelineState.imageData.width;
          targetCanvas.height = pipelineState.imageData.height;
        }
        ctx.putImageData(pipelineState.imageData, 0, 0);
        return pipelineState;
      }
    };
  })();
  fabric2.Image = fabric2.Image || {};
  fabric2.Image.filters = fabric2.Image.filters || {};
  fabric2.Image.filters.BaseFilter = fabric2.util.createClass({
    type: "BaseFilter",
    vertexSource: "attribute vec2 aPosition;\nvarying vec2 vTexCoord;\nvoid main() {\nvTexCoord = aPosition;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",
    fragmentSource: "precision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2D uTexture;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\n}",
    initialize: function(options) {
      if (options) {
        this.setOptions(options);
      }
    },
    setOptions: function(options) {
      for (var prop in options) {
        this[prop] = options[prop];
      }
    },
    createProgram: function(gl, fragmentSource, vertexSource) {
      fragmentSource = fragmentSource || this.fragmentSource;
      vertexSource = vertexSource || this.vertexSource;
      if (fabric2.webGlPrecision !== "highp") {
        fragmentSource = fragmentSource.replace(/precision highp float/g, "precision " + fabric2.webGlPrecision + " float");
      }
      var vertexShader = gl.createShader(gl.VERTEX_SHADER);
      gl.shaderSource(vertexShader, vertexSource);
      gl.compileShader(vertexShader);
      if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {
        throw new Error("Vertex shader compile error for " + this.type + ": " + gl.getShaderInfoLog(vertexShader));
      }
      var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
      gl.shaderSource(fragmentShader, fragmentSource);
      gl.compileShader(fragmentShader);
      if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
        throw new Error("Fragment shader compile error for " + this.type + ": " + gl.getShaderInfoLog(fragmentShader));
      }
      var program = gl.createProgram();
      gl.attachShader(program, vertexShader);
      gl.attachShader(program, fragmentShader);
      gl.linkProgram(program);
      if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
        throw new Error('Shader link error for "${this.type}" ' + gl.getProgramInfoLog(program));
      }
      var attributeLocations = this.getAttributeLocations(gl, program);
      var uniformLocations = this.getUniformLocations(gl, program) || {};
      uniformLocations.uStepW = gl.getUniformLocation(program, "uStepW");
      uniformLocations.uStepH = gl.getUniformLocation(program, "uStepH");
      return {
        program,
        attributeLocations,
        uniformLocations
      };
    },
    getAttributeLocations: function(gl, program) {
      return {
        aPosition: gl.getAttribLocation(program, "aPosition")
      };
    },
    getUniformLocations: function() {
      return {};
    },
    sendAttributeData: function(gl, attributeLocations, aPositionData) {
      var attributeLocation = attributeLocations.aPosition;
      var buffer = gl.createBuffer();
      gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
      gl.enableVertexAttribArray(attributeLocation);
      gl.vertexAttribPointer(attributeLocation, 2, gl.FLOAT, false, 0, 0);
      gl.bufferData(gl.ARRAY_BUFFER, aPositionData, gl.STATIC_DRAW);
    },
    _setupFrameBuffer: function(options) {
      var gl = options.context, width, height;
      if (options.passes > 1) {
        width = options.destinationWidth;
        height = options.destinationHeight;
        if (options.sourceWidth !== width || options.sourceHeight !== height) {
          gl.deleteTexture(options.targetTexture);
          options.targetTexture = options.filterBackend.createTexture(gl, width, height);
        }
        gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, options.targetTexture, 0);
      } else {
        gl.bindFramebuffer(gl.FRAMEBUFFER, null);
        gl.finish();
      }
    },
    _swapTextures: function(options) {
      options.passes--;
      options.pass++;
      var temp = options.targetTexture;
      options.targetTexture = options.sourceTexture;
      options.sourceTexture = temp;
    },
    isNeutralState: function() {
      var main2 = this.mainParameter, _class = fabric2.Image.filters[this.type].prototype;
      if (main2) {
        if (Array.isArray(_class[main2])) {
          for (var i2 = _class[main2].length; i2--; ) {
            if (this[main2][i2] !== _class[main2][i2]) {
              return false;
            }
          }
          return true;
        } else {
          return _class[main2] === this[main2];
        }
      } else {
        return false;
      }
    },
    applyTo: function(options) {
      if (options.webgl) {
        this._setupFrameBuffer(options);
        this.applyToWebGL(options);
        this._swapTextures(options);
      } else {
        this.applyTo2d(options);
      }
    },
    retrieveShader: function(options) {
      if (!options.programCache.hasOwnProperty(this.type)) {
        options.programCache[this.type] = this.createProgram(options.context);
      }
      return options.programCache[this.type];
    },
    applyToWebGL: function(options) {
      var gl = options.context;
      var shader = this.retrieveShader(options);
      if (options.pass === 0 && options.originalTexture) {
        gl.bindTexture(gl.TEXTURE_2D, options.originalTexture);
      } else {
        gl.bindTexture(gl.TEXTURE_2D, options.sourceTexture);
      }
      gl.useProgram(shader.program);
      this.sendAttributeData(gl, shader.attributeLocations, options.aPosition);
      gl.uniform1f(shader.uniformLocations.uStepW, 1 / options.sourceWidth);
      gl.uniform1f(shader.uniformLocations.uStepH, 1 / options.sourceHeight);
      this.sendUniformData(gl, shader.uniformLocations);
      gl.viewport(0, 0, options.destinationWidth, options.destinationHeight);
      gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
    },
    bindAdditionalTexture: function(gl, texture, textureUnit) {
      gl.activeTexture(textureUnit);
      gl.bindTexture(gl.TEXTURE_2D, texture);
      gl.activeTexture(gl.TEXTURE0);
    },
    unbindAdditionalTexture: function(gl, textureUnit) {
      gl.activeTexture(textureUnit);
      gl.bindTexture(gl.TEXTURE_2D, null);
      gl.activeTexture(gl.TEXTURE0);
    },
    getMainParameter: function() {
      return this[this.mainParameter];
    },
    setMainParameter: function(value) {
      this[this.mainParameter] = value;
    },
    sendUniformData: function() {
    },
    createHelpLayer: function(options) {
      if (!options.helpLayer) {
        var helpLayer = document.createElement("canvas");
        helpLayer.width = options.sourceWidth;
        helpLayer.height = options.sourceHeight;
        options.helpLayer = helpLayer;
      }
    },
    toObject: function() {
      var object = { type: this.type }, mainP = this.mainParameter;
      if (mainP) {
        object[mainP] = this[mainP];
      }
      return object;
    },
    toJSON: function() {
      return this.toObject();
    }
  });
  fabric2.Image.filters.BaseFilter.fromObject = function(object, callback) {
    var filter2 = new fabric2.Image.filters[object.type](object);
    callback && callback(filter2);
    return filter2;
  };
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {}), filters = fabric3.Image.filters, createClass = fabric3.util.createClass;
    filters.ColorMatrix = createClass(filters.BaseFilter, {
      type: "ColorMatrix",
      fragmentSource: "precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nuniform mat4 uColorMatrix;\nuniform vec4 uConstants;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor *= uColorMatrix;\ncolor += uConstants;\ngl_FragColor = color;\n}",
      matrix: [
        1,
        0,
        0,
        0,
        0,
        0,
        1,
        0,
        0,
        0,
        0,
        0,
        1,
        0,
        0,
        0,
        0,
        0,
        1,
        0
      ],
      mainParameter: "matrix",
      colorsOnly: true,
      initialize: function(options) {
        this.callSuper("initialize", options);
        this.matrix = this.matrix.slice(0);
      },
      applyTo2d: function(options) {
        var imageData = options.imageData, data = imageData.data, iLen = data.length, m2 = this.matrix, r2, g2, b2, a2, i2, colorsOnly = this.colorsOnly;
        for (i2 = 0; i2 < iLen; i2 += 4) {
          r2 = data[i2];
          g2 = data[i2 + 1];
          b2 = data[i2 + 2];
          if (colorsOnly) {
            data[i2] = r2 * m2[0] + g2 * m2[1] + b2 * m2[2] + m2[4] * 255;
            data[i2 + 1] = r2 * m2[5] + g2 * m2[6] + b2 * m2[7] + m2[9] * 255;
            data[i2 + 2] = r2 * m2[10] + g2 * m2[11] + b2 * m2[12] + m2[14] * 255;
          } else {
            a2 = data[i2 + 3];
            data[i2] = r2 * m2[0] + g2 * m2[1] + b2 * m2[2] + a2 * m2[3] + m2[4] * 255;
            data[i2 + 1] = r2 * m2[5] + g2 * m2[6] + b2 * m2[7] + a2 * m2[8] + m2[9] * 255;
            data[i2 + 2] = r2 * m2[10] + g2 * m2[11] + b2 * m2[12] + a2 * m2[13] + m2[14] * 255;
            data[i2 + 3] = r2 * m2[15] + g2 * m2[16] + b2 * m2[17] + a2 * m2[18] + m2[19] * 255;
          }
        }
      },
      getUniformLocations: function(gl, program) {
        return {
          uColorMatrix: gl.getUniformLocation(program, "uColorMatrix"),
          uConstants: gl.getUniformLocation(program, "uConstants")
        };
      },
      sendUniformData: function(gl, uniformLocations) {
        var m2 = this.matrix, matrix = [
          m2[0],
          m2[1],
          m2[2],
          m2[3],
          m2[5],
          m2[6],
          m2[7],
          m2[8],
          m2[10],
          m2[11],
          m2[12],
          m2[13],
          m2[15],
          m2[16],
          m2[17],
          m2[18]
        ], constants = [m2[4], m2[9], m2[14], m2[19]];
        gl.uniformMatrix4fv(uniformLocations.uColorMatrix, false, matrix);
        gl.uniform4fv(uniformLocations.uConstants, constants);
      }
    });
    fabric3.Image.filters.ColorMatrix.fromObject = fabric3.Image.filters.BaseFilter.fromObject;
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {}), filters = fabric3.Image.filters, createClass = fabric3.util.createClass;
    filters.Brightness = createClass(filters.BaseFilter, {
      type: "Brightness",
      fragmentSource: "precision highp float;\nuniform sampler2D uTexture;\nuniform float uBrightness;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor.rgb += uBrightness;\ngl_FragColor = color;\n}",
      brightness: 0,
      mainParameter: "brightness",
      applyTo2d: function(options) {
        if (this.brightness === 0) {
          return;
        }
        var imageData = options.imageData, data = imageData.data, i2, len = data.length, brightness = Math.round(this.brightness * 255);
        for (i2 = 0; i2 < len; i2 += 4) {
          data[i2] = data[i2] + brightness;
          data[i2 + 1] = data[i2 + 1] + brightness;
          data[i2 + 2] = data[i2 + 2] + brightness;
        }
      },
      getUniformLocations: function(gl, program) {
        return {
          uBrightness: gl.getUniformLocation(program, "uBrightness")
        };
      },
      sendUniformData: function(gl, uniformLocations) {
        gl.uniform1f(uniformLocations.uBrightness, this.brightness);
      }
    });
    fabric3.Image.filters.Brightness.fromObject = fabric3.Image.filters.BaseFilter.fromObject;
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {}), extend = fabric3.util.object.extend, filters = fabric3.Image.filters, createClass = fabric3.util.createClass;
    filters.Convolute = createClass(filters.BaseFilter, {
      type: "Convolute",
      opaque: false,
      matrix: [0, 0, 0, 0, 1, 0, 0, 0, 0],
      fragmentSource: {
        Convolute_3_1: "precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[9];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 0);\nfor (float h = 0.0; h < 3.0; h+=1.0) {\nfor (float w = 0.0; w < 3.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 1), uStepH * (h - 1));\ncolor += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 3.0 + w)];\n}\n}\ngl_FragColor = color;\n}",
        Convolute_3_0: "precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[9];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 1);\nfor (float h = 0.0; h < 3.0; h+=1.0) {\nfor (float w = 0.0; w < 3.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 1.0), uStepH * (h - 1.0));\ncolor.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 3.0 + w)];\n}\n}\nfloat alpha = texture2D(uTexture, vTexCoord).a;\ngl_FragColor = color;\ngl_FragColor.a = alpha;\n}",
        Convolute_5_1: "precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[25];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 0);\nfor (float h = 0.0; h < 5.0; h+=1.0) {\nfor (float w = 0.0; w < 5.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 2.0), uStepH * (h - 2.0));\ncolor += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 5.0 + w)];\n}\n}\ngl_FragColor = color;\n}",
        Convolute_5_0: "precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[25];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 1);\nfor (float h = 0.0; h < 5.0; h+=1.0) {\nfor (float w = 0.0; w < 5.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 2.0), uStepH * (h - 2.0));\ncolor.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 5.0 + w)];\n}\n}\nfloat alpha = texture2D(uTexture, vTexCoord).a;\ngl_FragColor = color;\ngl_FragColor.a = alpha;\n}",
        Convolute_7_1: "precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[49];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 0);\nfor (float h = 0.0; h < 7.0; h+=1.0) {\nfor (float w = 0.0; w < 7.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 3.0), uStepH * (h - 3.0));\ncolor += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 7.0 + w)];\n}\n}\ngl_FragColor = color;\n}",
        Convolute_7_0: "precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[49];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 1);\nfor (float h = 0.0; h < 7.0; h+=1.0) {\nfor (float w = 0.0; w < 7.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 3.0), uStepH * (h - 3.0));\ncolor.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 7.0 + w)];\n}\n}\nfloat alpha = texture2D(uTexture, vTexCoord).a;\ngl_FragColor = color;\ngl_FragColor.a = alpha;\n}",
        Convolute_9_1: "precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[81];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 0);\nfor (float h = 0.0; h < 9.0; h+=1.0) {\nfor (float w = 0.0; w < 9.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 4.0), uStepH * (h - 4.0));\ncolor += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 9.0 + w)];\n}\n}\ngl_FragColor = color;\n}",
        Convolute_9_0: "precision highp float;\nuniform sampler2D uTexture;\nuniform float uMatrix[81];\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = vec4(0, 0, 0, 1);\nfor (float h = 0.0; h < 9.0; h+=1.0) {\nfor (float w = 0.0; w < 9.0; w+=1.0) {\nvec2 matrixPos = vec2(uStepW * (w - 4.0), uStepH * (h - 4.0));\ncolor.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 9.0 + w)];\n}\n}\nfloat alpha = texture2D(uTexture, vTexCoord).a;\ngl_FragColor = color;\ngl_FragColor.a = alpha;\n}"
      },
      retrieveShader: function(options) {
        var size = Math.sqrt(this.matrix.length);
        var cacheKey = this.type + "_" + size + "_" + (this.opaque ? 1 : 0);
        var shaderSource = this.fragmentSource[cacheKey];
        if (!options.programCache.hasOwnProperty(cacheKey)) {
          options.programCache[cacheKey] = this.createProgram(options.context, shaderSource);
        }
        return options.programCache[cacheKey];
      },
      applyTo2d: function(options) {
        var imageData = options.imageData, data = imageData.data, weights = this.matrix, side = Math.round(Math.sqrt(weights.length)), halfSide = Math.floor(side / 2), sw = imageData.width, sh = imageData.height, output = options.ctx.createImageData(sw, sh), dst = output.data, alphaFac = this.opaque ? 1 : 0, r2, g2, b2, a2, dstOff, scx, scy, srcOff, wt, x2, y2, cx, cy;
        for (y2 = 0; y2 < sh; y2++) {
          for (x2 = 0; x2 < sw; x2++) {
            dstOff = (y2 * sw + x2) * 4;
            r2 = 0;
            g2 = 0;
            b2 = 0;
            a2 = 0;
            for (cy = 0; cy < side; cy++) {
              for (cx = 0; cx < side; cx++) {
                scy = y2 + cy - halfSide;
                scx = x2 + cx - halfSide;
                if (scy < 0 || scy >= sh || scx < 0 || scx >= sw) {
                  continue;
                }
                srcOff = (scy * sw + scx) * 4;
                wt = weights[cy * side + cx];
                r2 += data[srcOff] * wt;
                g2 += data[srcOff + 1] * wt;
                b2 += data[srcOff + 2] * wt;
                if (!alphaFac) {
                  a2 += data[srcOff + 3] * wt;
                }
              }
            }
            dst[dstOff] = r2;
            dst[dstOff + 1] = g2;
            dst[dstOff + 2] = b2;
            if (!alphaFac) {
              dst[dstOff + 3] = a2;
            } else {
              dst[dstOff + 3] = data[dstOff + 3];
            }
          }
        }
        options.imageData = output;
      },
      getUniformLocations: function(gl, program) {
        return {
          uMatrix: gl.getUniformLocation(program, "uMatrix"),
          uOpaque: gl.getUniformLocation(program, "uOpaque"),
          uHalfSize: gl.getUniformLocation(program, "uHalfSize"),
          uSize: gl.getUniformLocation(program, "uSize")
        };
      },
      sendUniformData: function(gl, uniformLocations) {
        gl.uniform1fv(uniformLocations.uMatrix, this.matrix);
      },
      toObject: function() {
        return extend(this.callSuper("toObject"), {
          opaque: this.opaque,
          matrix: this.matrix
        });
      }
    });
    fabric3.Image.filters.Convolute.fromObject = fabric3.Image.filters.BaseFilter.fromObject;
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {}), filters = fabric3.Image.filters, createClass = fabric3.util.createClass;
    filters.Grayscale = createClass(filters.BaseFilter, {
      type: "Grayscale",
      fragmentSource: {
        average: "precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat average = (color.r + color.b + color.g) / 3.0;\ngl_FragColor = vec4(average, average, average, color.a);\n}",
        lightness: "precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\ngl_FragColor = vec4(average, average, average, col.a);\n}",
        luminosity: "precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\ngl_FragColor = vec4(average, average, average, col.a);\n}"
      },
      mode: "average",
      mainParameter: "mode",
      applyTo2d: function(options) {
        var imageData = options.imageData, data = imageData.data, i2, len = data.length, value, mode = this.mode;
        for (i2 = 0; i2 < len; i2 += 4) {
          if (mode === "average") {
            value = (data[i2] + data[i2 + 1] + data[i2 + 2]) / 3;
          } else if (mode === "lightness") {
            value = (Math.min(data[i2], data[i2 + 1], data[i2 + 2]) + Math.max(data[i2], data[i2 + 1], data[i2 + 2])) / 2;
          } else if (mode === "luminosity") {
            value = 0.21 * data[i2] + 0.72 * data[i2 + 1] + 0.07 * data[i2 + 2];
          }
          data[i2] = value;
          data[i2 + 1] = value;
          data[i2 + 2] = value;
        }
      },
      retrieveShader: function(options) {
        var cacheKey = this.type + "_" + this.mode;
        if (!options.programCache.hasOwnProperty(cacheKey)) {
          var shaderSource = this.fragmentSource[this.mode];
          options.programCache[cacheKey] = this.createProgram(options.context, shaderSource);
        }
        return options.programCache[cacheKey];
      },
      getUniformLocations: function(gl, program) {
        return {
          uMode: gl.getUniformLocation(program, "uMode")
        };
      },
      sendUniformData: function(gl, uniformLocations) {
        var mode = 1;
        gl.uniform1i(uniformLocations.uMode, mode);
      },
      isNeutralState: function() {
        return false;
      }
    });
    fabric3.Image.filters.Grayscale.fromObject = fabric3.Image.filters.BaseFilter.fromObject;
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {}), filters = fabric3.Image.filters, createClass = fabric3.util.createClass;
    filters.Invert = createClass(filters.BaseFilter, {
      type: "Invert",
      fragmentSource: "precision highp float;\nuniform sampler2D uTexture;\nuniform int uInvert;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nif (uInvert == 1) {\ngl_FragColor = vec4(1.0 - color.r,1.0 -color.g,1.0 -color.b,color.a);\n} else {\ngl_FragColor = color;\n}\n}",
      invert: true,
      mainParameter: "invert",
      applyTo2d: function(options) {
        var imageData = options.imageData, data = imageData.data, i2, len = data.length;
        for (i2 = 0; i2 < len; i2 += 4) {
          data[i2] = 255 - data[i2];
          data[i2 + 1] = 255 - data[i2 + 1];
          data[i2 + 2] = 255 - data[i2 + 2];
        }
      },
      isNeutralState: function() {
        return !this.invert;
      },
      getUniformLocations: function(gl, program) {
        return {
          uInvert: gl.getUniformLocation(program, "uInvert")
        };
      },
      sendUniformData: function(gl, uniformLocations) {
        gl.uniform1i(uniformLocations.uInvert, this.invert);
      }
    });
    fabric3.Image.filters.Invert.fromObject = fabric3.Image.filters.BaseFilter.fromObject;
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {}), extend = fabric3.util.object.extend, filters = fabric3.Image.filters, createClass = fabric3.util.createClass;
    filters.Noise = createClass(filters.BaseFilter, {
      type: "Noise",
      fragmentSource: "precision highp float;\nuniform sampler2D uTexture;\nuniform float uStepH;\nuniform float uNoise;\nuniform float uSeed;\nvarying vec2 vTexCoord;\nfloat rand(vec2 co, float seed, float vScale) {\nreturn fract(sin(dot(co.xy * vScale ,vec2(12.9898 , 78.233))) * 43758.5453 * (seed + 0.01) / 2.0);\n}\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor.rgb += (0.5 - rand(vTexCoord, uSeed, 0.1 / uStepH)) * uNoise;\ngl_FragColor = color;\n}",
      mainParameter: "noise",
      noise: 0,
      applyTo2d: function(options) {
        if (this.noise === 0) {
          return;
        }
        var imageData = options.imageData, data = imageData.data, i2, len = data.length, noise = this.noise, rand;
        for (i2 = 0, len = data.length; i2 < len; i2 += 4) {
          rand = (0.5 - Math.random()) * noise;
          data[i2] += rand;
          data[i2 + 1] += rand;
          data[i2 + 2] += rand;
        }
      },
      getUniformLocations: function(gl, program) {
        return {
          uNoise: gl.getUniformLocation(program, "uNoise"),
          uSeed: gl.getUniformLocation(program, "uSeed")
        };
      },
      sendUniformData: function(gl, uniformLocations) {
        gl.uniform1f(uniformLocations.uNoise, this.noise / 255);
        gl.uniform1f(uniformLocations.uSeed, Math.random());
      },
      toObject: function() {
        return extend(this.callSuper("toObject"), {
          noise: this.noise
        });
      }
    });
    fabric3.Image.filters.Noise.fromObject = fabric3.Image.filters.BaseFilter.fromObject;
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {}), filters = fabric3.Image.filters, createClass = fabric3.util.createClass;
    filters.Pixelate = createClass(filters.BaseFilter, {
      type: "Pixelate",
      blocksize: 4,
      mainParameter: "blocksize",
      fragmentSource: "precision highp float;\nuniform sampler2D uTexture;\nuniform float uBlocksize;\nuniform float uStepW;\nuniform float uStepH;\nvarying vec2 vTexCoord;\nvoid main() {\nfloat blockW = uBlocksize * uStepW;\nfloat blockH = uBlocksize * uStepW;\nint posX = int(vTexCoord.x / blockW);\nint posY = int(vTexCoord.y / blockH);\nfloat fposX = float(posX);\nfloat fposY = float(posY);\nvec2 squareCoords = vec2(fposX * blockW, fposY * blockH);\nvec4 color = texture2D(uTexture, squareCoords);\ngl_FragColor = color;\n}",
      applyTo2d: function(options) {
        var imageData = options.imageData, data = imageData.data, iLen = imageData.height, jLen = imageData.width, index2, i2, j2, r2, g2, b2, a2, _i, _j, _iLen, _jLen;
        for (i2 = 0; i2 < iLen; i2 += this.blocksize) {
          for (j2 = 0; j2 < jLen; j2 += this.blocksize) {
            index2 = i2 * 4 * jLen + j2 * 4;
            r2 = data[index2];
            g2 = data[index2 + 1];
            b2 = data[index2 + 2];
            a2 = data[index2 + 3];
            _iLen = Math.min(i2 + this.blocksize, iLen);
            _jLen = Math.min(j2 + this.blocksize, jLen);
            for (_i = i2; _i < _iLen; _i++) {
              for (_j = j2; _j < _jLen; _j++) {
                index2 = _i * 4 * jLen + _j * 4;
                data[index2] = r2;
                data[index2 + 1] = g2;
                data[index2 + 2] = b2;
                data[index2 + 3] = a2;
              }
            }
          }
        }
      },
      isNeutralState: function() {
        return this.blocksize === 1;
      },
      getUniformLocations: function(gl, program) {
        return {
          uBlocksize: gl.getUniformLocation(program, "uBlocksize"),
          uStepW: gl.getUniformLocation(program, "uStepW"),
          uStepH: gl.getUniformLocation(program, "uStepH")
        };
      },
      sendUniformData: function(gl, uniformLocations) {
        gl.uniform1f(uniformLocations.uBlocksize, this.blocksize);
      }
    });
    fabric3.Image.filters.Pixelate.fromObject = fabric3.Image.filters.BaseFilter.fromObject;
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {}), extend = fabric3.util.object.extend, filters = fabric3.Image.filters, createClass = fabric3.util.createClass;
    filters.RemoveColor = createClass(filters.BaseFilter, {
      type: "RemoveColor",
      color: "#FFFFFF",
      fragmentSource: "precision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uLow;\nuniform vec4 uHigh;\nvarying vec2 vTexCoord;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\nif(all(greaterThan(gl_FragColor.rgb,uLow.rgb)) && all(greaterThan(uHigh.rgb,gl_FragColor.rgb))) {\ngl_FragColor.a = 0.0;\n}\n}",
      distance: 0.02,
      useAlpha: false,
      applyTo2d: function(options) {
        var imageData = options.imageData, data = imageData.data, i2, distance = this.distance * 255, r2, g2, b2, source = new fabric3.Color(this.color).getSource(), lowC = [
          source[0] - distance,
          source[1] - distance,
          source[2] - distance
        ], highC = [
          source[0] + distance,
          source[1] + distance,
          source[2] + distance
        ];
        for (i2 = 0; i2 < data.length; i2 += 4) {
          r2 = data[i2];
          g2 = data[i2 + 1];
          b2 = data[i2 + 2];
          if (r2 > lowC[0] && g2 > lowC[1] && b2 > lowC[2] && r2 < highC[0] && g2 < highC[1] && b2 < highC[2]) {
            data[i2 + 3] = 0;
          }
        }
      },
      getUniformLocations: function(gl, program) {
        return {
          uLow: gl.getUniformLocation(program, "uLow"),
          uHigh: gl.getUniformLocation(program, "uHigh")
        };
      },
      sendUniformData: function(gl, uniformLocations) {
        var source = new fabric3.Color(this.color).getSource(), distance = parseFloat(this.distance), lowC = [
          0 + source[0] / 255 - distance,
          0 + source[1] / 255 - distance,
          0 + source[2] / 255 - distance,
          1
        ], highC = [
          source[0] / 255 + distance,
          source[1] / 255 + distance,
          source[2] / 255 + distance,
          1
        ];
        gl.uniform4fv(uniformLocations.uLow, lowC);
        gl.uniform4fv(uniformLocations.uHigh, highC);
      },
      toObject: function() {
        return extend(this.callSuper("toObject"), {
          color: this.color,
          distance: this.distance
        });
      }
    });
    fabric3.Image.filters.RemoveColor.fromObject = fabric3.Image.filters.BaseFilter.fromObject;
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {}), filters = fabric3.Image.filters, createClass = fabric3.util.createClass;
    var matrices = {
      Brownie: [
        0.5997,
        0.34553,
        -0.27082,
        0,
        0.186,
        -0.0377,
        0.86095,
        0.15059,
        0,
        -0.1449,
        0.24113,
        -0.07441,
        0.44972,
        0,
        -0.02965,
        0,
        0,
        0,
        1,
        0
      ],
      Vintage: [
        0.62793,
        0.32021,
        -0.03965,
        0,
        0.03784,
        0.02578,
        0.64411,
        0.03259,
        0,
        0.02926,
        0.0466,
        -0.08512,
        0.52416,
        0,
        0.02023,
        0,
        0,
        0,
        1,
        0
      ],
      Kodachrome: [
        1.12855,
        -0.39673,
        -0.03992,
        0,
        0.24991,
        -0.16404,
        1.08352,
        -0.05498,
        0,
        0.09698,
        -0.16786,
        -0.56034,
        1.60148,
        0,
        0.13972,
        0,
        0,
        0,
        1,
        0
      ],
      Technicolor: [
        1.91252,
        -0.85453,
        -0.09155,
        0,
        0.04624,
        -0.30878,
        1.76589,
        -0.10601,
        0,
        -0.27589,
        -0.2311,
        -0.75018,
        1.84759,
        0,
        0.12137,
        0,
        0,
        0,
        1,
        0
      ],
      Polaroid: [
        1.438,
        -0.062,
        -0.062,
        0,
        0,
        -0.122,
        1.378,
        -0.122,
        0,
        0,
        -0.016,
        -0.016,
        1.483,
        0,
        0,
        0,
        0,
        0,
        1,
        0
      ],
      Sepia: [
        0.393,
        0.769,
        0.189,
        0,
        0,
        0.349,
        0.686,
        0.168,
        0,
        0,
        0.272,
        0.534,
        0.131,
        0,
        0,
        0,
        0,
        0,
        1,
        0
      ],
      BlackWhite: [
        1.5,
        1.5,
        1.5,
        0,
        -1,
        1.5,
        1.5,
        1.5,
        0,
        -1,
        1.5,
        1.5,
        1.5,
        0,
        -1,
        0,
        0,
        0,
        1,
        0
      ]
    };
    for (var key in matrices) {
      filters[key] = createClass(filters.ColorMatrix, {
        type: key,
        matrix: matrices[key],
        mainParameter: false,
        colorsOnly: true
      });
      fabric3.Image.filters[key].fromObject = fabric3.Image.filters.BaseFilter.fromObject;
    }
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric, filters = fabric3.Image.filters, createClass = fabric3.util.createClass;
    filters.BlendColor = createClass(filters.BaseFilter, {
      type: "BlendColor",
      color: "#F95C63",
      mode: "multiply",
      alpha: 1,
      fragmentSource: {
        multiply: "gl_FragColor.rgb *= uColor.rgb;\n",
        screen: "gl_FragColor.rgb = 1.0 - (1.0 - gl_FragColor.rgb) * (1.0 - uColor.rgb);\n",
        add: "gl_FragColor.rgb += uColor.rgb;\n",
        diff: "gl_FragColor.rgb = abs(gl_FragColor.rgb - uColor.rgb);\n",
        subtract: "gl_FragColor.rgb -= uColor.rgb;\n",
        lighten: "gl_FragColor.rgb = max(gl_FragColor.rgb, uColor.rgb);\n",
        darken: "gl_FragColor.rgb = min(gl_FragColor.rgb, uColor.rgb);\n",
        exclusion: "gl_FragColor.rgb += uColor.rgb - 2.0 * (uColor.rgb * gl_FragColor.rgb);\n",
        overlay: "if (uColor.r < 0.5) {\ngl_FragColor.r *= 2.0 * uColor.r;\n} else {\ngl_FragColor.r = 1.0 - 2.0 * (1.0 - gl_FragColor.r) * (1.0 - uColor.r);\n}\nif (uColor.g < 0.5) {\ngl_FragColor.g *= 2.0 * uColor.g;\n} else {\ngl_FragColor.g = 1.0 - 2.0 * (1.0 - gl_FragColor.g) * (1.0 - uColor.g);\n}\nif (uColor.b < 0.5) {\ngl_FragColor.b *= 2.0 * uColor.b;\n} else {\ngl_FragColor.b = 1.0 - 2.0 * (1.0 - gl_FragColor.b) * (1.0 - uColor.b);\n}\n",
        tint: "gl_FragColor.rgb *= (1.0 - uColor.a);\ngl_FragColor.rgb += uColor.rgb;\n"
      },
      buildSource: function(mode) {
        return "precision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ngl_FragColor = color;\nif (color.a > 0.0) {\n" + this.fragmentSource[mode] + "}\n}";
      },
      retrieveShader: function(options) {
        var cacheKey = this.type + "_" + this.mode, shaderSource;
        if (!options.programCache.hasOwnProperty(cacheKey)) {
          shaderSource = this.buildSource(this.mode);
          options.programCache[cacheKey] = this.createProgram(options.context, shaderSource);
        }
        return options.programCache[cacheKey];
      },
      applyTo2d: function(options) {
        var imageData = options.imageData, data = imageData.data, iLen = data.length, tr, tg, tb, r2, g2, b2, source, alpha1 = 1 - this.alpha;
        source = new fabric3.Color(this.color).getSource();
        tr = source[0] * this.alpha;
        tg = source[1] * this.alpha;
        tb = source[2] * this.alpha;
        for (var i2 = 0; i2 < iLen; i2 += 4) {
          r2 = data[i2];
          g2 = data[i2 + 1];
          b2 = data[i2 + 2];
          switch (this.mode) {
            case "multiply":
              data[i2] = r2 * tr / 255;
              data[i2 + 1] = g2 * tg / 255;
              data[i2 + 2] = b2 * tb / 255;
              break;
            case "screen":
              data[i2] = 255 - (255 - r2) * (255 - tr) / 255;
              data[i2 + 1] = 255 - (255 - g2) * (255 - tg) / 255;
              data[i2 + 2] = 255 - (255 - b2) * (255 - tb) / 255;
              break;
            case "add":
              data[i2] = r2 + tr;
              data[i2 + 1] = g2 + tg;
              data[i2 + 2] = b2 + tb;
              break;
            case "diff":
            case "difference":
              data[i2] = Math.abs(r2 - tr);
              data[i2 + 1] = Math.abs(g2 - tg);
              data[i2 + 2] = Math.abs(b2 - tb);
              break;
            case "subtract":
              data[i2] = r2 - tr;
              data[i2 + 1] = g2 - tg;
              data[i2 + 2] = b2 - tb;
              break;
            case "darken":
              data[i2] = Math.min(r2, tr);
              data[i2 + 1] = Math.min(g2, tg);
              data[i2 + 2] = Math.min(b2, tb);
              break;
            case "lighten":
              data[i2] = Math.max(r2, tr);
              data[i2 + 1] = Math.max(g2, tg);
              data[i2 + 2] = Math.max(b2, tb);
              break;
            case "overlay":
              data[i2] = tr < 128 ? 2 * r2 * tr / 255 : 255 - 2 * (255 - r2) * (255 - tr) / 255;
              data[i2 + 1] = tg < 128 ? 2 * g2 * tg / 255 : 255 - 2 * (255 - g2) * (255 - tg) / 255;
              data[i2 + 2] = tb < 128 ? 2 * b2 * tb / 255 : 255 - 2 * (255 - b2) * (255 - tb) / 255;
              break;
            case "exclusion":
              data[i2] = tr + r2 - 2 * tr * r2 / 255;
              data[i2 + 1] = tg + g2 - 2 * tg * g2 / 255;
              data[i2 + 2] = tb + b2 - 2 * tb * b2 / 255;
              break;
            case "tint":
              data[i2] = tr + r2 * alpha1;
              data[i2 + 1] = tg + g2 * alpha1;
              data[i2 + 2] = tb + b2 * alpha1;
          }
        }
      },
      getUniformLocations: function(gl, program) {
        return {
          uColor: gl.getUniformLocation(program, "uColor")
        };
      },
      sendUniformData: function(gl, uniformLocations) {
        var source = new fabric3.Color(this.color).getSource();
        source[0] = this.alpha * source[0] / 255;
        source[1] = this.alpha * source[1] / 255;
        source[2] = this.alpha * source[2] / 255;
        source[3] = this.alpha;
        gl.uniform4fv(uniformLocations.uColor, source);
      },
      toObject: function() {
        return {
          type: this.type,
          color: this.color,
          mode: this.mode,
          alpha: this.alpha
        };
      }
    });
    fabric3.Image.filters.BlendColor.fromObject = fabric3.Image.filters.BaseFilter.fromObject;
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric, filters = fabric3.Image.filters, createClass = fabric3.util.createClass;
    filters.BlendImage = createClass(filters.BaseFilter, {
      type: "BlendImage",
      image: null,
      mode: "multiply",
      alpha: 1,
      vertexSource: "attribute vec2 aPosition;\nvarying vec2 vTexCoord;\nvarying vec2 vTexCoord2;\nuniform mat3 uTransformMatrix;\nvoid main() {\nvTexCoord = aPosition;\nvTexCoord2 = (uTransformMatrix * vec3(aPosition, 1.0)).xy;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",
      fragmentSource: {
        multiply: "precision highp float;\nuniform sampler2D uTexture;\nuniform sampler2D uImage;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvarying vec2 vTexCoord2;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec4 color2 = texture2D(uImage, vTexCoord2);\ncolor.rgba *= color2.rgba;\ngl_FragColor = color;\n}",
        mask: "precision highp float;\nuniform sampler2D uTexture;\nuniform sampler2D uImage;\nuniform vec4 uColor;\nvarying vec2 vTexCoord;\nvarying vec2 vTexCoord2;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec4 color2 = texture2D(uImage, vTexCoord2);\ncolor.a = color2.a;\ngl_FragColor = color;\n}"
      },
      retrieveShader: function(options) {
        var cacheKey = this.type + "_" + this.mode;
        var shaderSource = this.fragmentSource[this.mode];
        if (!options.programCache.hasOwnProperty(cacheKey)) {
          options.programCache[cacheKey] = this.createProgram(options.context, shaderSource);
        }
        return options.programCache[cacheKey];
      },
      applyToWebGL: function(options) {
        var gl = options.context, texture = this.createTexture(options.filterBackend, this.image);
        this.bindAdditionalTexture(gl, texture, gl.TEXTURE1);
        this.callSuper("applyToWebGL", options);
        this.unbindAdditionalTexture(gl, gl.TEXTURE1);
      },
      createTexture: function(backend, image) {
        return backend.getCachedTexture(image.cacheKey, image._element);
      },
      calculateMatrix: function() {
        var image = this.image, width = image._element.width, height = image._element.height;
        return [
          1 / image.scaleX,
          0,
          0,
          0,
          1 / image.scaleY,
          0,
          -image.left / width,
          -image.top / height,
          1
        ];
      },
      applyTo2d: function(options) {
        var imageData = options.imageData, resources = options.filterBackend.resources, data = imageData.data, iLen = data.length, width = imageData.width, height = imageData.height, tr, tg, tb, ta, r2, g2, b2, a2, canvas1, context, image = this.image, blendData;
        if (!resources.blendImage) {
          resources.blendImage = fabric3.util.createCanvasElement();
        }
        canvas1 = resources.blendImage;
        context = canvas1.getContext("2d");
        if (canvas1.width !== width || canvas1.height !== height) {
          canvas1.width = width;
          canvas1.height = height;
        } else {
          context.clearRect(0, 0, width, height);
        }
        context.setTransform(image.scaleX, 0, 0, image.scaleY, image.left, image.top);
        context.drawImage(image._element, 0, 0, width, height);
        blendData = context.getImageData(0, 0, width, height).data;
        for (var i2 = 0; i2 < iLen; i2 += 4) {
          r2 = data[i2];
          g2 = data[i2 + 1];
          b2 = data[i2 + 2];
          a2 = data[i2 + 3];
          tr = blendData[i2];
          tg = blendData[i2 + 1];
          tb = blendData[i2 + 2];
          ta = blendData[i2 + 3];
          switch (this.mode) {
            case "multiply":
              data[i2] = r2 * tr / 255;
              data[i2 + 1] = g2 * tg / 255;
              data[i2 + 2] = b2 * tb / 255;
              data[i2 + 3] = a2 * ta / 255;
              break;
            case "mask":
              data[i2 + 3] = ta;
              break;
          }
        }
      },
      getUniformLocations: function(gl, program) {
        return {
          uTransformMatrix: gl.getUniformLocation(program, "uTransformMatrix"),
          uImage: gl.getUniformLocation(program, "uImage")
        };
      },
      sendUniformData: function(gl, uniformLocations) {
        var matrix = this.calculateMatrix();
        gl.uniform1i(uniformLocations.uImage, 1);
        gl.uniformMatrix3fv(uniformLocations.uTransformMatrix, false, matrix);
      },
      toObject: function() {
        return {
          type: this.type,
          image: this.image && this.image.toObject(),
          mode: this.mode,
          alpha: this.alpha
        };
      }
    });
    fabric3.Image.filters.BlendImage.fromObject = function(object, callback) {
      fabric3.Image.fromObject(object.image, function(image) {
        var options = fabric3.util.object.clone(object);
        options.image = image;
        callback(new fabric3.Image.filters.BlendImage(options));
      });
    };
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {}), pow = Math.pow, floor = Math.floor, sqrt = Math.sqrt, abs = Math.abs, round2 = Math.round, sin = Math.sin, ceil = Math.ceil, filters = fabric3.Image.filters, createClass = fabric3.util.createClass;
    filters.Resize = createClass(filters.BaseFilter, {
      type: "Resize",
      resizeType: "hermite",
      scaleX: 1,
      scaleY: 1,
      lanczosLobes: 3,
      getUniformLocations: function(gl, program) {
        return {
          uDelta: gl.getUniformLocation(program, "uDelta"),
          uTaps: gl.getUniformLocation(program, "uTaps")
        };
      },
      sendUniformData: function(gl, uniformLocations) {
        gl.uniform2fv(uniformLocations.uDelta, this.horizontal ? [1 / this.width, 0] : [0, 1 / this.height]);
        gl.uniform1fv(uniformLocations.uTaps, this.taps);
      },
      retrieveShader: function(options) {
        var filterWindow = this.getFilterWindow(), cacheKey = this.type + "_" + filterWindow;
        if (!options.programCache.hasOwnProperty(cacheKey)) {
          var fragmentShader = this.generateShader(filterWindow);
          options.programCache[cacheKey] = this.createProgram(options.context, fragmentShader);
        }
        return options.programCache[cacheKey];
      },
      getFilterWindow: function() {
        var scale2 = this.tempScale;
        return Math.ceil(this.lanczosLobes / scale2);
      },
      getTaps: function() {
        var lobeFunction = this.lanczosCreate(this.lanczosLobes), scale2 = this.tempScale, filterWindow = this.getFilterWindow(), taps = new Array(filterWindow);
        for (var i2 = 1; i2 <= filterWindow; i2++) {
          taps[i2 - 1] = lobeFunction(i2 * scale2);
        }
        return taps;
      },
      generateShader: function(filterWindow) {
        var offsets = new Array(filterWindow), fragmentShader = this.fragmentSourceTOP, filterWindow;
        for (var i2 = 1; i2 <= filterWindow; i2++) {
          offsets[i2 - 1] = i2 + ".0 * uDelta";
        }
        fragmentShader += "uniform float uTaps[" + filterWindow + "];\n";
        fragmentShader += "void main() {\n";
        fragmentShader += "  vec4 color = texture2D(uTexture, vTexCoord);\n";
        fragmentShader += "  float sum = 1.0;\n";
        offsets.forEach(function(offset2, i3) {
          fragmentShader += "  color += texture2D(uTexture, vTexCoord + " + offset2 + ") * uTaps[" + i3 + "];\n";
          fragmentShader += "  color += texture2D(uTexture, vTexCoord - " + offset2 + ") * uTaps[" + i3 + "];\n";
          fragmentShader += "  sum += 2.0 * uTaps[" + i3 + "];\n";
        });
        fragmentShader += "  gl_FragColor = color / sum;\n";
        fragmentShader += "}";
        return fragmentShader;
      },
      fragmentSourceTOP: "precision highp float;\nuniform sampler2D uTexture;\nuniform vec2 uDelta;\nvarying vec2 vTexCoord;\n",
      applyTo: function(options) {
        if (options.webgl) {
          options.passes++;
          this.width = options.sourceWidth;
          this.horizontal = true;
          this.dW = Math.round(this.width * this.scaleX);
          this.dH = options.sourceHeight;
          this.tempScale = this.dW / this.width;
          this.taps = this.getTaps();
          options.destinationWidth = this.dW;
          this._setupFrameBuffer(options);
          this.applyToWebGL(options);
          this._swapTextures(options);
          options.sourceWidth = options.destinationWidth;
          this.height = options.sourceHeight;
          this.horizontal = false;
          this.dH = Math.round(this.height * this.scaleY);
          this.tempScale = this.dH / this.height;
          this.taps = this.getTaps();
          options.destinationHeight = this.dH;
          this._setupFrameBuffer(options);
          this.applyToWebGL(options);
          this._swapTextures(options);
          options.sourceHeight = options.destinationHeight;
        } else {
          this.applyTo2d(options);
        }
      },
      isNeutralState: function() {
        return this.scaleX === 1 && this.scaleY === 1;
      },
      lanczosCreate: function(lobes) {
        return function(x2) {
          if (x2 >= lobes || x2 <= -lobes) {
            return 0;
          }
          if (x2 < 11920929e-14 && x2 > -11920929e-14) {
            return 1;
          }
          x2 *= Math.PI;
          var xx = x2 / lobes;
          return sin(x2) / x2 * sin(xx) / xx;
        };
      },
      applyTo2d: function(options) {
        var imageData = options.imageData, scaleX = this.scaleX, scaleY = this.scaleY;
        this.rcpScaleX = 1 / scaleX;
        this.rcpScaleY = 1 / scaleY;
        var oW = imageData.width, oH = imageData.height, dW = round2(oW * scaleX), dH = round2(oH * scaleY), newData;
        if (this.resizeType === "sliceHack") {
          newData = this.sliceByTwo(options, oW, oH, dW, dH);
        } else if (this.resizeType === "hermite") {
          newData = this.hermiteFastResize(options, oW, oH, dW, dH);
        } else if (this.resizeType === "bilinear") {
          newData = this.bilinearFiltering(options, oW, oH, dW, dH);
        } else if (this.resizeType === "lanczos") {
          newData = this.lanczosResize(options, oW, oH, dW, dH);
        }
        options.imageData = newData;
      },
      sliceByTwo: function(options, oW, oH, dW, dH) {
        var imageData = options.imageData, mult = 0.5, doneW = false, doneH = false, stepW = oW * mult, stepH = oH * mult, resources = fabric3.filterBackend.resources, tmpCanvas, ctx, sX = 0, sY = 0, dX = oW, dY = 0;
        if (!resources.sliceByTwo) {
          resources.sliceByTwo = document.createElement("canvas");
        }
        tmpCanvas = resources.sliceByTwo;
        if (tmpCanvas.width < oW * 1.5 || tmpCanvas.height < oH) {
          tmpCanvas.width = oW * 1.5;
          tmpCanvas.height = oH;
        }
        ctx = tmpCanvas.getContext("2d");
        ctx.clearRect(0, 0, oW * 1.5, oH);
        ctx.putImageData(imageData, 0, 0);
        dW = floor(dW);
        dH = floor(dH);
        while (!doneW || !doneH) {
          oW = stepW;
          oH = stepH;
          if (dW < floor(stepW * mult)) {
            stepW = floor(stepW * mult);
          } else {
            stepW = dW;
            doneW = true;
          }
          if (dH < floor(stepH * mult)) {
            stepH = floor(stepH * mult);
          } else {
            stepH = dH;
            doneH = true;
          }
          ctx.drawImage(tmpCanvas, sX, sY, oW, oH, dX, dY, stepW, stepH);
          sX = dX;
          sY = dY;
          dY += stepH;
        }
        return ctx.getImageData(sX, sY, dW, dH);
      },
      lanczosResize: function(options, oW, oH, dW, dH) {
        function process2(u2) {
          var v2, i2, weight, idx, a2, red, green, blue, alpha2, fX, fY;
          center.x = (u2 + 0.5) * ratioX;
          icenter.x = floor(center.x);
          for (v2 = 0; v2 < dH; v2++) {
            center.y = (v2 + 0.5) * ratioY;
            icenter.y = floor(center.y);
            a2 = 0;
            red = 0;
            green = 0;
            blue = 0;
            alpha2 = 0;
            for (i2 = icenter.x - range2X; i2 <= icenter.x + range2X; i2++) {
              if (i2 < 0 || i2 >= oW) {
                continue;
              }
              fX = floor(1e3 * abs(i2 - center.x));
              if (!cacheLanc[fX]) {
                cacheLanc[fX] = {};
              }
              for (var j2 = icenter.y - range2Y; j2 <= icenter.y + range2Y; j2++) {
                if (j2 < 0 || j2 >= oH) {
                  continue;
                }
                fY = floor(1e3 * abs(j2 - center.y));
                if (!cacheLanc[fX][fY]) {
                  cacheLanc[fX][fY] = lanczos(sqrt(pow(fX * rcpRatioX, 2) + pow(fY * rcpRatioY, 2)) / 1e3);
                }
                weight = cacheLanc[fX][fY];
                if (weight > 0) {
                  idx = (j2 * oW + i2) * 4;
                  a2 += weight;
                  red += weight * srcData[idx];
                  green += weight * srcData[idx + 1];
                  blue += weight * srcData[idx + 2];
                  alpha2 += weight * srcData[idx + 3];
                }
              }
            }
            idx = (v2 * dW + u2) * 4;
            destData[idx] = red / a2;
            destData[idx + 1] = green / a2;
            destData[idx + 2] = blue / a2;
            destData[idx + 3] = alpha2 / a2;
          }
          if (++u2 < dW) {
            return process2(u2);
          } else {
            return destImg;
          }
        }
        var srcData = options.imageData.data, destImg = options.ctx.createImageData(dW, dH), destData = destImg.data, lanczos = this.lanczosCreate(this.lanczosLobes), ratioX = this.rcpScaleX, ratioY = this.rcpScaleY, rcpRatioX = 2 / this.rcpScaleX, rcpRatioY = 2 / this.rcpScaleY, range2X = ceil(ratioX * this.lanczosLobes / 2), range2Y = ceil(ratioY * this.lanczosLobes / 2), cacheLanc = {}, center = {}, icenter = {};
        return process2(0);
      },
      bilinearFiltering: function(options, oW, oH, dW, dH) {
        var a2, b2, c2, d2, x2, y2, i2, j2, xDiff, yDiff, chnl, color2, offset2 = 0, origPix, ratioX = this.rcpScaleX, ratioY = this.rcpScaleY, w4 = 4 * (oW - 1), img = options.imageData, pixels = img.data, destImage = options.ctx.createImageData(dW, dH), destPixels = destImage.data;
        for (i2 = 0; i2 < dH; i2++) {
          for (j2 = 0; j2 < dW; j2++) {
            x2 = floor(ratioX * j2);
            y2 = floor(ratioY * i2);
            xDiff = ratioX * j2 - x2;
            yDiff = ratioY * i2 - y2;
            origPix = 4 * (y2 * oW + x2);
            for (chnl = 0; chnl < 4; chnl++) {
              a2 = pixels[origPix + chnl];
              b2 = pixels[origPix + 4 + chnl];
              c2 = pixels[origPix + w4 + chnl];
              d2 = pixels[origPix + w4 + 4 + chnl];
              color2 = a2 * (1 - xDiff) * (1 - yDiff) + b2 * xDiff * (1 - yDiff) + c2 * yDiff * (1 - xDiff) + d2 * xDiff * yDiff;
              destPixels[offset2++] = color2;
            }
          }
        }
        return destImage;
      },
      hermiteFastResize: function(options, oW, oH, dW, dH) {
        var ratioW = this.rcpScaleX, ratioH = this.rcpScaleY, ratioWHalf = ceil(ratioW / 2), ratioHHalf = ceil(ratioH / 2), img = options.imageData, data = img.data, img2 = options.ctx.createImageData(dW, dH), data2 = img2.data;
        for (var j2 = 0; j2 < dH; j2++) {
          for (var i2 = 0; i2 < dW; i2++) {
            var x2 = (i2 + j2 * dW) * 4, weight = 0, weights = 0, weightsAlpha = 0, gxR = 0, gxG = 0, gxB = 0, gxA = 0, centerY = (j2 + 0.5) * ratioH;
            for (var yy = floor(j2 * ratioH); yy < (j2 + 1) * ratioH; yy++) {
              var dy = abs(centerY - (yy + 0.5)) / ratioHHalf, centerX = (i2 + 0.5) * ratioW, w0 = dy * dy;
              for (var xx = floor(i2 * ratioW); xx < (i2 + 1) * ratioW; xx++) {
                var dx = abs(centerX - (xx + 0.5)) / ratioWHalf, w2 = sqrt(w0 + dx * dx);
                if (w2 > 1 && w2 < -1) {
                  continue;
                }
                weight = 2 * w2 * w2 * w2 - 3 * w2 * w2 + 1;
                if (weight > 0) {
                  dx = 4 * (xx + yy * oW);
                  gxA += weight * data[dx + 3];
                  weightsAlpha += weight;
                  if (data[dx + 3] < 255) {
                    weight = weight * data[dx + 3] / 250;
                  }
                  gxR += weight * data[dx];
                  gxG += weight * data[dx + 1];
                  gxB += weight * data[dx + 2];
                  weights += weight;
                }
              }
            }
            data2[x2] = gxR / weights;
            data2[x2 + 1] = gxG / weights;
            data2[x2 + 2] = gxB / weights;
            data2[x2 + 3] = gxA / weightsAlpha;
          }
        }
        return img2;
      },
      toObject: function() {
        return {
          type: this.type,
          scaleX: this.scaleX,
          scaleY: this.scaleY,
          resizeType: this.resizeType,
          lanczosLobes: this.lanczosLobes
        };
      }
    });
    fabric3.Image.filters.Resize.fromObject = fabric3.Image.filters.BaseFilter.fromObject;
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {}), filters = fabric3.Image.filters, createClass = fabric3.util.createClass;
    filters.Contrast = createClass(filters.BaseFilter, {
      type: "Contrast",
      fragmentSource: "precision highp float;\nuniform sampler2D uTexture;\nuniform float uContrast;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\ncolor.rgb = contrastF * (color.rgb - 0.5) + 0.5;\ngl_FragColor = color;\n}",
      contrast: 0,
      mainParameter: "contrast",
      applyTo2d: function(options) {
        if (this.contrast === 0) {
          return;
        }
        var imageData = options.imageData, i2, len, data = imageData.data, len = data.length, contrast = Math.floor(this.contrast * 255), contrastF = 259 * (contrast + 255) / (255 * (259 - contrast));
        for (i2 = 0; i2 < len; i2 += 4) {
          data[i2] = contrastF * (data[i2] - 128) + 128;
          data[i2 + 1] = contrastF * (data[i2 + 1] - 128) + 128;
          data[i2 + 2] = contrastF * (data[i2 + 2] - 128) + 128;
        }
      },
      getUniformLocations: function(gl, program) {
        return {
          uContrast: gl.getUniformLocation(program, "uContrast")
        };
      },
      sendUniformData: function(gl, uniformLocations) {
        gl.uniform1f(uniformLocations.uContrast, this.contrast);
      }
    });
    fabric3.Image.filters.Contrast.fromObject = fabric3.Image.filters.BaseFilter.fromObject;
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {}), filters = fabric3.Image.filters, createClass = fabric3.util.createClass;
    filters.Saturation = createClass(filters.BaseFilter, {
      type: "Saturation",
      fragmentSource: "precision highp float;\nuniform sampler2D uTexture;\nuniform float uSaturation;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat rgMax = max(color.r, color.g);\nfloat rgbMax = max(rgMax, color.b);\ncolor.r += rgbMax != color.r ? (rgbMax - color.r) * uSaturation : 0.00;\ncolor.g += rgbMax != color.g ? (rgbMax - color.g) * uSaturation : 0.00;\ncolor.b += rgbMax != color.b ? (rgbMax - color.b) * uSaturation : 0.00;\ngl_FragColor = color;\n}",
      saturation: 0,
      mainParameter: "saturation",
      applyTo2d: function(options) {
        if (this.saturation === 0) {
          return;
        }
        var imageData = options.imageData, data = imageData.data, len = data.length, adjust = -this.saturation, i2, max;
        for (i2 = 0; i2 < len; i2 += 4) {
          max = Math.max(data[i2], data[i2 + 1], data[i2 + 2]);
          data[i2] += max !== data[i2] ? (max - data[i2]) * adjust : 0;
          data[i2 + 1] += max !== data[i2 + 1] ? (max - data[i2 + 1]) * adjust : 0;
          data[i2 + 2] += max !== data[i2 + 2] ? (max - data[i2 + 2]) * adjust : 0;
        }
      },
      getUniformLocations: function(gl, program) {
        return {
          uSaturation: gl.getUniformLocation(program, "uSaturation")
        };
      },
      sendUniformData: function(gl, uniformLocations) {
        gl.uniform1f(uniformLocations.uSaturation, -this.saturation);
      }
    });
    fabric3.Image.filters.Saturation.fromObject = fabric3.Image.filters.BaseFilter.fromObject;
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {}), filters = fabric3.Image.filters, createClass = fabric3.util.createClass;
    filters.Vibrance = createClass(filters.BaseFilter, {
      type: "Vibrance",
      fragmentSource: "precision highp float;\nuniform sampler2D uTexture;\nuniform float uVibrance;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat max = max(color.r, max(color.g, color.b));\nfloat avg = (color.r + color.g + color.b) / 3.0;\nfloat amt = (abs(max - avg) * 2.0) * uVibrance;\ncolor.r += max != color.r ? (max - color.r) * amt : 0.00;\ncolor.g += max != color.g ? (max - color.g) * amt : 0.00;\ncolor.b += max != color.b ? (max - color.b) * amt : 0.00;\ngl_FragColor = color;\n}",
      vibrance: 0,
      mainParameter: "vibrance",
      applyTo2d: function(options) {
        if (this.vibrance === 0) {
          return;
        }
        var imageData = options.imageData, data = imageData.data, len = data.length, adjust = -this.vibrance, i2, max, avg, amt;
        for (i2 = 0; i2 < len; i2 += 4) {
          max = Math.max(data[i2], data[i2 + 1], data[i2 + 2]);
          avg = (data[i2] + data[i2 + 1] + data[i2 + 2]) / 3;
          amt = Math.abs(max - avg) * 2 / 255 * adjust;
          data[i2] += max !== data[i2] ? (max - data[i2]) * amt : 0;
          data[i2 + 1] += max !== data[i2 + 1] ? (max - data[i2 + 1]) * amt : 0;
          data[i2 + 2] += max !== data[i2 + 2] ? (max - data[i2 + 2]) * amt : 0;
        }
      },
      getUniformLocations: function(gl, program) {
        return {
          uVibrance: gl.getUniformLocation(program, "uVibrance")
        };
      },
      sendUniformData: function(gl, uniformLocations) {
        gl.uniform1f(uniformLocations.uVibrance, -this.vibrance);
      }
    });
    fabric3.Image.filters.Vibrance.fromObject = fabric3.Image.filters.BaseFilter.fromObject;
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {}), filters = fabric3.Image.filters, createClass = fabric3.util.createClass;
    filters.Blur = createClass(filters.BaseFilter, {
      type: "Blur",
      fragmentSource: "precision highp float;\nuniform sampler2D uTexture;\nuniform vec2 uDelta;\nvarying vec2 vTexCoord;\nconst float nSamples = 15.0;\nvec3 v3offset = vec3(12.9898, 78.233, 151.7182);\nfloat random(vec3 scale) {\nreturn fract(sin(dot(gl_FragCoord.xyz, scale)) * 43758.5453);\n}\nvoid main() {\nvec4 color = vec4(0.0);\nfloat total = 0.0;\nfloat offset = random(v3offset);\nfor (float t = -nSamples; t <= nSamples; t++) {\nfloat percent = (t + offset - 0.5) / nSamples;\nfloat weight = 1.0 - abs(percent);\ncolor += texture2D(uTexture, vTexCoord + uDelta * percent) * weight;\ntotal += weight;\n}\ngl_FragColor = color / total;\n}",
      blur: 0,
      mainParameter: "blur",
      applyTo: function(options) {
        if (options.webgl) {
          this.aspectRatio = options.sourceWidth / options.sourceHeight;
          options.passes++;
          this._setupFrameBuffer(options);
          this.horizontal = true;
          this.applyToWebGL(options);
          this._swapTextures(options);
          this._setupFrameBuffer(options);
          this.horizontal = false;
          this.applyToWebGL(options);
          this._swapTextures(options);
        } else {
          this.applyTo2d(options);
        }
      },
      applyTo2d: function(options) {
        options.imageData = this.simpleBlur(options);
      },
      simpleBlur: function(options) {
        var resources = options.filterBackend.resources, canvas1, canvas2, width = options.imageData.width, height = options.imageData.height;
        if (!resources.blurLayer1) {
          resources.blurLayer1 = fabric3.util.createCanvasElement();
          resources.blurLayer2 = fabric3.util.createCanvasElement();
        }
        canvas1 = resources.blurLayer1;
        canvas2 = resources.blurLayer2;
        if (canvas1.width !== width || canvas1.height !== height) {
          canvas2.width = canvas1.width = width;
          canvas2.height = canvas1.height = height;
        }
        var ctx1 = canvas1.getContext("2d"), ctx2 = canvas2.getContext("2d"), nSamples = 15, random, percent2, j2, i2, blur = this.blur * 0.06 * 0.5;
        ctx1.putImageData(options.imageData, 0, 0);
        ctx2.clearRect(0, 0, width, height);
        for (i2 = -nSamples; i2 <= nSamples; i2++) {
          random = (Math.random() - 0.5) / 4;
          percent2 = i2 / nSamples;
          j2 = blur * percent2 * width + random;
          ctx2.globalAlpha = 1 - Math.abs(percent2);
          ctx2.drawImage(canvas1, j2, random);
          ctx1.drawImage(canvas2, 0, 0);
          ctx2.globalAlpha = 1;
          ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
        }
        for (i2 = -nSamples; i2 <= nSamples; i2++) {
          random = (Math.random() - 0.5) / 4;
          percent2 = i2 / nSamples;
          j2 = blur * percent2 * height + random;
          ctx2.globalAlpha = 1 - Math.abs(percent2);
          ctx2.drawImage(canvas1, random, j2);
          ctx1.drawImage(canvas2, 0, 0);
          ctx2.globalAlpha = 1;
          ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
        }
        options.ctx.drawImage(canvas1, 0, 0);
        var newImageData = options.ctx.getImageData(0, 0, canvas1.width, canvas1.height);
        ctx1.globalAlpha = 1;
        ctx1.clearRect(0, 0, canvas1.width, canvas1.height);
        return newImageData;
      },
      getUniformLocations: function(gl, program) {
        return {
          delta: gl.getUniformLocation(program, "uDelta")
        };
      },
      sendUniformData: function(gl, uniformLocations) {
        var delta = this.chooseRightDelta();
        gl.uniform2fv(uniformLocations.delta, delta);
      },
      chooseRightDelta: function() {
        var blurScale = 1, delta = [0, 0], blur;
        if (this.horizontal) {
          if (this.aspectRatio > 1) {
            blurScale = 1 / this.aspectRatio;
          }
        } else {
          if (this.aspectRatio < 1) {
            blurScale = this.aspectRatio;
          }
        }
        blur = blurScale * this.blur * 0.12;
        if (this.horizontal) {
          delta[0] = blur;
        } else {
          delta[1] = blur;
        }
        return delta;
      }
    });
    filters.Blur.fromObject = fabric3.Image.filters.BaseFilter.fromObject;
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {}), filters = fabric3.Image.filters, createClass = fabric3.util.createClass;
    filters.Gamma = createClass(filters.BaseFilter, {
      type: "Gamma",
      fragmentSource: "precision highp float;\nuniform sampler2D uTexture;\nuniform vec3 uGamma;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec3 correction = (1.0 / uGamma);\ncolor.r = pow(color.r, correction.r);\ncolor.g = pow(color.g, correction.g);\ncolor.b = pow(color.b, correction.b);\ngl_FragColor = color;\ngl_FragColor.rgb *= color.a;\n}",
      gamma: [1, 1, 1],
      mainParameter: "gamma",
      initialize: function(options) {
        this.gamma = [1, 1, 1];
        filters.BaseFilter.prototype.initialize.call(this, options);
      },
      applyTo2d: function(options) {
        var imageData = options.imageData, data = imageData.data, gamma = this.gamma, len = data.length, rInv = 1 / gamma[0], gInv = 1 / gamma[1], bInv = 1 / gamma[2], i2;
        if (!this.rVals) {
          this.rVals = new Uint8Array(256);
          this.gVals = new Uint8Array(256);
          this.bVals = new Uint8Array(256);
        }
        for (i2 = 0, len = 256; i2 < len; i2++) {
          this.rVals[i2] = Math.pow(i2 / 255, rInv) * 255;
          this.gVals[i2] = Math.pow(i2 / 255, gInv) * 255;
          this.bVals[i2] = Math.pow(i2 / 255, bInv) * 255;
        }
        for (i2 = 0, len = data.length; i2 < len; i2 += 4) {
          data[i2] = this.rVals[data[i2]];
          data[i2 + 1] = this.gVals[data[i2 + 1]];
          data[i2 + 2] = this.bVals[data[i2 + 2]];
        }
      },
      getUniformLocations: function(gl, program) {
        return {
          uGamma: gl.getUniformLocation(program, "uGamma")
        };
      },
      sendUniformData: function(gl, uniformLocations) {
        gl.uniform3fv(uniformLocations.uGamma, this.gamma);
      }
    });
    fabric3.Image.filters.Gamma.fromObject = fabric3.Image.filters.BaseFilter.fromObject;
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {}), filters = fabric3.Image.filters, createClass = fabric3.util.createClass;
    filters.Composed = createClass(filters.BaseFilter, {
      type: "Composed",
      subFilters: [],
      initialize: function(options) {
        this.callSuper("initialize", options);
        this.subFilters = this.subFilters.slice(0);
      },
      applyTo: function(options) {
        options.passes += this.subFilters.length - 1;
        this.subFilters.forEach(function(filter2) {
          filter2.applyTo(options);
        });
      },
      toObject: function() {
        return fabric3.util.object.extend(this.callSuper("toObject"), {
          subFilters: this.subFilters.map(function(filter2) {
            return filter2.toObject();
          })
        });
      },
      isNeutralState: function() {
        return !this.subFilters.some(function(filter2) {
          return !filter2.isNeutralState();
        });
      }
    });
    fabric3.Image.filters.Composed.fromObject = function(object, callback) {
      var filters2 = object.subFilters || [], subFilters = filters2.map(function(filter2) {
        return new fabric3.Image.filters[filter2.type](filter2);
      }), instance = new fabric3.Image.filters.Composed({ subFilters });
      callback && callback(instance);
      return instance;
    };
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {}), filters = fabric3.Image.filters, createClass = fabric3.util.createClass;
    filters.HueRotation = createClass(filters.ColorMatrix, {
      type: "HueRotation",
      rotation: 0,
      mainParameter: "rotation",
      calculateMatrix: function() {
        var rad = this.rotation * Math.PI, cos = fabric3.util.cos(rad), sin = fabric3.util.sin(rad), aThird = 1 / 3, aThirdSqtSin = Math.sqrt(aThird) * sin, OneMinusCos = 1 - cos;
        this.matrix = [
          1,
          0,
          0,
          0,
          0,
          0,
          1,
          0,
          0,
          0,
          0,
          0,
          1,
          0,
          0,
          0,
          0,
          0,
          1,
          0
        ];
        this.matrix[0] = cos + OneMinusCos / 3;
        this.matrix[1] = aThird * OneMinusCos - aThirdSqtSin;
        this.matrix[2] = aThird * OneMinusCos + aThirdSqtSin;
        this.matrix[5] = aThird * OneMinusCos + aThirdSqtSin;
        this.matrix[6] = cos + aThird * OneMinusCos;
        this.matrix[7] = aThird * OneMinusCos - aThirdSqtSin;
        this.matrix[10] = aThird * OneMinusCos - aThirdSqtSin;
        this.matrix[11] = aThird * OneMinusCos + aThirdSqtSin;
        this.matrix[12] = cos + aThird * OneMinusCos;
      },
      isNeutralState: function(options) {
        this.calculateMatrix();
        return filters.BaseFilter.prototype.isNeutralState.call(this, options);
      },
      applyTo: function(options) {
        this.calculateMatrix();
        filters.BaseFilter.prototype.applyTo.call(this, options);
      }
    });
    fabric3.Image.filters.HueRotation.fromObject = fabric3.Image.filters.BaseFilter.fromObject;
  })(exports2);
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {}), clone = fabric3.util.object.clone;
    if (fabric3.Text) {
      fabric3.warn("fabric.Text is already defined");
      return;
    }
    var additionalProps = "fontFamily fontWeight fontSize text underline overline linethrough textAlign fontStyle lineHeight textBackgroundColor charSpacing styles direction path pathStartOffset pathSide".split(" ");
    fabric3.Text = fabric3.util.createClass(fabric3.Object, {
      _dimensionAffectingProps: [
        "fontSize",
        "fontWeight",
        "fontFamily",
        "fontStyle",
        "lineHeight",
        "text",
        "charSpacing",
        "textAlign",
        "styles",
        "path",
        "pathStartOffset",
        "pathSide"
      ],
      _reNewline: /\r?\n/,
      _reSpacesAndTabs: /[ \t\r]/g,
      _reSpaceAndTab: /[ \t\r]/,
      _reWords: /\S+/g,
      type: "text",
      fontSize: 40,
      fontWeight: "normal",
      fontFamily: "Times New Roman",
      underline: false,
      overline: false,
      linethrough: false,
      textAlign: "left",
      fontStyle: "normal",
      lineHeight: 1.16,
      superscript: {
        size: 0.6,
        baseline: -0.35
      },
      subscript: {
        size: 0.6,
        baseline: 0.11
      },
      textBackgroundColor: "",
      stateProperties: fabric3.Object.prototype.stateProperties.concat(additionalProps),
      cacheProperties: fabric3.Object.prototype.cacheProperties.concat(additionalProps),
      stroke: null,
      shadow: null,
      path: null,
      pathStartOffset: 0,
      pathSide: "left",
      _fontSizeFraction: 0.222,
      offsets: {
        underline: 0.1,
        linethrough: -0.315,
        overline: -0.88
      },
      _fontSizeMult: 1.13,
      charSpacing: 0,
      styles: null,
      _measuringContext: null,
      deltaY: 0,
      direction: "ltr",
      _styleProperties: [
        "stroke",
        "strokeWidth",
        "fill",
        "fontFamily",
        "fontSize",
        "fontWeight",
        "fontStyle",
        "underline",
        "overline",
        "linethrough",
        "deltaY",
        "textBackgroundColor"
      ],
      __charBounds: [],
      CACHE_FONT_SIZE: 400,
      MIN_TEXT_WIDTH: 2,
      initialize: function(text2, options) {
        this.styles = options ? options.styles || {} : {};
        this.text = text2;
        this.__skipDimension = true;
        this.callSuper("initialize", options);
        if (this.path) {
          this.setPathInfo();
        }
        this.__skipDimension = false;
        this.initDimensions();
        this.setCoords();
        this.setupState({ propertySet: "_dimensionAffectingProps" });
      },
      setPathInfo: function() {
        var path = this.path;
        if (path) {
          path.segmentsInfo = fabric3.util.getPathSegmentsInfo(path.path);
        }
      },
      getMeasuringContext: function() {
        if (!fabric3._measuringContext) {
          fabric3._measuringContext = this.canvas && this.canvas.contextCache || fabric3.util.createCanvasElement().getContext("2d");
        }
        return fabric3._measuringContext;
      },
      _splitText: function() {
        var newLines = this._splitTextIntoLines(this.text);
        this.textLines = newLines.lines;
        this._textLines = newLines.graphemeLines;
        this._unwrappedTextLines = newLines._unwrappedLines;
        this._text = newLines.graphemeText;
        return newLines;
      },
      initDimensions: function() {
        if (this.__skipDimension) {
          return;
        }
        this._splitText();
        this._clearCache();
        if (this.path) {
          this.width = this.path.width;
          this.height = this.path.height;
        } else {
          this.width = this.calcTextWidth() || this.cursorWidth || this.MIN_TEXT_WIDTH;
          this.height = this.calcTextHeight();
        }
        if (this.textAlign.indexOf("justify") !== -1) {
          this.enlargeSpaces();
        }
        this.saveState({ propertySet: "_dimensionAffectingProps" });
      },
      enlargeSpaces: function() {
        var diffSpace, currentLineWidth, numberOfSpaces, accumulatedSpace, line, charBound, spaces;
        for (var i2 = 0, len = this._textLines.length; i2 < len; i2++) {
          if (this.textAlign !== "justify" && (i2 === len - 1 || this.isEndOfWrapping(i2))) {
            continue;
          }
          accumulatedSpace = 0;
          line = this._textLines[i2];
          currentLineWidth = this.getLineWidth(i2);
          if (currentLineWidth < this.width && (spaces = this.textLines[i2].match(this._reSpacesAndTabs))) {
            numberOfSpaces = spaces.length;
            diffSpace = (this.width - currentLineWidth) / numberOfSpaces;
            for (var j2 = 0, jlen = line.length; j2 <= jlen; j2++) {
              charBound = this.__charBounds[i2][j2];
              if (this._reSpaceAndTab.test(line[j2])) {
                charBound.width += diffSpace;
                charBound.kernedWidth += diffSpace;
                charBound.left += accumulatedSpace;
                accumulatedSpace += diffSpace;
              } else {
                charBound.left += accumulatedSpace;
              }
            }
          }
        }
      },
      isEndOfWrapping: function(lineIndex) {
        return lineIndex === this._textLines.length - 1;
      },
      missingNewlineOffset: function() {
        return 1;
      },
      toString: function() {
        return "#<fabric.Text (" + this.complexity() + '): { "text": "' + this.text + '", "fontFamily": "' + this.fontFamily + '" }>';
      },
      _getCacheCanvasDimensions: function() {
        var dims = this.callSuper("_getCacheCanvasDimensions");
        var fontSize = this.fontSize;
        dims.width += fontSize * dims.zoomX;
        dims.height += fontSize * dims.zoomY;
        return dims;
      },
      _render: function(ctx) {
        var path = this.path;
        path && !path.isNotVisible() && path._render(ctx);
        this._setTextStyles(ctx);
        this._renderTextLinesBackground(ctx);
        this._renderTextDecoration(ctx, "underline");
        this._renderText(ctx);
        this._renderTextDecoration(ctx, "overline");
        this._renderTextDecoration(ctx, "linethrough");
      },
      _renderText: function(ctx) {
        if (this.paintFirst === "stroke") {
          this._renderTextStroke(ctx);
          this._renderTextFill(ctx);
        } else {
          this._renderTextFill(ctx);
          this._renderTextStroke(ctx);
        }
      },
      _setTextStyles: function(ctx, charStyle, forMeasuring) {
        ctx.textBaseline = "alphabetic";
        ctx.font = this._getFontDeclaration(charStyle, forMeasuring);
      },
      calcTextWidth: function() {
        var maxWidth = this.getLineWidth(0);
        for (var i2 = 1, len = this._textLines.length; i2 < len; i2++) {
          var currentLineWidth = this.getLineWidth(i2);
          if (currentLineWidth > maxWidth) {
            maxWidth = currentLineWidth;
          }
        }
        return maxWidth;
      },
      _renderTextLine: function(method, ctx, line, left, top, lineIndex) {
        this._renderChars(method, ctx, line, left, top, lineIndex);
      },
      _renderTextLinesBackground: function(ctx) {
        if (!this.textBackgroundColor && !this.styleHas("textBackgroundColor")) {
          return;
        }
        var heightOfLine, lineLeftOffset, originalFill = ctx.fillStyle, line, lastColor, leftOffset = this._getLeftOffset(), lineTopOffset = this._getTopOffset(), boxStart = 0, boxWidth = 0, charBox, currentColor, path = this.path, drawStart;
        for (var i2 = 0, len = this._textLines.length; i2 < len; i2++) {
          heightOfLine = this.getHeightOfLine(i2);
          if (!this.textBackgroundColor && !this.styleHas("textBackgroundColor", i2)) {
            lineTopOffset += heightOfLine;
            continue;
          }
          line = this._textLines[i2];
          lineLeftOffset = this._getLineLeftOffset(i2);
          boxWidth = 0;
          boxStart = 0;
          lastColor = this.getValueOfPropertyAt(i2, 0, "textBackgroundColor");
          for (var j2 = 0, jlen = line.length; j2 < jlen; j2++) {
            charBox = this.__charBounds[i2][j2];
            currentColor = this.getValueOfPropertyAt(i2, j2, "textBackgroundColor");
            if (path) {
              ctx.save();
              ctx.translate(charBox.renderLeft, charBox.renderTop);
              ctx.rotate(charBox.angle);
              ctx.fillStyle = currentColor;
              currentColor && ctx.fillRect(-charBox.width / 2, -heightOfLine / this.lineHeight * (1 - this._fontSizeFraction), charBox.width, heightOfLine / this.lineHeight);
              ctx.restore();
            } else if (currentColor !== lastColor) {
              drawStart = leftOffset + lineLeftOffset + boxStart;
              if (this.direction === "rtl") {
                drawStart = this.width - drawStart - boxWidth;
              }
              ctx.fillStyle = lastColor;
              lastColor && ctx.fillRect(drawStart, lineTopOffset, boxWidth, heightOfLine / this.lineHeight);
              boxStart = charBox.left;
              boxWidth = charBox.width;
              lastColor = currentColor;
            } else {
              boxWidth += charBox.kernedWidth;
            }
          }
          if (currentColor && !path) {
            drawStart = leftOffset + lineLeftOffset + boxStart;
            if (this.direction === "rtl") {
              drawStart = this.width - drawStart - boxWidth;
            }
            ctx.fillStyle = currentColor;
            ctx.fillRect(drawStart, lineTopOffset, boxWidth, heightOfLine / this.lineHeight);
          }
          lineTopOffset += heightOfLine;
        }
        ctx.fillStyle = originalFill;
        this._removeShadow(ctx);
      },
      getFontCache: function(decl) {
        var fontFamily = decl.fontFamily.toLowerCase();
        if (!fabric3.charWidthsCache[fontFamily]) {
          fabric3.charWidthsCache[fontFamily] = {};
        }
        var cache = fabric3.charWidthsCache[fontFamily], cacheProp = decl.fontStyle.toLowerCase() + "_" + (decl.fontWeight + "").toLowerCase();
        if (!cache[cacheProp]) {
          cache[cacheProp] = {};
        }
        return cache[cacheProp];
      },
      _measureChar: function(_char, charStyle, previousChar, prevCharStyle) {
        var fontCache = this.getFontCache(charStyle), fontDeclaration = this._getFontDeclaration(charStyle), previousFontDeclaration = this._getFontDeclaration(prevCharStyle), couple = previousChar + _char, stylesAreEqual = fontDeclaration === previousFontDeclaration, width, coupleWidth, previousWidth, fontMultiplier = charStyle.fontSize / this.CACHE_FONT_SIZE, kernedWidth;
        if (previousChar && fontCache[previousChar] !== void 0) {
          previousWidth = fontCache[previousChar];
        }
        if (fontCache[_char] !== void 0) {
          kernedWidth = width = fontCache[_char];
        }
        if (stylesAreEqual && fontCache[couple] !== void 0) {
          coupleWidth = fontCache[couple];
          kernedWidth = coupleWidth - previousWidth;
        }
        if (width === void 0 || previousWidth === void 0 || coupleWidth === void 0) {
          var ctx = this.getMeasuringContext();
          this._setTextStyles(ctx, charStyle, true);
        }
        if (width === void 0) {
          kernedWidth = width = ctx.measureText(_char).width;
          fontCache[_char] = width;
        }
        if (previousWidth === void 0 && stylesAreEqual && previousChar) {
          previousWidth = ctx.measureText(previousChar).width;
          fontCache[previousChar] = previousWidth;
        }
        if (stylesAreEqual && coupleWidth === void 0) {
          coupleWidth = ctx.measureText(couple).width;
          fontCache[couple] = coupleWidth;
          kernedWidth = coupleWidth - previousWidth;
        }
        return { width: width * fontMultiplier, kernedWidth: kernedWidth * fontMultiplier };
      },
      getHeightOfChar: function(line, _char) {
        return this.getValueOfPropertyAt(line, _char, "fontSize");
      },
      measureLine: function(lineIndex) {
        var lineInfo = this._measureLine(lineIndex);
        if (this.charSpacing !== 0) {
          lineInfo.width -= this._getWidthOfCharSpacing();
        }
        if (lineInfo.width < 0) {
          lineInfo.width = 0;
        }
        return lineInfo;
      },
      _measureLine: function(lineIndex) {
        var width = 0, i2, grapheme, line = this._textLines[lineIndex], prevGrapheme, graphemeInfo, numOfSpaces = 0, lineBounds = new Array(line.length), positionInPath = 0, startingPoint, totalPathLength, path = this.path, reverse = this.pathSide === "right";
        this.__charBounds[lineIndex] = lineBounds;
        for (i2 = 0; i2 < line.length; i2++) {
          grapheme = line[i2];
          graphemeInfo = this._getGraphemeBox(grapheme, lineIndex, i2, prevGrapheme);
          lineBounds[i2] = graphemeInfo;
          width += graphemeInfo.kernedWidth;
          prevGrapheme = grapheme;
        }
        lineBounds[i2] = {
          left: graphemeInfo ? graphemeInfo.left + graphemeInfo.width : 0,
          width: 0,
          kernedWidth: 0,
          height: this.fontSize
        };
        if (path) {
          totalPathLength = path.segmentsInfo[path.segmentsInfo.length - 1].length;
          startingPoint = fabric3.util.getPointOnPath(path.path, 0, path.segmentsInfo);
          startingPoint.x += path.pathOffset.x;
          startingPoint.y += path.pathOffset.y;
          switch (this.textAlign) {
            case "left":
              positionInPath = reverse ? totalPathLength - width : 0;
              break;
            case "center":
              positionInPath = (totalPathLength - width) / 2;
              break;
            case "right":
              positionInPath = reverse ? 0 : totalPathLength - width;
              break;
          }
          positionInPath += this.pathStartOffset * (reverse ? -1 : 1);
          for (i2 = reverse ? line.length - 1 : 0; reverse ? i2 >= 0 : i2 < line.length; reverse ? i2-- : i2++) {
            graphemeInfo = lineBounds[i2];
            if (positionInPath > totalPathLength) {
              positionInPath %= totalPathLength;
            } else if (positionInPath < 0) {
              positionInPath += totalPathLength;
            }
            this._setGraphemeOnPath(positionInPath, graphemeInfo, startingPoint);
            positionInPath += graphemeInfo.kernedWidth;
          }
        }
        return { width, numOfSpaces };
      },
      _setGraphemeOnPath: function(positionInPath, graphemeInfo, startingPoint) {
        var centerPosition = positionInPath + graphemeInfo.kernedWidth / 2, path = this.path;
        var info = fabric3.util.getPointOnPath(path.path, centerPosition, path.segmentsInfo);
        graphemeInfo.renderLeft = info.x - startingPoint.x;
        graphemeInfo.renderTop = info.y - startingPoint.y;
        graphemeInfo.angle = info.angle + (this.pathSide === "right" ? Math.PI : 0);
      },
      _getGraphemeBox: function(grapheme, lineIndex, charIndex, prevGrapheme, skipLeft) {
        var style2 = this.getCompleteStyleDeclaration(lineIndex, charIndex), prevStyle = prevGrapheme ? this.getCompleteStyleDeclaration(lineIndex, charIndex - 1) : {}, info = this._measureChar(grapheme, style2, prevGrapheme, prevStyle), kernedWidth = info.kernedWidth, width = info.width, charSpacing;
        if (this.charSpacing !== 0) {
          charSpacing = this._getWidthOfCharSpacing();
          width += charSpacing;
          kernedWidth += charSpacing;
        }
        var box = {
          width,
          left: 0,
          height: style2.fontSize,
          kernedWidth,
          deltaY: style2.deltaY
        };
        if (charIndex > 0 && !skipLeft) {
          var previousBox = this.__charBounds[lineIndex][charIndex - 1];
          box.left = previousBox.left + previousBox.width + info.kernedWidth - info.width;
        }
        return box;
      },
      getHeightOfLine: function(lineIndex) {
        if (this.__lineHeights[lineIndex]) {
          return this.__lineHeights[lineIndex];
        }
        var line = this._textLines[lineIndex], maxHeight = this.getHeightOfChar(lineIndex, 0);
        for (var i2 = 1, len = line.length; i2 < len; i2++) {
          maxHeight = Math.max(this.getHeightOfChar(lineIndex, i2), maxHeight);
        }
        return this.__lineHeights[lineIndex] = maxHeight * this.lineHeight * this._fontSizeMult;
      },
      calcTextHeight: function() {
        var lineHeight, height = 0;
        for (var i2 = 0, len = this._textLines.length; i2 < len; i2++) {
          lineHeight = this.getHeightOfLine(i2);
          height += i2 === len - 1 ? lineHeight / this.lineHeight : lineHeight;
        }
        return height;
      },
      _getLeftOffset: function() {
        return this.direction === "ltr" ? -this.width / 2 : this.width / 2;
      },
      _getTopOffset: function() {
        return -this.height / 2;
      },
      _renderTextCommon: function(ctx, method) {
        ctx.save();
        var lineHeights = 0, left = this._getLeftOffset(), top = this._getTopOffset();
        for (var i2 = 0, len = this._textLines.length; i2 < len; i2++) {
          var heightOfLine = this.getHeightOfLine(i2), maxHeight = heightOfLine / this.lineHeight, leftOffset = this._getLineLeftOffset(i2);
          this._renderTextLine(method, ctx, this._textLines[i2], left + leftOffset, top + lineHeights + maxHeight, i2);
          lineHeights += heightOfLine;
        }
        ctx.restore();
      },
      _renderTextFill: function(ctx) {
        if (!this.fill && !this.styleHas("fill")) {
          return;
        }
        this._renderTextCommon(ctx, "fillText");
      },
      _renderTextStroke: function(ctx) {
        if ((!this.stroke || this.strokeWidth === 0) && this.isEmptyStyles()) {
          return;
        }
        if (this.shadow && !this.shadow.affectStroke) {
          this._removeShadow(ctx);
        }
        ctx.save();
        this._setLineDash(ctx, this.strokeDashArray);
        ctx.beginPath();
        this._renderTextCommon(ctx, "strokeText");
        ctx.closePath();
        ctx.restore();
      },
      _renderChars: function(method, ctx, line, left, top, lineIndex) {
        var lineHeight = this.getHeightOfLine(lineIndex), isJustify = this.textAlign.indexOf("justify") !== -1, actualStyle, nextStyle, charsToRender = "", charBox, boxWidth = 0, timeToRender, path = this.path, shortCut = !isJustify && this.charSpacing === 0 && this.isEmptyStyles(lineIndex) && !path, isLtr = this.direction === "ltr", sign = this.direction === "ltr" ? 1 : -1, drawingLeft;
        ctx.save();
        top -= lineHeight * this._fontSizeFraction / this.lineHeight;
        if (shortCut) {
          ctx.canvas.setAttribute("dir", isLtr ? "ltr" : "rtl");
          ctx.direction = isLtr ? "ltr" : "rtl";
          ctx.textAlign = isLtr ? "left" : "right";
          this._renderChar(method, ctx, lineIndex, 0, line.join(""), left, top, lineHeight);
          ctx.restore();
          return;
        }
        for (var i2 = 0, len = line.length - 1; i2 <= len; i2++) {
          timeToRender = i2 === len || this.charSpacing || path;
          charsToRender += line[i2];
          charBox = this.__charBounds[lineIndex][i2];
          if (boxWidth === 0) {
            left += sign * (charBox.kernedWidth - charBox.width);
            boxWidth += charBox.width;
          } else {
            boxWidth += charBox.kernedWidth;
          }
          if (isJustify && !timeToRender) {
            if (this._reSpaceAndTab.test(line[i2])) {
              timeToRender = true;
            }
          }
          if (!timeToRender) {
            actualStyle = actualStyle || this.getCompleteStyleDeclaration(lineIndex, i2);
            nextStyle = this.getCompleteStyleDeclaration(lineIndex, i2 + 1);
            timeToRender = this._hasStyleChanged(actualStyle, nextStyle);
          }
          if (timeToRender) {
            if (path) {
              ctx.save();
              ctx.translate(charBox.renderLeft, charBox.renderTop);
              ctx.rotate(charBox.angle);
              this._renderChar(method, ctx, lineIndex, i2, charsToRender, -boxWidth / 2, 0, lineHeight);
              ctx.restore();
            } else {
              drawingLeft = left;
              ctx.canvas.setAttribute("dir", isLtr ? "ltr" : "rtl");
              ctx.direction = isLtr ? "ltr" : "rtl";
              ctx.textAlign = isLtr ? "left" : "right";
              this._renderChar(method, ctx, lineIndex, i2, charsToRender, drawingLeft, top, lineHeight);
            }
            charsToRender = "";
            actualStyle = nextStyle;
            left += sign * boxWidth;
            boxWidth = 0;
          }
        }
        ctx.restore();
      },
      _applyPatternGradientTransformText: function(filler) {
        var pCanvas = fabric3.util.createCanvasElement(), pCtx, width = this.width + this.strokeWidth, height = this.height + this.strokeWidth;
        pCanvas.width = width;
        pCanvas.height = height;
        pCtx = pCanvas.getContext("2d");
        pCtx.beginPath();
        pCtx.moveTo(0, 0);
        pCtx.lineTo(width, 0);
        pCtx.lineTo(width, height);
        pCtx.lineTo(0, height);
        pCtx.closePath();
        pCtx.translate(width / 2, height / 2);
        pCtx.fillStyle = filler.toLive(pCtx);
        this._applyPatternGradientTransform(pCtx, filler);
        pCtx.fill();
        return pCtx.createPattern(pCanvas, "no-repeat");
      },
      handleFiller: function(ctx, property, filler) {
        var offsetX, offsetY;
        if (filler.toLive) {
          if (filler.gradientUnits === "percentage" || filler.gradientTransform || filler.patternTransform) {
            offsetX = -this.width / 2;
            offsetY = -this.height / 2;
            ctx.translate(offsetX, offsetY);
            ctx[property] = this._applyPatternGradientTransformText(filler);
            return { offsetX, offsetY };
          } else {
            ctx[property] = filler.toLive(ctx, this);
            return this._applyPatternGradientTransform(ctx, filler);
          }
        } else {
          ctx[property] = filler;
        }
        return { offsetX: 0, offsetY: 0 };
      },
      _setStrokeStyles: function(ctx, decl) {
        ctx.lineWidth = decl.strokeWidth;
        ctx.lineCap = this.strokeLineCap;
        ctx.lineDashOffset = this.strokeDashOffset;
        ctx.lineJoin = this.strokeLineJoin;
        ctx.miterLimit = this.strokeMiterLimit;
        return this.handleFiller(ctx, "strokeStyle", decl.stroke);
      },
      _setFillStyles: function(ctx, decl) {
        return this.handleFiller(ctx, "fillStyle", decl.fill);
      },
      _renderChar: function(method, ctx, lineIndex, charIndex, _char, left, top) {
        var decl = this._getStyleDeclaration(lineIndex, charIndex), fullDecl = this.getCompleteStyleDeclaration(lineIndex, charIndex), shouldFill = method === "fillText" && fullDecl.fill, shouldStroke = method === "strokeText" && fullDecl.stroke && fullDecl.strokeWidth, fillOffsets, strokeOffsets;
        if (!shouldStroke && !shouldFill) {
          return;
        }
        ctx.save();
        shouldFill && (fillOffsets = this._setFillStyles(ctx, fullDecl));
        shouldStroke && (strokeOffsets = this._setStrokeStyles(ctx, fullDecl));
        ctx.font = this._getFontDeclaration(fullDecl);
        if (decl && decl.textBackgroundColor) {
          this._removeShadow(ctx);
        }
        if (decl && decl.deltaY) {
          top += decl.deltaY;
        }
        shouldFill && ctx.fillText(_char, left - fillOffsets.offsetX, top - fillOffsets.offsetY);
        shouldStroke && ctx.strokeText(_char, left - strokeOffsets.offsetX, top - strokeOffsets.offsetY);
        ctx.restore();
      },
      setSuperscript: function(start, end) {
        return this._setScript(start, end, this.superscript);
      },
      setSubscript: function(start, end) {
        return this._setScript(start, end, this.subscript);
      },
      _setScript: function(start, end, schema) {
        var loc = this.get2DCursorLocation(start, true), fontSize = this.getValueOfPropertyAt(loc.lineIndex, loc.charIndex, "fontSize"), dy = this.getValueOfPropertyAt(loc.lineIndex, loc.charIndex, "deltaY"), style2 = { fontSize: fontSize * schema.size, deltaY: dy + fontSize * schema.baseline };
        this.setSelectionStyles(style2, start, end);
        return this;
      },
      _hasStyleChanged: function(prevStyle, thisStyle) {
        return prevStyle.fill !== thisStyle.fill || prevStyle.stroke !== thisStyle.stroke || prevStyle.strokeWidth !== thisStyle.strokeWidth || prevStyle.fontSize !== thisStyle.fontSize || prevStyle.fontFamily !== thisStyle.fontFamily || prevStyle.fontWeight !== thisStyle.fontWeight || prevStyle.fontStyle !== thisStyle.fontStyle || prevStyle.deltaY !== thisStyle.deltaY;
      },
      _hasStyleChangedForSvg: function(prevStyle, thisStyle) {
        return this._hasStyleChanged(prevStyle, thisStyle) || prevStyle.overline !== thisStyle.overline || prevStyle.underline !== thisStyle.underline || prevStyle.linethrough !== thisStyle.linethrough;
      },
      _getLineLeftOffset: function(lineIndex) {
        var lineWidth = this.getLineWidth(lineIndex), lineDiff = this.width - lineWidth, textAlign = this.textAlign, direction = this.direction, isEndOfWrapping, leftOffset = 0, isEndOfWrapping = this.isEndOfWrapping(lineIndex);
        if (textAlign === "justify" || textAlign === "justify-center" && !isEndOfWrapping || textAlign === "justify-right" && !isEndOfWrapping || textAlign === "justify-left" && !isEndOfWrapping) {
          return 0;
        }
        if (textAlign === "center") {
          leftOffset = lineDiff / 2;
        }
        if (textAlign === "right") {
          leftOffset = lineDiff;
        }
        if (textAlign === "justify-center") {
          leftOffset = lineDiff / 2;
        }
        if (textAlign === "justify-right") {
          leftOffset = lineDiff;
        }
        if (direction === "rtl") {
          leftOffset -= lineDiff;
        }
        return leftOffset;
      },
      _clearCache: function() {
        this.__lineWidths = [];
        this.__lineHeights = [];
        this.__charBounds = [];
      },
      _shouldClearDimensionCache: function() {
        var shouldClear = this._forceClearCache;
        shouldClear || (shouldClear = this.hasStateChanged("_dimensionAffectingProps"));
        if (shouldClear) {
          this.dirty = true;
          this._forceClearCache = false;
        }
        return shouldClear;
      },
      getLineWidth: function(lineIndex) {
        if (this.__lineWidths[lineIndex]) {
          return this.__lineWidths[lineIndex];
        }
        var width, line = this._textLines[lineIndex], lineInfo;
        if (line === "") {
          width = 0;
        } else {
          lineInfo = this.measureLine(lineIndex);
          width = lineInfo.width;
        }
        this.__lineWidths[lineIndex] = width;
        return width;
      },
      _getWidthOfCharSpacing: function() {
        if (this.charSpacing !== 0) {
          return this.fontSize * this.charSpacing / 1e3;
        }
        return 0;
      },
      getValueOfPropertyAt: function(lineIndex, charIndex, property) {
        var charStyle = this._getStyleDeclaration(lineIndex, charIndex);
        if (charStyle && typeof charStyle[property] !== "undefined") {
          return charStyle[property];
        }
        return this[property];
      },
      _renderTextDecoration: function(ctx, type) {
        if (!this[type] && !this.styleHas(type)) {
          return;
        }
        var heightOfLine, size, _size, lineLeftOffset, dy, _dy, line, lastDecoration, leftOffset = this._getLeftOffset(), topOffset = this._getTopOffset(), top, boxStart, boxWidth, charBox, currentDecoration, maxHeight, currentFill, lastFill, path = this.path, charSpacing = this._getWidthOfCharSpacing(), offsetY = this.offsets[type];
        for (var i2 = 0, len = this._textLines.length; i2 < len; i2++) {
          heightOfLine = this.getHeightOfLine(i2);
          if (!this[type] && !this.styleHas(type, i2)) {
            topOffset += heightOfLine;
            continue;
          }
          line = this._textLines[i2];
          maxHeight = heightOfLine / this.lineHeight;
          lineLeftOffset = this._getLineLeftOffset(i2);
          boxStart = 0;
          boxWidth = 0;
          lastDecoration = this.getValueOfPropertyAt(i2, 0, type);
          lastFill = this.getValueOfPropertyAt(i2, 0, "fill");
          top = topOffset + maxHeight * (1 - this._fontSizeFraction);
          size = this.getHeightOfChar(i2, 0);
          dy = this.getValueOfPropertyAt(i2, 0, "deltaY");
          for (var j2 = 0, jlen = line.length; j2 < jlen; j2++) {
            charBox = this.__charBounds[i2][j2];
            currentDecoration = this.getValueOfPropertyAt(i2, j2, type);
            currentFill = this.getValueOfPropertyAt(i2, j2, "fill");
            _size = this.getHeightOfChar(i2, j2);
            _dy = this.getValueOfPropertyAt(i2, j2, "deltaY");
            if (path && currentDecoration && currentFill) {
              ctx.save();
              ctx.fillStyle = lastFill;
              ctx.translate(charBox.renderLeft, charBox.renderTop);
              ctx.rotate(charBox.angle);
              ctx.fillRect(-charBox.kernedWidth / 2, offsetY * _size + _dy, charBox.kernedWidth, this.fontSize / 15);
              ctx.restore();
            } else if ((currentDecoration !== lastDecoration || currentFill !== lastFill || _size !== size || _dy !== dy) && boxWidth > 0) {
              var drawStart = leftOffset + lineLeftOffset + boxStart;
              if (this.direction === "rtl") {
                drawStart = this.width - drawStart - boxWidth;
              }
              if (lastDecoration && lastFill) {
                ctx.fillStyle = lastFill;
                ctx.fillRect(drawStart, top + offsetY * size + dy, boxWidth, this.fontSize / 15);
              }
              boxStart = charBox.left;
              boxWidth = charBox.width;
              lastDecoration = currentDecoration;
              lastFill = currentFill;
              size = _size;
              dy = _dy;
            } else {
              boxWidth += charBox.kernedWidth;
            }
          }
          var drawStart = leftOffset + lineLeftOffset + boxStart;
          if (this.direction === "rtl") {
            drawStart = this.width - drawStart - boxWidth;
          }
          ctx.fillStyle = currentFill;
          currentDecoration && currentFill && ctx.fillRect(drawStart, top + offsetY * size + dy, boxWidth - charSpacing, this.fontSize / 15);
          topOffset += heightOfLine;
        }
        this._removeShadow(ctx);
      },
      _getFontDeclaration: function(styleObject, forMeasuring) {
        var style2 = styleObject || this, family = this.fontFamily, fontIsGeneric = fabric3.Text.genericFonts.indexOf(family.toLowerCase()) > -1;
        var fontFamily = family === void 0 || family.indexOf("'") > -1 || family.indexOf(",") > -1 || family.indexOf('"') > -1 || fontIsGeneric ? style2.fontFamily : '"' + style2.fontFamily + '"';
        return [
          fabric3.isLikelyNode ? style2.fontWeight : style2.fontStyle,
          fabric3.isLikelyNode ? style2.fontStyle : style2.fontWeight,
          forMeasuring ? this.CACHE_FONT_SIZE + "px" : style2.fontSize + "px",
          fontFamily
        ].join(" ");
      },
      render: function(ctx) {
        if (!this.visible) {
          return;
        }
        if (this.canvas && this.canvas.skipOffscreen && !this.group && !this.isOnScreen()) {
          return;
        }
        if (this._shouldClearDimensionCache()) {
          this.initDimensions();
        }
        this.callSuper("render", ctx);
      },
      _splitTextIntoLines: function(text2) {
        var lines = text2.split(this._reNewline), newLines = new Array(lines.length), newLine = ["\n"], newText = [];
        for (var i2 = 0; i2 < lines.length; i2++) {
          newLines[i2] = fabric3.util.string.graphemeSplit(lines[i2]);
          newText = newText.concat(newLines[i2], newLine);
        }
        newText.pop();
        return { _unwrappedLines: newLines, lines, graphemeText: newText, graphemeLines: newLines };
      },
      toObject: function(propertiesToInclude) {
        var allProperties = additionalProps.concat(propertiesToInclude);
        var obj = this.callSuper("toObject", allProperties);
        obj.styles = clone(this.styles, true);
        if (obj.path) {
          obj.path = this.path.toObject();
        }
        return obj;
      },
      set: function(key, value) {
        this.callSuper("set", key, value);
        var needsDims = false;
        var isAddingPath = false;
        if (typeof key === "object") {
          for (var _key in key) {
            if (_key === "path") {
              this.setPathInfo();
            }
            needsDims = needsDims || this._dimensionAffectingProps.indexOf(_key) !== -1;
            isAddingPath = isAddingPath || _key === "path";
          }
        } else {
          needsDims = this._dimensionAffectingProps.indexOf(key) !== -1;
          isAddingPath = key === "path";
        }
        if (isAddingPath) {
          this.setPathInfo();
        }
        if (needsDims) {
          this.initDimensions();
          this.setCoords();
        }
        return this;
      },
      complexity: function() {
        return 1;
      }
    });
    fabric3.Text.ATTRIBUTE_NAMES = fabric3.SHARED_ATTRIBUTES.concat("x y dx dy font-family font-style font-weight font-size letter-spacing text-decoration text-anchor".split(" "));
    fabric3.Text.DEFAULT_SVG_FONT_SIZE = 16;
    fabric3.Text.fromElement = function(element, callback, options) {
      if (!element) {
        return callback(null);
      }
      var parsedAttributes = fabric3.parseAttributes(element, fabric3.Text.ATTRIBUTE_NAMES), parsedAnchor = parsedAttributes.textAnchor || "left";
      options = fabric3.util.object.extend(options ? clone(options) : {}, parsedAttributes);
      options.top = options.top || 0;
      options.left = options.left || 0;
      if (parsedAttributes.textDecoration) {
        var textDecoration = parsedAttributes.textDecoration;
        if (textDecoration.indexOf("underline") !== -1) {
          options.underline = true;
        }
        if (textDecoration.indexOf("overline") !== -1) {
          options.overline = true;
        }
        if (textDecoration.indexOf("line-through") !== -1) {
          options.linethrough = true;
        }
        delete options.textDecoration;
      }
      if ("dx" in parsedAttributes) {
        options.left += parsedAttributes.dx;
      }
      if ("dy" in parsedAttributes) {
        options.top += parsedAttributes.dy;
      }
      if (!("fontSize" in options)) {
        options.fontSize = fabric3.Text.DEFAULT_SVG_FONT_SIZE;
      }
      var textContent = "";
      if (!("textContent" in element)) {
        if ("firstChild" in element && element.firstChild !== null) {
          if ("data" in element.firstChild && element.firstChild.data !== null) {
            textContent = element.firstChild.data;
          }
        }
      } else {
        textContent = element.textContent;
      }
      textContent = textContent.replace(/^\s+|\s+$|\n+/g, "").replace(/\s+/g, " ");
      var originalStrokeWidth = options.strokeWidth;
      options.strokeWidth = 0;
      var text2 = new fabric3.Text(textContent, options), textHeightScaleFactor = text2.getScaledHeight() / text2.height, lineHeightDiff = (text2.height + text2.strokeWidth) * text2.lineHeight - text2.height, scaledDiff = lineHeightDiff * textHeightScaleFactor, textHeight = text2.getScaledHeight() + scaledDiff, offX = 0;
      if (parsedAnchor === "center") {
        offX = text2.getScaledWidth() / 2;
      }
      if (parsedAnchor === "right") {
        offX = text2.getScaledWidth();
      }
      text2.set({
        left: text2.left - offX,
        top: text2.top - (textHeight - text2.fontSize * (0.07 + text2._fontSizeFraction)) / text2.lineHeight,
        strokeWidth: typeof originalStrokeWidth !== "undefined" ? originalStrokeWidth : 1
      });
      callback(text2);
    };
    fabric3.Text.fromObject = function(object, callback) {
      var objectCopy = clone(object), path = object.path;
      delete objectCopy.path;
      return fabric3.Object._fromObject("Text", objectCopy, function(textInstance) {
        if (path) {
          fabric3.Object._fromObject("Path", path, function(pathInstance) {
            textInstance.set("path", pathInstance);
            callback(textInstance);
          }, "path");
        } else {
          callback(textInstance);
        }
      }, "text");
    };
    fabric3.Text.genericFonts = ["sans-serif", "serif", "cursive", "fantasy", "monospace"];
    fabric3.util.createAccessors && fabric3.util.createAccessors(fabric3.Text);
  })(exports2);
  (function() {
    fabric2.util.object.extend(fabric2.Text.prototype, {
      isEmptyStyles: function(lineIndex) {
        if (!this.styles) {
          return true;
        }
        if (typeof lineIndex !== "undefined" && !this.styles[lineIndex]) {
          return true;
        }
        var obj = typeof lineIndex === "undefined" ? this.styles : { line: this.styles[lineIndex] };
        for (var p1 in obj) {
          for (var p2 in obj[p1]) {
            for (var p3 in obj[p1][p2]) {
              return false;
            }
          }
        }
        return true;
      },
      styleHas: function(property, lineIndex) {
        if (!this.styles || !property || property === "") {
          return false;
        }
        if (typeof lineIndex !== "undefined" && !this.styles[lineIndex]) {
          return false;
        }
        var obj = typeof lineIndex === "undefined" ? this.styles : { 0: this.styles[lineIndex] };
        for (var p1 in obj) {
          for (var p2 in obj[p1]) {
            if (typeof obj[p1][p2][property] !== "undefined") {
              return true;
            }
          }
        }
        return false;
      },
      cleanStyle: function(property) {
        if (!this.styles || !property || property === "") {
          return false;
        }
        var obj = this.styles, stylesCount = 0, letterCount, stylePropertyValue, allStyleObjectPropertiesMatch = true, graphemeCount = 0, styleObject;
        for (var p1 in obj) {
          letterCount = 0;
          for (var p2 in obj[p1]) {
            var styleObject = obj[p1][p2], stylePropertyHasBeenSet = styleObject.hasOwnProperty(property);
            stylesCount++;
            if (stylePropertyHasBeenSet) {
              if (!stylePropertyValue) {
                stylePropertyValue = styleObject[property];
              } else if (styleObject[property] !== stylePropertyValue) {
                allStyleObjectPropertiesMatch = false;
              }
              if (styleObject[property] === this[property]) {
                delete styleObject[property];
              }
            } else {
              allStyleObjectPropertiesMatch = false;
            }
            if (Object.keys(styleObject).length !== 0) {
              letterCount++;
            } else {
              delete obj[p1][p2];
            }
          }
          if (letterCount === 0) {
            delete obj[p1];
          }
        }
        for (var i2 = 0; i2 < this._textLines.length; i2++) {
          graphemeCount += this._textLines[i2].length;
        }
        if (allStyleObjectPropertiesMatch && stylesCount === graphemeCount) {
          this[property] = stylePropertyValue;
          this.removeStyle(property);
        }
      },
      removeStyle: function(property) {
        if (!this.styles || !property || property === "") {
          return;
        }
        var obj = this.styles, line, lineNum, charNum;
        for (lineNum in obj) {
          line = obj[lineNum];
          for (charNum in line) {
            delete line[charNum][property];
            if (Object.keys(line[charNum]).length === 0) {
              delete line[charNum];
            }
          }
          if (Object.keys(line).length === 0) {
            delete obj[lineNum];
          }
        }
      },
      _extendStyles: function(index2, styles) {
        var loc = this.get2DCursorLocation(index2);
        if (!this._getLineStyle(loc.lineIndex)) {
          this._setLineStyle(loc.lineIndex);
        }
        if (!this._getStyleDeclaration(loc.lineIndex, loc.charIndex)) {
          this._setStyleDeclaration(loc.lineIndex, loc.charIndex, {});
        }
        fabric2.util.object.extend(this._getStyleDeclaration(loc.lineIndex, loc.charIndex), styles);
      },
      get2DCursorLocation: function(selectionStart, skipWrapping) {
        if (typeof selectionStart === "undefined") {
          selectionStart = this.selectionStart;
        }
        var lines = skipWrapping ? this._unwrappedTextLines : this._textLines, len = lines.length;
        for (var i2 = 0; i2 < len; i2++) {
          if (selectionStart <= lines[i2].length) {
            return {
              lineIndex: i2,
              charIndex: selectionStart
            };
          }
          selectionStart -= lines[i2].length + this.missingNewlineOffset(i2);
        }
        return {
          lineIndex: i2 - 1,
          charIndex: lines[i2 - 1].length < selectionStart ? lines[i2 - 1].length : selectionStart
        };
      },
      getSelectionStyles: function(startIndex, endIndex, complete) {
        if (typeof startIndex === "undefined") {
          startIndex = this.selectionStart || 0;
        }
        if (typeof endIndex === "undefined") {
          endIndex = this.selectionEnd || startIndex;
        }
        var styles = [];
        for (var i2 = startIndex; i2 < endIndex; i2++) {
          styles.push(this.getStyleAtPosition(i2, complete));
        }
        return styles;
      },
      getStyleAtPosition: function(position2, complete) {
        var loc = this.get2DCursorLocation(position2), style2 = complete ? this.getCompleteStyleDeclaration(loc.lineIndex, loc.charIndex) : this._getStyleDeclaration(loc.lineIndex, loc.charIndex);
        return style2 || {};
      },
      setSelectionStyles: function(styles, startIndex, endIndex) {
        if (typeof startIndex === "undefined") {
          startIndex = this.selectionStart || 0;
        }
        if (typeof endIndex === "undefined") {
          endIndex = this.selectionEnd || startIndex;
        }
        for (var i2 = startIndex; i2 < endIndex; i2++) {
          this._extendStyles(i2, styles);
        }
        this._forceClearCache = true;
        return this;
      },
      _getStyleDeclaration: function(lineIndex, charIndex) {
        var lineStyle = this.styles && this.styles[lineIndex];
        if (!lineStyle) {
          return null;
        }
        return lineStyle[charIndex];
      },
      getCompleteStyleDeclaration: function(lineIndex, charIndex) {
        var style2 = this._getStyleDeclaration(lineIndex, charIndex) || {}, styleObject = {}, prop;
        for (var i2 = 0; i2 < this._styleProperties.length; i2++) {
          prop = this._styleProperties[i2];
          styleObject[prop] = typeof style2[prop] === "undefined" ? this[prop] : style2[prop];
        }
        return styleObject;
      },
      _setStyleDeclaration: function(lineIndex, charIndex, style2) {
        this.styles[lineIndex][charIndex] = style2;
      },
      _deleteStyleDeclaration: function(lineIndex, charIndex) {
        delete this.styles[lineIndex][charIndex];
      },
      _getLineStyle: function(lineIndex) {
        return !!this.styles[lineIndex];
      },
      _setLineStyle: function(lineIndex) {
        this.styles[lineIndex] = {};
      },
      _deleteLineStyle: function(lineIndex) {
        delete this.styles[lineIndex];
      }
    });
  })();
  (function() {
    function parseDecoration(object) {
      if (object.textDecoration) {
        object.textDecoration.indexOf("underline") > -1 && (object.underline = true);
        object.textDecoration.indexOf("line-through") > -1 && (object.linethrough = true);
        object.textDecoration.indexOf("overline") > -1 && (object.overline = true);
        delete object.textDecoration;
      }
    }
    fabric2.IText = fabric2.util.createClass(fabric2.Text, fabric2.Observable, {
      type: "i-text",
      selectionStart: 0,
      selectionEnd: 0,
      selectionColor: "rgba(17,119,255,0.3)",
      isEditing: false,
      editable: true,
      editingBorderColor: "rgba(102,153,255,0.25)",
      cursorWidth: 2,
      cursorColor: "",
      cursorDelay: 1e3,
      cursorDuration: 600,
      caching: true,
      hiddenTextareaContainer: null,
      _reSpace: /\s|\n/,
      _currentCursorOpacity: 0,
      _selectionDirection: null,
      _abortCursorAnimation: false,
      __widthOfSpace: [],
      inCompositionMode: false,
      initialize: function(text2, options) {
        this.callSuper("initialize", text2, options);
        this.initBehavior();
      },
      setSelectionStart: function(index2) {
        index2 = Math.max(index2, 0);
        this._updateAndFire("selectionStart", index2);
      },
      setSelectionEnd: function(index2) {
        index2 = Math.min(index2, this.text.length);
        this._updateAndFire("selectionEnd", index2);
      },
      _updateAndFire: function(property, index2) {
        if (this[property] !== index2) {
          this._fireSelectionChanged();
          this[property] = index2;
        }
        this._updateTextarea();
      },
      _fireSelectionChanged: function() {
        this.fire("selection:changed");
        this.canvas && this.canvas.fire("text:selection:changed", { target: this });
      },
      initDimensions: function() {
        this.isEditing && this.initDelayedCursor();
        this.clearContextTop();
        this.callSuper("initDimensions");
      },
      render: function(ctx) {
        this.clearContextTop();
        this.callSuper("render", ctx);
        this.cursorOffsetCache = {};
        this.renderCursorOrSelection();
      },
      _render: function(ctx) {
        this.callSuper("_render", ctx);
      },
      clearContextTop: function(skipRestore) {
        if (!this.isEditing || !this.canvas || !this.canvas.contextTop) {
          return;
        }
        var ctx = this.canvas.contextTop, v2 = this.canvas.viewportTransform;
        ctx.save();
        ctx.transform(v2[0], v2[1], v2[2], v2[3], v2[4], v2[5]);
        this.transform(ctx);
        this._clearTextArea(ctx);
        skipRestore || ctx.restore();
      },
      renderCursorOrSelection: function() {
        if (!this.isEditing || !this.canvas || !this.canvas.contextTop) {
          return;
        }
        var boundaries = this._getCursorBoundaries(), ctx = this.canvas.contextTop;
        this.clearContextTop(true);
        if (this.selectionStart === this.selectionEnd) {
          this.renderCursor(boundaries, ctx);
        } else {
          this.renderSelection(boundaries, ctx);
        }
        ctx.restore();
      },
      _clearTextArea: function(ctx) {
        var width = this.width + 4, height = this.height + 4;
        ctx.clearRect(-width / 2, -height / 2, width, height);
      },
      _getCursorBoundaries: function(position2) {
        if (typeof position2 === "undefined") {
          position2 = this.selectionStart;
        }
        var left = this._getLeftOffset(), top = this._getTopOffset(), offsets = this._getCursorBoundariesOffsets(position2);
        return {
          left,
          top,
          leftOffset: offsets.left,
          topOffset: offsets.top
        };
      },
      _getCursorBoundariesOffsets: function(position2) {
        if (this.cursorOffsetCache && "top" in this.cursorOffsetCache) {
          return this.cursorOffsetCache;
        }
        var lineLeftOffset, lineIndex, charIndex, topOffset = 0, leftOffset = 0, boundaries, cursorPosition = this.get2DCursorLocation(position2);
        charIndex = cursorPosition.charIndex;
        lineIndex = cursorPosition.lineIndex;
        for (var i2 = 0; i2 < lineIndex; i2++) {
          topOffset += this.getHeightOfLine(i2);
        }
        lineLeftOffset = this._getLineLeftOffset(lineIndex);
        var bound = this.__charBounds[lineIndex][charIndex];
        bound && (leftOffset = bound.left);
        if (this.charSpacing !== 0 && charIndex === this._textLines[lineIndex].length) {
          leftOffset -= this._getWidthOfCharSpacing();
        }
        boundaries = {
          top: topOffset,
          left: lineLeftOffset + (leftOffset > 0 ? leftOffset : 0)
        };
        if (this.direction === "rtl") {
          boundaries.left *= -1;
        }
        this.cursorOffsetCache = boundaries;
        return this.cursorOffsetCache;
      },
      renderCursor: function(boundaries, ctx) {
        var cursorLocation = this.get2DCursorLocation(), lineIndex = cursorLocation.lineIndex, charIndex = cursorLocation.charIndex > 0 ? cursorLocation.charIndex - 1 : 0, charHeight = this.getValueOfPropertyAt(lineIndex, charIndex, "fontSize"), multiplier = this.scaleX * this.canvas.getZoom(), cursorWidth = this.cursorWidth / multiplier, topOffset = boundaries.topOffset, dy = this.getValueOfPropertyAt(lineIndex, charIndex, "deltaY");
        topOffset += (1 - this._fontSizeFraction) * this.getHeightOfLine(lineIndex) / this.lineHeight - charHeight * (1 - this._fontSizeFraction);
        if (this.inCompositionMode) {
          this.renderSelection(boundaries, ctx);
        }
        ctx.fillStyle = this.cursorColor || this.getValueOfPropertyAt(lineIndex, charIndex, "fill");
        ctx.globalAlpha = this.__isMousedown ? 1 : this._currentCursorOpacity;
        ctx.fillRect(boundaries.left + boundaries.leftOffset - cursorWidth / 2, topOffset + boundaries.top + dy, cursorWidth, charHeight);
      },
      renderSelection: function(boundaries, ctx) {
        var selectionStart = this.inCompositionMode ? this.hiddenTextarea.selectionStart : this.selectionStart, selectionEnd = this.inCompositionMode ? this.hiddenTextarea.selectionEnd : this.selectionEnd, isJustify = this.textAlign.indexOf("justify") !== -1, start = this.get2DCursorLocation(selectionStart), end = this.get2DCursorLocation(selectionEnd), startLine = start.lineIndex, endLine = end.lineIndex, startChar = start.charIndex < 0 ? 0 : start.charIndex, endChar = end.charIndex < 0 ? 0 : end.charIndex;
        for (var i2 = startLine; i2 <= endLine; i2++) {
          var lineOffset = this._getLineLeftOffset(i2) || 0, lineHeight = this.getHeightOfLine(i2), realLineHeight = 0, boxStart = 0, boxEnd = 0;
          if (i2 === startLine) {
            boxStart = this.__charBounds[startLine][startChar].left;
          }
          if (i2 >= startLine && i2 < endLine) {
            boxEnd = isJustify && !this.isEndOfWrapping(i2) ? this.width : this.getLineWidth(i2) || 5;
          } else if (i2 === endLine) {
            if (endChar === 0) {
              boxEnd = this.__charBounds[endLine][endChar].left;
            } else {
              var charSpacing = this._getWidthOfCharSpacing();
              boxEnd = this.__charBounds[endLine][endChar - 1].left + this.__charBounds[endLine][endChar - 1].width - charSpacing;
            }
          }
          realLineHeight = lineHeight;
          if (this.lineHeight < 1 || i2 === endLine && this.lineHeight > 1) {
            lineHeight /= this.lineHeight;
          }
          var drawStart = boundaries.left + lineOffset + boxStart, drawWidth = boxEnd - boxStart, drawHeight = lineHeight, extraTop = 0;
          if (this.inCompositionMode) {
            ctx.fillStyle = this.compositionColor || "black";
            drawHeight = 1;
            extraTop = lineHeight;
          } else {
            ctx.fillStyle = this.selectionColor;
          }
          if (this.direction === "rtl") {
            drawStart = this.width - drawStart - drawWidth;
          }
          ctx.fillRect(drawStart, boundaries.top + boundaries.topOffset + extraTop, drawWidth, drawHeight);
          boundaries.topOffset += realLineHeight;
        }
      },
      getCurrentCharFontSize: function() {
        var cp = this._getCurrentCharIndex();
        return this.getValueOfPropertyAt(cp.l, cp.c, "fontSize");
      },
      getCurrentCharColor: function() {
        var cp = this._getCurrentCharIndex();
        return this.getValueOfPropertyAt(cp.l, cp.c, "fill");
      },
      _getCurrentCharIndex: function() {
        var cursorPosition = this.get2DCursorLocation(this.selectionStart, true), charIndex = cursorPosition.charIndex > 0 ? cursorPosition.charIndex - 1 : 0;
        return { l: cursorPosition.lineIndex, c: charIndex };
      }
    });
    fabric2.IText.fromObject = function(object, callback) {
      parseDecoration(object);
      if (object.styles) {
        for (var i2 in object.styles) {
          for (var j2 in object.styles[i2]) {
            parseDecoration(object.styles[i2][j2]);
          }
        }
      }
      fabric2.Object._fromObject("IText", object, callback, "text");
    };
  })();
  (function() {
    var clone = fabric2.util.object.clone;
    fabric2.util.object.extend(fabric2.IText.prototype, {
      initBehavior: function() {
        this.initAddedHandler();
        this.initRemovedHandler();
        this.initCursorSelectionHandlers();
        this.initDoubleClickSimulation();
        this.mouseMoveHandler = this.mouseMoveHandler.bind(this);
      },
      onDeselect: function() {
        this.isEditing && this.exitEditing();
        this.selected = false;
      },
      initAddedHandler: function() {
        var _this = this;
        this.on("added", function() {
          var canvas = _this.canvas;
          if (canvas) {
            if (!canvas._hasITextHandlers) {
              canvas._hasITextHandlers = true;
              _this._initCanvasHandlers(canvas);
            }
            canvas._iTextInstances = canvas._iTextInstances || [];
            canvas._iTextInstances.push(_this);
          }
        });
      },
      initRemovedHandler: function() {
        var _this = this;
        this.on("removed", function() {
          var canvas = _this.canvas;
          if (canvas) {
            canvas._iTextInstances = canvas._iTextInstances || [];
            fabric2.util.removeFromArray(canvas._iTextInstances, _this);
            if (canvas._iTextInstances.length === 0) {
              canvas._hasITextHandlers = false;
              _this._removeCanvasHandlers(canvas);
            }
          }
        });
      },
      _initCanvasHandlers: function(canvas) {
        canvas._mouseUpITextHandler = function() {
          if (canvas._iTextInstances) {
            canvas._iTextInstances.forEach(function(obj) {
              obj.__isMousedown = false;
            });
          }
        };
        canvas.on("mouse:up", canvas._mouseUpITextHandler);
      },
      _removeCanvasHandlers: function(canvas) {
        canvas.off("mouse:up", canvas._mouseUpITextHandler);
      },
      _tick: function() {
        this._currentTickState = this._animateCursor(this, 1, this.cursorDuration, "_onTickComplete");
      },
      _animateCursor: function(obj, targetOpacity, duration, completeMethod) {
        var tickState;
        tickState = {
          isAborted: false,
          abort: function() {
            this.isAborted = true;
          }
        };
        obj.animate("_currentCursorOpacity", targetOpacity, {
          duration,
          onComplete: function() {
            if (!tickState.isAborted) {
              obj[completeMethod]();
            }
          },
          onChange: function() {
            if (obj.canvas && obj.selectionStart === obj.selectionEnd) {
              obj.renderCursorOrSelection();
            }
          },
          abort: function() {
            return tickState.isAborted;
          }
        });
        return tickState;
      },
      _onTickComplete: function() {
        var _this = this;
        if (this._cursorTimeout1) {
          clearTimeout(this._cursorTimeout1);
        }
        this._cursorTimeout1 = setTimeout(function() {
          _this._currentTickCompleteState = _this._animateCursor(_this, 0, this.cursorDuration / 2, "_tick");
        }, 100);
      },
      initDelayedCursor: function(restart) {
        var _this = this, delay = restart ? 0 : this.cursorDelay;
        this.abortCursorAnimation();
        this._currentCursorOpacity = 1;
        this._cursorTimeout2 = setTimeout(function() {
          _this._tick();
        }, delay);
      },
      abortCursorAnimation: function() {
        var shouldClear = this._currentTickState || this._currentTickCompleteState, canvas = this.canvas;
        this._currentTickState && this._currentTickState.abort();
        this._currentTickCompleteState && this._currentTickCompleteState.abort();
        clearTimeout(this._cursorTimeout1);
        clearTimeout(this._cursorTimeout2);
        this._currentCursorOpacity = 0;
        if (shouldClear && canvas) {
          canvas.clearContext(canvas.contextTop || canvas.contextContainer);
        }
      },
      selectAll: function() {
        this.selectionStart = 0;
        this.selectionEnd = this._text.length;
        this._fireSelectionChanged();
        this._updateTextarea();
        return this;
      },
      getSelectedText: function() {
        return this._text.slice(this.selectionStart, this.selectionEnd).join("");
      },
      findWordBoundaryLeft: function(startFrom) {
        var offset2 = 0, index2 = startFrom - 1;
        if (this._reSpace.test(this._text[index2])) {
          while (this._reSpace.test(this._text[index2])) {
            offset2++;
            index2--;
          }
        }
        while (/\S/.test(this._text[index2]) && index2 > -1) {
          offset2++;
          index2--;
        }
        return startFrom - offset2;
      },
      findWordBoundaryRight: function(startFrom) {
        var offset2 = 0, index2 = startFrom;
        if (this._reSpace.test(this._text[index2])) {
          while (this._reSpace.test(this._text[index2])) {
            offset2++;
            index2++;
          }
        }
        while (/\S/.test(this._text[index2]) && index2 < this._text.length) {
          offset2++;
          index2++;
        }
        return startFrom + offset2;
      },
      findLineBoundaryLeft: function(startFrom) {
        var offset2 = 0, index2 = startFrom - 1;
        while (!/\n/.test(this._text[index2]) && index2 > -1) {
          offset2++;
          index2--;
        }
        return startFrom - offset2;
      },
      findLineBoundaryRight: function(startFrom) {
        var offset2 = 0, index2 = startFrom;
        while (!/\n/.test(this._text[index2]) && index2 < this._text.length) {
          offset2++;
          index2++;
        }
        return startFrom + offset2;
      },
      searchWordBoundary: function(selectionStart, direction) {
        var text2 = this._text, index2 = this._reSpace.test(text2[selectionStart]) ? selectionStart - 1 : selectionStart, _char = text2[index2], reNonWord = fabric2.reNonWord;
        while (!reNonWord.test(_char) && index2 > 0 && index2 < text2.length) {
          index2 += direction;
          _char = text2[index2];
        }
        if (reNonWord.test(_char)) {
          index2 += direction === 1 ? 0 : 1;
        }
        return index2;
      },
      selectWord: function(selectionStart) {
        selectionStart = selectionStart || this.selectionStart;
        var newSelectionStart = this.searchWordBoundary(selectionStart, -1), newSelectionEnd = this.searchWordBoundary(selectionStart, 1);
        this.selectionStart = newSelectionStart;
        this.selectionEnd = newSelectionEnd;
        this._fireSelectionChanged();
        this._updateTextarea();
        this.renderCursorOrSelection();
      },
      selectLine: function(selectionStart) {
        selectionStart = selectionStart || this.selectionStart;
        var newSelectionStart = this.findLineBoundaryLeft(selectionStart), newSelectionEnd = this.findLineBoundaryRight(selectionStart);
        this.selectionStart = newSelectionStart;
        this.selectionEnd = newSelectionEnd;
        this._fireSelectionChanged();
        this._updateTextarea();
        return this;
      },
      enterEditing: function(e2) {
        if (this.isEditing || !this.editable) {
          return;
        }
        if (this.canvas) {
          this.canvas.calcOffset();
          this.exitEditingOnOthers(this.canvas);
        }
        this.isEditing = true;
        this.initHiddenTextarea(e2);
        this.hiddenTextarea.focus();
        this.hiddenTextarea.value = this.text;
        this._updateTextarea();
        this._saveEditingProps();
        this._setEditingProps();
        this._textBeforeEdit = this.text;
        this._tick();
        this.fire("editing:entered");
        this._fireSelectionChanged();
        if (!this.canvas) {
          return this;
        }
        this.canvas.fire("text:editing:entered", { target: this });
        this.initMouseMoveHandler();
        this.canvas.requestRenderAll();
        return this;
      },
      exitEditingOnOthers: function(canvas) {
        if (canvas._iTextInstances) {
          canvas._iTextInstances.forEach(function(obj) {
            obj.selected = false;
            if (obj.isEditing) {
              obj.exitEditing();
            }
          });
        }
      },
      initMouseMoveHandler: function() {
        this.canvas.on("mouse:move", this.mouseMoveHandler);
      },
      mouseMoveHandler: function(options) {
        if (!this.__isMousedown || !this.isEditing) {
          return;
        }
        var newSelectionStart = this.getSelectionStartFromPointer(options.e), currentStart = this.selectionStart, currentEnd = this.selectionEnd;
        if ((newSelectionStart !== this.__selectionStartOnMouseDown || currentStart === currentEnd) && (currentStart === newSelectionStart || currentEnd === newSelectionStart)) {
          return;
        }
        if (newSelectionStart > this.__selectionStartOnMouseDown) {
          this.selectionStart = this.__selectionStartOnMouseDown;
          this.selectionEnd = newSelectionStart;
        } else {
          this.selectionStart = newSelectionStart;
          this.selectionEnd = this.__selectionStartOnMouseDown;
        }
        if (this.selectionStart !== currentStart || this.selectionEnd !== currentEnd) {
          this.restartCursorIfNeeded();
          this._fireSelectionChanged();
          this._updateTextarea();
          this.renderCursorOrSelection();
        }
      },
      _setEditingProps: function() {
        this.hoverCursor = "text";
        if (this.canvas) {
          this.canvas.defaultCursor = this.canvas.moveCursor = "text";
        }
        this.borderColor = this.editingBorderColor;
        this.hasControls = this.selectable = false;
        this.lockMovementX = this.lockMovementY = true;
      },
      fromStringToGraphemeSelection: function(start, end, text2) {
        var smallerTextStart = text2.slice(0, start), graphemeStart = fabric2.util.string.graphemeSplit(smallerTextStart).length;
        if (start === end) {
          return { selectionStart: graphemeStart, selectionEnd: graphemeStart };
        }
        var smallerTextEnd = text2.slice(start, end), graphemeEnd = fabric2.util.string.graphemeSplit(smallerTextEnd).length;
        return { selectionStart: graphemeStart, selectionEnd: graphemeStart + graphemeEnd };
      },
      fromGraphemeToStringSelection: function(start, end, _text) {
        var smallerTextStart = _text.slice(0, start), graphemeStart = smallerTextStart.join("").length;
        if (start === end) {
          return { selectionStart: graphemeStart, selectionEnd: graphemeStart };
        }
        var smallerTextEnd = _text.slice(start, end), graphemeEnd = smallerTextEnd.join("").length;
        return { selectionStart: graphemeStart, selectionEnd: graphemeStart + graphemeEnd };
      },
      _updateTextarea: function() {
        this.cursorOffsetCache = {};
        if (!this.hiddenTextarea) {
          return;
        }
        if (!this.inCompositionMode) {
          var newSelection = this.fromGraphemeToStringSelection(this.selectionStart, this.selectionEnd, this._text);
          this.hiddenTextarea.selectionStart = newSelection.selectionStart;
          this.hiddenTextarea.selectionEnd = newSelection.selectionEnd;
        }
        this.updateTextareaPosition();
      },
      updateFromTextArea: function() {
        if (!this.hiddenTextarea) {
          return;
        }
        this.cursorOffsetCache = {};
        this.text = this.hiddenTextarea.value;
        if (this._shouldClearDimensionCache()) {
          this.initDimensions();
          this.setCoords();
        }
        var newSelection = this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart, this.hiddenTextarea.selectionEnd, this.hiddenTextarea.value);
        this.selectionEnd = this.selectionStart = newSelection.selectionEnd;
        if (!this.inCompositionMode) {
          this.selectionStart = newSelection.selectionStart;
        }
        this.updateTextareaPosition();
      },
      updateTextareaPosition: function() {
        if (this.selectionStart === this.selectionEnd) {
          var style2 = this._calcTextareaPosition();
          this.hiddenTextarea.style.left = style2.left;
          this.hiddenTextarea.style.top = style2.top;
        }
      },
      _calcTextareaPosition: function() {
        if (!this.canvas) {
          return { x: 1, y: 1 };
        }
        var desiredPosition = this.inCompositionMode ? this.compositionStart : this.selectionStart, boundaries = this._getCursorBoundaries(desiredPosition), cursorLocation = this.get2DCursorLocation(desiredPosition), lineIndex = cursorLocation.lineIndex, charIndex = cursorLocation.charIndex, charHeight = this.getValueOfPropertyAt(lineIndex, charIndex, "fontSize") * this.lineHeight, leftOffset = boundaries.leftOffset, m2 = this.calcTransformMatrix(), p2 = {
          x: boundaries.left + leftOffset,
          y: boundaries.top + boundaries.topOffset + charHeight
        }, retinaScaling = this.canvas.getRetinaScaling(), upperCanvas = this.canvas.upperCanvasEl, upperCanvasWidth = upperCanvas.width / retinaScaling, upperCanvasHeight = upperCanvas.height / retinaScaling, maxWidth = upperCanvasWidth - charHeight, maxHeight = upperCanvasHeight - charHeight, scaleX = upperCanvas.clientWidth / upperCanvasWidth, scaleY = upperCanvas.clientHeight / upperCanvasHeight;
        p2 = fabric2.util.transformPoint(p2, m2);
        p2 = fabric2.util.transformPoint(p2, this.canvas.viewportTransform);
        p2.x *= scaleX;
        p2.y *= scaleY;
        if (p2.x < 0) {
          p2.x = 0;
        }
        if (p2.x > maxWidth) {
          p2.x = maxWidth;
        }
        if (p2.y < 0) {
          p2.y = 0;
        }
        if (p2.y > maxHeight) {
          p2.y = maxHeight;
        }
        p2.x += this.canvas._offset.left;
        p2.y += this.canvas._offset.top;
        return { left: p2.x + "px", top: p2.y + "px", fontSize: charHeight + "px", charHeight };
      },
      _saveEditingProps: function() {
        this._savedProps = {
          hasControls: this.hasControls,
          borderColor: this.borderColor,
          lockMovementX: this.lockMovementX,
          lockMovementY: this.lockMovementY,
          hoverCursor: this.hoverCursor,
          selectable: this.selectable,
          defaultCursor: this.canvas && this.canvas.defaultCursor,
          moveCursor: this.canvas && this.canvas.moveCursor
        };
      },
      _restoreEditingProps: function() {
        if (!this._savedProps) {
          return;
        }
        this.hoverCursor = this._savedProps.hoverCursor;
        this.hasControls = this._savedProps.hasControls;
        this.borderColor = this._savedProps.borderColor;
        this.selectable = this._savedProps.selectable;
        this.lockMovementX = this._savedProps.lockMovementX;
        this.lockMovementY = this._savedProps.lockMovementY;
        if (this.canvas) {
          this.canvas.defaultCursor = this._savedProps.defaultCursor;
          this.canvas.moveCursor = this._savedProps.moveCursor;
        }
      },
      exitEditing: function() {
        var isTextChanged = this._textBeforeEdit !== this.text;
        var hiddenTextarea = this.hiddenTextarea;
        this.selected = false;
        this.isEditing = false;
        this.selectionEnd = this.selectionStart;
        if (hiddenTextarea) {
          hiddenTextarea.blur && hiddenTextarea.blur();
          hiddenTextarea.parentNode && hiddenTextarea.parentNode.removeChild(hiddenTextarea);
        }
        this.hiddenTextarea = null;
        this.abortCursorAnimation();
        this._restoreEditingProps();
        this._currentCursorOpacity = 0;
        if (this._shouldClearDimensionCache()) {
          this.initDimensions();
          this.setCoords();
        }
        this.fire("editing:exited");
        isTextChanged && this.fire("modified");
        if (this.canvas) {
          this.canvas.off("mouse:move", this.mouseMoveHandler);
          this.canvas.fire("text:editing:exited", { target: this });
          isTextChanged && this.canvas.fire("object:modified", { target: this });
        }
        return this;
      },
      _removeExtraneousStyles: function() {
        for (var prop in this.styles) {
          if (!this._textLines[prop]) {
            delete this.styles[prop];
          }
        }
      },
      removeStyleFromTo: function(start, end) {
        var cursorStart = this.get2DCursorLocation(start, true), cursorEnd = this.get2DCursorLocation(end, true), lineStart = cursorStart.lineIndex, charStart = cursorStart.charIndex, lineEnd = cursorEnd.lineIndex, charEnd = cursorEnd.charIndex, i2, styleObj;
        if (lineStart !== lineEnd) {
          if (this.styles[lineStart]) {
            for (i2 = charStart; i2 < this._unwrappedTextLines[lineStart].length; i2++) {
              delete this.styles[lineStart][i2];
            }
          }
          if (this.styles[lineEnd]) {
            for (i2 = charEnd; i2 < this._unwrappedTextLines[lineEnd].length; i2++) {
              styleObj = this.styles[lineEnd][i2];
              if (styleObj) {
                this.styles[lineStart] || (this.styles[lineStart] = {});
                this.styles[lineStart][charStart + i2 - charEnd] = styleObj;
              }
            }
          }
          for (i2 = lineStart + 1; i2 <= lineEnd; i2++) {
            delete this.styles[i2];
          }
          this.shiftLineStyles(lineEnd, lineStart - lineEnd);
        } else {
          if (this.styles[lineStart]) {
            styleObj = this.styles[lineStart];
            var diff = charEnd - charStart, numericChar, _char;
            for (i2 = charStart; i2 < charEnd; i2++) {
              delete styleObj[i2];
            }
            for (_char in this.styles[lineStart]) {
              numericChar = parseInt(_char, 10);
              if (numericChar >= charEnd) {
                styleObj[numericChar - diff] = styleObj[_char];
                delete styleObj[_char];
              }
            }
          }
        }
      },
      shiftLineStyles: function(lineIndex, offset2) {
        var clonedStyles = clone(this.styles);
        for (var line in this.styles) {
          var numericLine = parseInt(line, 10);
          if (numericLine > lineIndex) {
            this.styles[numericLine + offset2] = clonedStyles[numericLine];
            if (!clonedStyles[numericLine - offset2]) {
              delete this.styles[numericLine];
            }
          }
        }
      },
      restartCursorIfNeeded: function() {
        if (!this._currentTickState || this._currentTickState.isAborted || !this._currentTickCompleteState || this._currentTickCompleteState.isAborted) {
          this.initDelayedCursor();
        }
      },
      insertNewlineStyleObject: function(lineIndex, charIndex, qty, copiedStyle) {
        var currentCharStyle, newLineStyles = {}, somethingAdded = false, isEndOfLine = this._unwrappedTextLines[lineIndex].length === charIndex;
        qty || (qty = 1);
        this.shiftLineStyles(lineIndex, qty);
        if (this.styles[lineIndex]) {
          currentCharStyle = this.styles[lineIndex][charIndex === 0 ? charIndex : charIndex - 1];
        }
        for (var index2 in this.styles[lineIndex]) {
          var numIndex = parseInt(index2, 10);
          if (numIndex >= charIndex) {
            somethingAdded = true;
            newLineStyles[numIndex - charIndex] = this.styles[lineIndex][index2];
            if (!(isEndOfLine && charIndex === 0)) {
              delete this.styles[lineIndex][index2];
            }
          }
        }
        var styleCarriedOver = false;
        if (somethingAdded && !isEndOfLine) {
          this.styles[lineIndex + qty] = newLineStyles;
          styleCarriedOver = true;
        }
        if (styleCarriedOver) {
          qty--;
        }
        while (qty > 0) {
          if (copiedStyle && copiedStyle[qty - 1]) {
            this.styles[lineIndex + qty] = { 0: clone(copiedStyle[qty - 1]) };
          } else if (currentCharStyle) {
            this.styles[lineIndex + qty] = { 0: clone(currentCharStyle) };
          } else {
            delete this.styles[lineIndex + qty];
          }
          qty--;
        }
        this._forceClearCache = true;
      },
      insertCharStyleObject: function(lineIndex, charIndex, quantity, copiedStyle) {
        if (!this.styles) {
          this.styles = {};
        }
        var currentLineStyles = this.styles[lineIndex], currentLineStylesCloned = currentLineStyles ? clone(currentLineStyles) : {};
        quantity || (quantity = 1);
        for (var index2 in currentLineStylesCloned) {
          var numericIndex = parseInt(index2, 10);
          if (numericIndex >= charIndex) {
            currentLineStyles[numericIndex + quantity] = currentLineStylesCloned[numericIndex];
            if (!currentLineStylesCloned[numericIndex - quantity]) {
              delete currentLineStyles[numericIndex];
            }
          }
        }
        this._forceClearCache = true;
        if (copiedStyle) {
          while (quantity--) {
            if (!Object.keys(copiedStyle[quantity]).length) {
              continue;
            }
            if (!this.styles[lineIndex]) {
              this.styles[lineIndex] = {};
            }
            this.styles[lineIndex][charIndex + quantity] = clone(copiedStyle[quantity]);
          }
          return;
        }
        if (!currentLineStyles) {
          return;
        }
        var newStyle = currentLineStyles[charIndex ? charIndex - 1 : 1];
        while (newStyle && quantity--) {
          this.styles[lineIndex][charIndex + quantity] = clone(newStyle);
        }
      },
      insertNewStyleBlock: function(insertedText, start, copiedStyle) {
        var cursorLoc = this.get2DCursorLocation(start, true), addedLines = [0], linesLength = 0;
        for (var i2 = 0; i2 < insertedText.length; i2++) {
          if (insertedText[i2] === "\n") {
            linesLength++;
            addedLines[linesLength] = 0;
          } else {
            addedLines[linesLength]++;
          }
        }
        if (addedLines[0] > 0) {
          this.insertCharStyleObject(cursorLoc.lineIndex, cursorLoc.charIndex, addedLines[0], copiedStyle);
          copiedStyle = copiedStyle && copiedStyle.slice(addedLines[0] + 1);
        }
        linesLength && this.insertNewlineStyleObject(cursorLoc.lineIndex, cursorLoc.charIndex + addedLines[0], linesLength);
        for (var i2 = 1; i2 < linesLength; i2++) {
          if (addedLines[i2] > 0) {
            this.insertCharStyleObject(cursorLoc.lineIndex + i2, 0, addedLines[i2], copiedStyle);
          } else if (copiedStyle) {
            this.styles[cursorLoc.lineIndex + i2][0] = copiedStyle[0];
          }
          copiedStyle = copiedStyle && copiedStyle.slice(addedLines[i2] + 1);
        }
        if (addedLines[i2] > 0) {
          this.insertCharStyleObject(cursorLoc.lineIndex + i2, 0, addedLines[i2], copiedStyle);
        }
      },
      setSelectionStartEndWithShift: function(start, end, newSelection) {
        if (newSelection <= start) {
          if (end === start) {
            this._selectionDirection = "left";
          } else if (this._selectionDirection === "right") {
            this._selectionDirection = "left";
            this.selectionEnd = start;
          }
          this.selectionStart = newSelection;
        } else if (newSelection > start && newSelection < end) {
          if (this._selectionDirection === "right") {
            this.selectionEnd = newSelection;
          } else {
            this.selectionStart = newSelection;
          }
        } else {
          if (end === start) {
            this._selectionDirection = "right";
          } else if (this._selectionDirection === "left") {
            this._selectionDirection = "right";
            this.selectionStart = end;
          }
          this.selectionEnd = newSelection;
        }
      },
      setSelectionInBoundaries: function() {
        var length = this.text.length;
        if (this.selectionStart > length) {
          this.selectionStart = length;
        } else if (this.selectionStart < 0) {
          this.selectionStart = 0;
        }
        if (this.selectionEnd > length) {
          this.selectionEnd = length;
        } else if (this.selectionEnd < 0) {
          this.selectionEnd = 0;
        }
      }
    });
  })();
  fabric2.util.object.extend(fabric2.IText.prototype, {
    initDoubleClickSimulation: function() {
      this.__lastClickTime = +new Date();
      this.__lastLastClickTime = +new Date();
      this.__lastPointer = {};
      this.on("mousedown", this.onMouseDown);
    },
    onMouseDown: function(options) {
      if (!this.canvas) {
        return;
      }
      this.__newClickTime = +new Date();
      var newPointer = options.pointer;
      if (this.isTripleClick(newPointer)) {
        this.fire("tripleclick", options);
        this._stopEvent(options.e);
      }
      this.__lastLastClickTime = this.__lastClickTime;
      this.__lastClickTime = this.__newClickTime;
      this.__lastPointer = newPointer;
      this.__lastIsEditing = this.isEditing;
      this.__lastSelected = this.selected;
    },
    isTripleClick: function(newPointer) {
      return this.__newClickTime - this.__lastClickTime < 500 && this.__lastClickTime - this.__lastLastClickTime < 500 && this.__lastPointer.x === newPointer.x && this.__lastPointer.y === newPointer.y;
    },
    _stopEvent: function(e2) {
      e2.preventDefault && e2.preventDefault();
      e2.stopPropagation && e2.stopPropagation();
    },
    initCursorSelectionHandlers: function() {
      this.initMousedownHandler();
      this.initMouseupHandler();
      this.initClicks();
    },
    doubleClickHandler: function(options) {
      if (!this.isEditing) {
        return;
      }
      this.selectWord(this.getSelectionStartFromPointer(options.e));
    },
    tripleClickHandler: function(options) {
      if (!this.isEditing) {
        return;
      }
      this.selectLine(this.getSelectionStartFromPointer(options.e));
    },
    initClicks: function() {
      this.on("mousedblclick", this.doubleClickHandler);
      this.on("tripleclick", this.tripleClickHandler);
    },
    _mouseDownHandler: function(options) {
      if (!this.canvas || !this.editable || options.e.button && options.e.button !== 1) {
        return;
      }
      this.__isMousedown = true;
      if (this.selected) {
        this.inCompositionMode = false;
        this.setCursorByClick(options.e);
      }
      if (this.isEditing) {
        this.__selectionStartOnMouseDown = this.selectionStart;
        if (this.selectionStart === this.selectionEnd) {
          this.abortCursorAnimation();
        }
        this.renderCursorOrSelection();
      }
    },
    _mouseDownHandlerBefore: function(options) {
      if (!this.canvas || !this.editable || options.e.button && options.e.button !== 1) {
        return;
      }
      this.selected = this === this.canvas._activeObject;
    },
    initMousedownHandler: function() {
      this.on("mousedown", this._mouseDownHandler);
      this.on("mousedown:before", this._mouseDownHandlerBefore);
    },
    initMouseupHandler: function() {
      this.on("mouseup", this.mouseUpHandler);
    },
    mouseUpHandler: function(options) {
      this.__isMousedown = false;
      if (!this.editable || this.group || options.transform && options.transform.actionPerformed || options.e.button && options.e.button !== 1) {
        return;
      }
      if (this.canvas) {
        var currentActive = this.canvas._activeObject;
        if (currentActive && currentActive !== this) {
          return;
        }
      }
      if (this.__lastSelected && !this.__corner) {
        this.selected = false;
        this.__lastSelected = false;
        this.enterEditing(options.e);
        if (this.selectionStart === this.selectionEnd) {
          this.initDelayedCursor(true);
        } else {
          this.renderCursorOrSelection();
        }
      } else {
        this.selected = true;
      }
    },
    setCursorByClick: function(e2) {
      var newSelection = this.getSelectionStartFromPointer(e2), start = this.selectionStart, end = this.selectionEnd;
      if (e2.shiftKey) {
        this.setSelectionStartEndWithShift(start, end, newSelection);
      } else {
        this.selectionStart = newSelection;
        this.selectionEnd = newSelection;
      }
      if (this.isEditing) {
        this._fireSelectionChanged();
        this._updateTextarea();
      }
    },
    getSelectionStartFromPointer: function(e2) {
      var mouseOffset = this.getLocalPointer(e2), prevWidth = 0, width = 0, height = 0, charIndex = 0, lineIndex = 0, lineLeftOffset, line;
      for (var i2 = 0, len = this._textLines.length; i2 < len; i2++) {
        if (height <= mouseOffset.y) {
          height += this.getHeightOfLine(i2) * this.scaleY;
          lineIndex = i2;
          if (i2 > 0) {
            charIndex += this._textLines[i2 - 1].length + this.missingNewlineOffset(i2 - 1);
          }
        } else {
          break;
        }
      }
      lineLeftOffset = this._getLineLeftOffset(lineIndex);
      width = lineLeftOffset * this.scaleX;
      line = this._textLines[lineIndex];
      if (this.direction === "rtl") {
        mouseOffset.x = this.width * this.scaleX - mouseOffset.x + width;
      }
      for (var j2 = 0, jlen = line.length; j2 < jlen; j2++) {
        prevWidth = width;
        width += this.__charBounds[lineIndex][j2].kernedWidth * this.scaleX;
        if (width <= mouseOffset.x) {
          charIndex++;
        } else {
          break;
        }
      }
      return this._getNewSelectionStartFromOffset(mouseOffset, prevWidth, width, charIndex, jlen);
    },
    _getNewSelectionStartFromOffset: function(mouseOffset, prevWidth, width, index2, jlen) {
      var distanceBtwLastCharAndCursor = mouseOffset.x - prevWidth, distanceBtwNextCharAndCursor = width - mouseOffset.x, offset2 = distanceBtwNextCharAndCursor > distanceBtwLastCharAndCursor || distanceBtwNextCharAndCursor < 0 ? 0 : 1, newSelectionStart = index2 + offset2;
      if (this.flipX) {
        newSelectionStart = jlen - newSelectionStart;
      }
      if (newSelectionStart > this._text.length) {
        newSelectionStart = this._text.length;
      }
      return newSelectionStart;
    }
  });
  fabric2.util.object.extend(fabric2.IText.prototype, {
    initHiddenTextarea: function() {
      this.hiddenTextarea = fabric2.document.createElement("textarea");
      this.hiddenTextarea.setAttribute("autocapitalize", "off");
      this.hiddenTextarea.setAttribute("autocorrect", "off");
      this.hiddenTextarea.setAttribute("autocomplete", "off");
      this.hiddenTextarea.setAttribute("spellcheck", "false");
      this.hiddenTextarea.setAttribute("data-fabric-hiddentextarea", "");
      this.hiddenTextarea.setAttribute("wrap", "off");
      var style2 = this._calcTextareaPosition();
      this.hiddenTextarea.style.cssText = "position: absolute; top: " + style2.top + "; left: " + style2.left + "; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; padding\uFF70top: " + style2.fontSize + ";";
      if (this.hiddenTextareaContainer) {
        this.hiddenTextareaContainer.appendChild(this.hiddenTextarea);
      } else {
        fabric2.document.body.appendChild(this.hiddenTextarea);
      }
      fabric2.util.addListener(this.hiddenTextarea, "keydown", this.onKeyDown.bind(this));
      fabric2.util.addListener(this.hiddenTextarea, "keyup", this.onKeyUp.bind(this));
      fabric2.util.addListener(this.hiddenTextarea, "input", this.onInput.bind(this));
      fabric2.util.addListener(this.hiddenTextarea, "copy", this.copy.bind(this));
      fabric2.util.addListener(this.hiddenTextarea, "cut", this.copy.bind(this));
      fabric2.util.addListener(this.hiddenTextarea, "paste", this.paste.bind(this));
      fabric2.util.addListener(this.hiddenTextarea, "compositionstart", this.onCompositionStart.bind(this));
      fabric2.util.addListener(this.hiddenTextarea, "compositionupdate", this.onCompositionUpdate.bind(this));
      fabric2.util.addListener(this.hiddenTextarea, "compositionend", this.onCompositionEnd.bind(this));
      if (!this._clickHandlerInitialized && this.canvas) {
        fabric2.util.addListener(this.canvas.upperCanvasEl, "click", this.onClick.bind(this));
        this._clickHandlerInitialized = true;
      }
    },
    keysMap: {
      9: "exitEditing",
      27: "exitEditing",
      33: "moveCursorUp",
      34: "moveCursorDown",
      35: "moveCursorRight",
      36: "moveCursorLeft",
      37: "moveCursorLeft",
      38: "moveCursorUp",
      39: "moveCursorRight",
      40: "moveCursorDown"
    },
    keysMapRtl: {
      9: "exitEditing",
      27: "exitEditing",
      33: "moveCursorUp",
      34: "moveCursorDown",
      35: "moveCursorLeft",
      36: "moveCursorRight",
      37: "moveCursorRight",
      38: "moveCursorUp",
      39: "moveCursorLeft",
      40: "moveCursorDown"
    },
    ctrlKeysMapUp: {
      67: "copy",
      88: "cut"
    },
    ctrlKeysMapDown: {
      65: "selectAll"
    },
    onClick: function() {
      this.hiddenTextarea && this.hiddenTextarea.focus();
    },
    onKeyDown: function(e2) {
      if (!this.isEditing) {
        return;
      }
      var keyMap = this.direction === "rtl" ? this.keysMapRtl : this.keysMap;
      if (e2.keyCode in keyMap) {
        this[keyMap[e2.keyCode]](e2);
      } else if (e2.keyCode in this.ctrlKeysMapDown && (e2.ctrlKey || e2.metaKey)) {
        this[this.ctrlKeysMapDown[e2.keyCode]](e2);
      } else {
        return;
      }
      e2.stopImmediatePropagation();
      e2.preventDefault();
      if (e2.keyCode >= 33 && e2.keyCode <= 40) {
        this.inCompositionMode = false;
        this.clearContextTop();
        this.renderCursorOrSelection();
      } else {
        this.canvas && this.canvas.requestRenderAll();
      }
    },
    onKeyUp: function(e2) {
      if (!this.isEditing || this._copyDone || this.inCompositionMode) {
        this._copyDone = false;
        return;
      }
      if (e2.keyCode in this.ctrlKeysMapUp && (e2.ctrlKey || e2.metaKey)) {
        this[this.ctrlKeysMapUp[e2.keyCode]](e2);
      } else {
        return;
      }
      e2.stopImmediatePropagation();
      e2.preventDefault();
      this.canvas && this.canvas.requestRenderAll();
    },
    onInput: function(e2) {
      var fromPaste = this.fromPaste;
      this.fromPaste = false;
      e2 && e2.stopPropagation();
      if (!this.isEditing) {
        return;
      }
      var nextText = this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText, charCount = this._text.length, nextCharCount = nextText.length, removedText, insertedText, charDiff = nextCharCount - charCount, selectionStart = this.selectionStart, selectionEnd = this.selectionEnd, selection = selectionStart !== selectionEnd, copiedStyle, removeFrom, removeTo;
      if (this.hiddenTextarea.value === "") {
        this.styles = {};
        this.updateFromTextArea();
        this.fire("changed");
        if (this.canvas) {
          this.canvas.fire("text:changed", { target: this });
          this.canvas.requestRenderAll();
        }
        return;
      }
      var textareaSelection = this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart, this.hiddenTextarea.selectionEnd, this.hiddenTextarea.value);
      var backDelete = selectionStart > textareaSelection.selectionStart;
      if (selection) {
        removedText = this._text.slice(selectionStart, selectionEnd);
        charDiff += selectionEnd - selectionStart;
      } else if (nextCharCount < charCount) {
        if (backDelete) {
          removedText = this._text.slice(selectionEnd + charDiff, selectionEnd);
        } else {
          removedText = this._text.slice(selectionStart, selectionStart - charDiff);
        }
      }
      insertedText = nextText.slice(textareaSelection.selectionEnd - charDiff, textareaSelection.selectionEnd);
      if (removedText && removedText.length) {
        if (insertedText.length) {
          copiedStyle = this.getSelectionStyles(selectionStart, selectionStart + 1, false);
          copiedStyle = insertedText.map(function() {
            return copiedStyle[0];
          });
        }
        if (selection) {
          removeFrom = selectionStart;
          removeTo = selectionEnd;
        } else if (backDelete) {
          removeFrom = selectionEnd - removedText.length;
          removeTo = selectionEnd;
        } else {
          removeFrom = selectionEnd;
          removeTo = selectionEnd + removedText.length;
        }
        this.removeStyleFromTo(removeFrom, removeTo);
      }
      if (insertedText.length) {
        if (fromPaste && insertedText.join("") === fabric2.copiedText && !fabric2.disableStyleCopyPaste) {
          copiedStyle = fabric2.copiedTextStyle;
        }
        this.insertNewStyleBlock(insertedText, selectionStart, copiedStyle);
      }
      this.updateFromTextArea();
      this.fire("changed");
      if (this.canvas) {
        this.canvas.fire("text:changed", { target: this });
        this.canvas.requestRenderAll();
      }
    },
    onCompositionStart: function() {
      this.inCompositionMode = true;
    },
    onCompositionEnd: function() {
      this.inCompositionMode = false;
    },
    onCompositionUpdate: function(e2) {
      this.compositionStart = e2.target.selectionStart;
      this.compositionEnd = e2.target.selectionEnd;
      this.updateTextareaPosition();
    },
    copy: function() {
      if (this.selectionStart === this.selectionEnd) {
        return;
      }
      fabric2.copiedText = this.getSelectedText();
      if (!fabric2.disableStyleCopyPaste) {
        fabric2.copiedTextStyle = this.getSelectionStyles(this.selectionStart, this.selectionEnd, true);
      } else {
        fabric2.copiedTextStyle = null;
      }
      this._copyDone = true;
    },
    paste: function() {
      this.fromPaste = true;
    },
    _getClipboardData: function(e2) {
      return e2 && e2.clipboardData || fabric2.window.clipboardData;
    },
    _getWidthBeforeCursor: function(lineIndex, charIndex) {
      var widthBeforeCursor = this._getLineLeftOffset(lineIndex), bound;
      if (charIndex > 0) {
        bound = this.__charBounds[lineIndex][charIndex - 1];
        widthBeforeCursor += bound.left + bound.width;
      }
      return widthBeforeCursor;
    },
    getDownCursorOffset: function(e2, isRight) {
      var selectionProp = this._getSelectionForOffset(e2, isRight), cursorLocation = this.get2DCursorLocation(selectionProp), lineIndex = cursorLocation.lineIndex;
      if (lineIndex === this._textLines.length - 1 || e2.metaKey || e2.keyCode === 34) {
        return this._text.length - selectionProp;
      }
      var charIndex = cursorLocation.charIndex, widthBeforeCursor = this._getWidthBeforeCursor(lineIndex, charIndex), indexOnOtherLine = this._getIndexOnLine(lineIndex + 1, widthBeforeCursor), textAfterCursor = this._textLines[lineIndex].slice(charIndex);
      return textAfterCursor.length + indexOnOtherLine + 1 + this.missingNewlineOffset(lineIndex);
    },
    _getSelectionForOffset: function(e2, isRight) {
      if (e2.shiftKey && this.selectionStart !== this.selectionEnd && isRight) {
        return this.selectionEnd;
      } else {
        return this.selectionStart;
      }
    },
    getUpCursorOffset: function(e2, isRight) {
      var selectionProp = this._getSelectionForOffset(e2, isRight), cursorLocation = this.get2DCursorLocation(selectionProp), lineIndex = cursorLocation.lineIndex;
      if (lineIndex === 0 || e2.metaKey || e2.keyCode === 33) {
        return -selectionProp;
      }
      var charIndex = cursorLocation.charIndex, widthBeforeCursor = this._getWidthBeforeCursor(lineIndex, charIndex), indexOnOtherLine = this._getIndexOnLine(lineIndex - 1, widthBeforeCursor), textBeforeCursor = this._textLines[lineIndex].slice(0, charIndex), missingNewlineOffset = this.missingNewlineOffset(lineIndex - 1);
      return -this._textLines[lineIndex - 1].length + indexOnOtherLine - textBeforeCursor.length + (1 - missingNewlineOffset);
    },
    _getIndexOnLine: function(lineIndex, width) {
      var line = this._textLines[lineIndex], lineLeftOffset = this._getLineLeftOffset(lineIndex), widthOfCharsOnLine = lineLeftOffset, indexOnLine = 0, charWidth, foundMatch;
      for (var j2 = 0, jlen = line.length; j2 < jlen; j2++) {
        charWidth = this.__charBounds[lineIndex][j2].width;
        widthOfCharsOnLine += charWidth;
        if (widthOfCharsOnLine > width) {
          foundMatch = true;
          var leftEdge = widthOfCharsOnLine - charWidth, rightEdge = widthOfCharsOnLine, offsetFromLeftEdge = Math.abs(leftEdge - width), offsetFromRightEdge = Math.abs(rightEdge - width);
          indexOnLine = offsetFromRightEdge < offsetFromLeftEdge ? j2 : j2 - 1;
          break;
        }
      }
      if (!foundMatch) {
        indexOnLine = line.length - 1;
      }
      return indexOnLine;
    },
    moveCursorDown: function(e2) {
      if (this.selectionStart >= this._text.length && this.selectionEnd >= this._text.length) {
        return;
      }
      this._moveCursorUpOrDown("Down", e2);
    },
    moveCursorUp: function(e2) {
      if (this.selectionStart === 0 && this.selectionEnd === 0) {
        return;
      }
      this._moveCursorUpOrDown("Up", e2);
    },
    _moveCursorUpOrDown: function(direction, e2) {
      var action = "get" + direction + "CursorOffset", offset2 = this[action](e2, this._selectionDirection === "right");
      if (e2.shiftKey) {
        this.moveCursorWithShift(offset2);
      } else {
        this.moveCursorWithoutShift(offset2);
      }
      if (offset2 !== 0) {
        this.setSelectionInBoundaries();
        this.abortCursorAnimation();
        this._currentCursorOpacity = 1;
        this.initDelayedCursor();
        this._fireSelectionChanged();
        this._updateTextarea();
      }
    },
    moveCursorWithShift: function(offset2) {
      var newSelection = this._selectionDirection === "left" ? this.selectionStart + offset2 : this.selectionEnd + offset2;
      this.setSelectionStartEndWithShift(this.selectionStart, this.selectionEnd, newSelection);
      return offset2 !== 0;
    },
    moveCursorWithoutShift: function(offset2) {
      if (offset2 < 0) {
        this.selectionStart += offset2;
        this.selectionEnd = this.selectionStart;
      } else {
        this.selectionEnd += offset2;
        this.selectionStart = this.selectionEnd;
      }
      return offset2 !== 0;
    },
    moveCursorLeft: function(e2) {
      if (this.selectionStart === 0 && this.selectionEnd === 0) {
        return;
      }
      this._moveCursorLeftOrRight("Left", e2);
    },
    _move: function(e2, prop, direction) {
      var newValue;
      if (e2.altKey) {
        newValue = this["findWordBoundary" + direction](this[prop]);
      } else if (e2.metaKey || e2.keyCode === 35 || e2.keyCode === 36) {
        newValue = this["findLineBoundary" + direction](this[prop]);
      } else {
        this[prop] += direction === "Left" ? -1 : 1;
        return true;
      }
      if (typeof newValue !== void 0 && this[prop] !== newValue) {
        this[prop] = newValue;
        return true;
      }
    },
    _moveLeft: function(e2, prop) {
      return this._move(e2, prop, "Left");
    },
    _moveRight: function(e2, prop) {
      return this._move(e2, prop, "Right");
    },
    moveCursorLeftWithoutShift: function(e2) {
      var change = true;
      this._selectionDirection = "left";
      if (this.selectionEnd === this.selectionStart && this.selectionStart !== 0) {
        change = this._moveLeft(e2, "selectionStart");
      }
      this.selectionEnd = this.selectionStart;
      return change;
    },
    moveCursorLeftWithShift: function(e2) {
      if (this._selectionDirection === "right" && this.selectionStart !== this.selectionEnd) {
        return this._moveLeft(e2, "selectionEnd");
      } else if (this.selectionStart !== 0) {
        this._selectionDirection = "left";
        return this._moveLeft(e2, "selectionStart");
      }
    },
    moveCursorRight: function(e2) {
      if (this.selectionStart >= this._text.length && this.selectionEnd >= this._text.length) {
        return;
      }
      this._moveCursorLeftOrRight("Right", e2);
    },
    _moveCursorLeftOrRight: function(direction, e2) {
      var actionName = "moveCursor" + direction + "With";
      this._currentCursorOpacity = 1;
      if (e2.shiftKey) {
        actionName += "Shift";
      } else {
        actionName += "outShift";
      }
      if (this[actionName](e2)) {
        this.abortCursorAnimation();
        this.initDelayedCursor();
        this._fireSelectionChanged();
        this._updateTextarea();
      }
    },
    moveCursorRightWithShift: function(e2) {
      if (this._selectionDirection === "left" && this.selectionStart !== this.selectionEnd) {
        return this._moveRight(e2, "selectionStart");
      } else if (this.selectionEnd !== this._text.length) {
        this._selectionDirection = "right";
        return this._moveRight(e2, "selectionEnd");
      }
    },
    moveCursorRightWithoutShift: function(e2) {
      var changed = true;
      this._selectionDirection = "right";
      if (this.selectionStart === this.selectionEnd) {
        changed = this._moveRight(e2, "selectionStart");
        this.selectionEnd = this.selectionStart;
      } else {
        this.selectionStart = this.selectionEnd;
      }
      return changed;
    },
    removeChars: function(start, end) {
      if (typeof end === "undefined") {
        end = start + 1;
      }
      this.removeStyleFromTo(start, end);
      this._text.splice(start, end - start);
      this.text = this._text.join("");
      this.set("dirty", true);
      if (this._shouldClearDimensionCache()) {
        this.initDimensions();
        this.setCoords();
      }
      this._removeExtraneousStyles();
    },
    insertChars: function(text2, style2, start, end) {
      if (typeof end === "undefined") {
        end = start;
      }
      if (end > start) {
        this.removeStyleFromTo(start, end);
      }
      var graphemes = fabric2.util.string.graphemeSplit(text2);
      this.insertNewStyleBlock(graphemes, start, style2);
      this._text = [].concat(this._text.slice(0, start), graphemes, this._text.slice(end));
      this.text = this._text.join("");
      this.set("dirty", true);
      if (this._shouldClearDimensionCache()) {
        this.initDimensions();
        this.setCoords();
      }
      this._removeExtraneousStyles();
    }
  });
  (function() {
    var toFixed = fabric2.util.toFixed, multipleSpacesRegex = /  +/g;
    fabric2.util.object.extend(fabric2.Text.prototype, {
      _toSVG: function() {
        var offsets = this._getSVGLeftTopOffsets(), textAndBg = this._getSVGTextAndBg(offsets.textTop, offsets.textLeft);
        return this._wrapSVGTextAndBg(textAndBg);
      },
      toSVG: function(reviver) {
        return this._createBaseSVGMarkup(this._toSVG(), { reviver, noStyle: true, withShadow: true });
      },
      _getSVGLeftTopOffsets: function() {
        return {
          textLeft: -this.width / 2,
          textTop: -this.height / 2,
          lineTop: this.getHeightOfLine(0)
        };
      },
      _wrapSVGTextAndBg: function(textAndBg) {
        var noShadow = true, textDecoration = this.getSvgTextDecoration(this);
        return [
          textAndBg.textBgRects.join(""),
          '		<text xml:space="preserve" ',
          this.fontFamily ? 'font-family="' + this.fontFamily.replace(/"/g, "'") + '" ' : "",
          this.fontSize ? 'font-size="' + this.fontSize + '" ' : "",
          this.fontStyle ? 'font-style="' + this.fontStyle + '" ' : "",
          this.fontWeight ? 'font-weight="' + this.fontWeight + '" ' : "",
          textDecoration ? 'text-decoration="' + textDecoration + '" ' : "",
          'style="',
          this.getSvgStyles(noShadow),
          '"',
          this.addPaintOrder(),
          " >",
          textAndBg.textSpans.join(""),
          "</text>\n"
        ];
      },
      _getSVGTextAndBg: function(textTopOffset, textLeftOffset) {
        var textSpans = [], textBgRects = [], height = textTopOffset, lineOffset;
        this._setSVGBg(textBgRects);
        for (var i2 = 0, len = this._textLines.length; i2 < len; i2++) {
          lineOffset = this._getLineLeftOffset(i2);
          if (this.textBackgroundColor || this.styleHas("textBackgroundColor", i2)) {
            this._setSVGTextLineBg(textBgRects, i2, textLeftOffset + lineOffset, height);
          }
          this._setSVGTextLineText(textSpans, i2, textLeftOffset + lineOffset, height);
          height += this.getHeightOfLine(i2);
        }
        return {
          textSpans,
          textBgRects
        };
      },
      _createTextCharSpan: function(_char, styleDecl, left, top) {
        var shouldUseWhitespace = _char !== _char.trim() || _char.match(multipleSpacesRegex), styleProps = this.getSvgSpanStyles(styleDecl, shouldUseWhitespace), fillStyles = styleProps ? 'style="' + styleProps + '"' : "", dy = styleDecl.deltaY, dySpan = "", NUM_FRACTION_DIGITS = fabric2.Object.NUM_FRACTION_DIGITS;
        if (dy) {
          dySpan = ' dy="' + toFixed(dy, NUM_FRACTION_DIGITS) + '" ';
        }
        return [
          '<tspan x="',
          toFixed(left, NUM_FRACTION_DIGITS),
          '" y="',
          toFixed(top, NUM_FRACTION_DIGITS),
          '" ',
          dySpan,
          fillStyles,
          ">",
          fabric2.util.string.escapeXml(_char),
          "</tspan>"
        ].join("");
      },
      _setSVGTextLineText: function(textSpans, lineIndex, textLeftOffset, textTopOffset) {
        var lineHeight = this.getHeightOfLine(lineIndex), isJustify = this.textAlign.indexOf("justify") !== -1, actualStyle, nextStyle, charsToRender = "", charBox, style2, boxWidth = 0, line = this._textLines[lineIndex], timeToRender;
        textTopOffset += lineHeight * (1 - this._fontSizeFraction) / this.lineHeight;
        for (var i2 = 0, len = line.length - 1; i2 <= len; i2++) {
          timeToRender = i2 === len || this.charSpacing;
          charsToRender += line[i2];
          charBox = this.__charBounds[lineIndex][i2];
          if (boxWidth === 0) {
            textLeftOffset += charBox.kernedWidth - charBox.width;
            boxWidth += charBox.width;
          } else {
            boxWidth += charBox.kernedWidth;
          }
          if (isJustify && !timeToRender) {
            if (this._reSpaceAndTab.test(line[i2])) {
              timeToRender = true;
            }
          }
          if (!timeToRender) {
            actualStyle = actualStyle || this.getCompleteStyleDeclaration(lineIndex, i2);
            nextStyle = this.getCompleteStyleDeclaration(lineIndex, i2 + 1);
            timeToRender = this._hasStyleChangedForSvg(actualStyle, nextStyle);
          }
          if (timeToRender) {
            style2 = this._getStyleDeclaration(lineIndex, i2) || {};
            textSpans.push(this._createTextCharSpan(charsToRender, style2, textLeftOffset, textTopOffset));
            charsToRender = "";
            actualStyle = nextStyle;
            textLeftOffset += boxWidth;
            boxWidth = 0;
          }
        }
      },
      _pushTextBgRect: function(textBgRects, color2, left, top, width, height) {
        var NUM_FRACTION_DIGITS = fabric2.Object.NUM_FRACTION_DIGITS;
        textBgRects.push("		<rect ", this._getFillAttributes(color2), ' x="', toFixed(left, NUM_FRACTION_DIGITS), '" y="', toFixed(top, NUM_FRACTION_DIGITS), '" width="', toFixed(width, NUM_FRACTION_DIGITS), '" height="', toFixed(height, NUM_FRACTION_DIGITS), '"></rect>\n');
      },
      _setSVGTextLineBg: function(textBgRects, i2, leftOffset, textTopOffset) {
        var line = this._textLines[i2], heightOfLine = this.getHeightOfLine(i2) / this.lineHeight, boxWidth = 0, boxStart = 0, charBox, currentColor, lastColor = this.getValueOfPropertyAt(i2, 0, "textBackgroundColor");
        for (var j2 = 0, jlen = line.length; j2 < jlen; j2++) {
          charBox = this.__charBounds[i2][j2];
          currentColor = this.getValueOfPropertyAt(i2, j2, "textBackgroundColor");
          if (currentColor !== lastColor) {
            lastColor && this._pushTextBgRect(textBgRects, lastColor, leftOffset + boxStart, textTopOffset, boxWidth, heightOfLine);
            boxStart = charBox.left;
            boxWidth = charBox.width;
            lastColor = currentColor;
          } else {
            boxWidth += charBox.kernedWidth;
          }
        }
        currentColor && this._pushTextBgRect(textBgRects, currentColor, leftOffset + boxStart, textTopOffset, boxWidth, heightOfLine);
      },
      _getFillAttributes: function(value) {
        var fillColor = value && typeof value === "string" ? new fabric2.Color(value) : "";
        if (!fillColor || !fillColor.getSource() || fillColor.getAlpha() === 1) {
          return 'fill="' + value + '"';
        }
        return 'opacity="' + fillColor.getAlpha() + '" fill="' + fillColor.setAlpha(1).toRgb() + '"';
      },
      _getSVGLineTopOffset: function(lineIndex) {
        var lineTopOffset = 0, lastHeight = 0;
        for (var j2 = 0; j2 < lineIndex; j2++) {
          lineTopOffset += this.getHeightOfLine(j2);
        }
        lastHeight = this.getHeightOfLine(j2);
        return {
          lineTop: lineTopOffset,
          offset: (this._fontSizeMult - this._fontSizeFraction) * lastHeight / (this.lineHeight * this._fontSizeMult)
        };
      },
      getSvgStyles: function(skipShadow) {
        var svgStyle = fabric2.Object.prototype.getSvgStyles.call(this, skipShadow);
        return svgStyle + " white-space: pre;";
      }
    });
  })();
  (function(global2) {
    var fabric3 = global2.fabric || (global2.fabric = {});
    fabric3.Textbox = fabric3.util.createClass(fabric3.IText, fabric3.Observable, {
      type: "textbox",
      minWidth: 20,
      dynamicMinWidth: 2,
      __cachedLines: null,
      lockScalingFlip: true,
      noScaleCache: false,
      _dimensionAffectingProps: fabric3.Text.prototype._dimensionAffectingProps.concat("width"),
      _wordJoiners: /[ \t\r]/,
      splitByGrapheme: false,
      initDimensions: function() {
        if (this.__skipDimension) {
          return;
        }
        this.isEditing && this.initDelayedCursor();
        this.clearContextTop();
        this._clearCache();
        this.dynamicMinWidth = 0;
        this._styleMap = this._generateStyleMap(this._splitText());
        if (this.dynamicMinWidth > this.width) {
          this._set("width", this.dynamicMinWidth);
        }
        if (this.textAlign.indexOf("justify") !== -1) {
          this.enlargeSpaces();
        }
        this.height = this.calcTextHeight();
        this.saveState({ propertySet: "_dimensionAffectingProps" });
      },
      _generateStyleMap: function(textInfo) {
        var realLineCount = 0, realLineCharCount = 0, charCount = 0, map = {};
        for (var i2 = 0; i2 < textInfo.graphemeLines.length; i2++) {
          if (textInfo.graphemeText[charCount] === "\n" && i2 > 0) {
            realLineCharCount = 0;
            charCount++;
            realLineCount++;
          } else if (!this.splitByGrapheme && this._reSpaceAndTab.test(textInfo.graphemeText[charCount]) && i2 > 0) {
            realLineCharCount++;
            charCount++;
          }
          map[i2] = { line: realLineCount, offset: realLineCharCount };
          charCount += textInfo.graphemeLines[i2].length;
          realLineCharCount += textInfo.graphemeLines[i2].length;
        }
        return map;
      },
      styleHas: function(property, lineIndex) {
        if (this._styleMap && !this.isWrapping) {
          var map = this._styleMap[lineIndex];
          if (map) {
            lineIndex = map.line;
          }
        }
        return fabric3.Text.prototype.styleHas.call(this, property, lineIndex);
      },
      isEmptyStyles: function(lineIndex) {
        if (!this.styles) {
          return true;
        }
        var offset2 = 0, nextLineIndex = lineIndex + 1, nextOffset, obj, shouldLimit = false, map = this._styleMap[lineIndex], mapNextLine = this._styleMap[lineIndex + 1];
        if (map) {
          lineIndex = map.line;
          offset2 = map.offset;
        }
        if (mapNextLine) {
          nextLineIndex = mapNextLine.line;
          shouldLimit = nextLineIndex === lineIndex;
          nextOffset = mapNextLine.offset;
        }
        obj = typeof lineIndex === "undefined" ? this.styles : { line: this.styles[lineIndex] };
        for (var p1 in obj) {
          for (var p2 in obj[p1]) {
            if (p2 >= offset2 && (!shouldLimit || p2 < nextOffset)) {
              for (var p3 in obj[p1][p2]) {
                return false;
              }
            }
          }
        }
        return true;
      },
      _getStyleDeclaration: function(lineIndex, charIndex) {
        if (this._styleMap && !this.isWrapping) {
          var map = this._styleMap[lineIndex];
          if (!map) {
            return null;
          }
          lineIndex = map.line;
          charIndex = map.offset + charIndex;
        }
        return this.callSuper("_getStyleDeclaration", lineIndex, charIndex);
      },
      _setStyleDeclaration: function(lineIndex, charIndex, style2) {
        var map = this._styleMap[lineIndex];
        lineIndex = map.line;
        charIndex = map.offset + charIndex;
        this.styles[lineIndex][charIndex] = style2;
      },
      _deleteStyleDeclaration: function(lineIndex, charIndex) {
        var map = this._styleMap[lineIndex];
        lineIndex = map.line;
        charIndex = map.offset + charIndex;
        delete this.styles[lineIndex][charIndex];
      },
      _getLineStyle: function(lineIndex) {
        var map = this._styleMap[lineIndex];
        return !!this.styles[map.line];
      },
      _setLineStyle: function(lineIndex) {
        var map = this._styleMap[lineIndex];
        this.styles[map.line] = {};
      },
      _wrapText: function(lines, desiredWidth) {
        var wrapped = [], i2;
        this.isWrapping = true;
        for (i2 = 0; i2 < lines.length; i2++) {
          wrapped = wrapped.concat(this._wrapLine(lines[i2], i2, desiredWidth));
        }
        this.isWrapping = false;
        return wrapped;
      },
      _measureWord: function(word, lineIndex, charOffset) {
        var width = 0, prevGrapheme, skipLeft = true;
        charOffset = charOffset || 0;
        for (var i2 = 0, len = word.length; i2 < len; i2++) {
          var box = this._getGraphemeBox(word[i2], lineIndex, i2 + charOffset, prevGrapheme, skipLeft);
          width += box.kernedWidth;
          prevGrapheme = word[i2];
        }
        return width;
      },
      _wrapLine: function(_line, lineIndex, desiredWidth, reservedSpace) {
        var lineWidth = 0, splitByGrapheme = this.splitByGrapheme, graphemeLines = [], line = [], words = splitByGrapheme ? fabric3.util.string.graphemeSplit(_line) : _line.split(this._wordJoiners), word = "", offset2 = 0, infix = splitByGrapheme ? "" : " ", wordWidth = 0, infixWidth = 0, largestWordWidth = 0, lineJustStarted = true, additionalSpace = this._getWidthOfCharSpacing(), reservedSpace = reservedSpace || 0;
        if (words.length === 0) {
          words.push([]);
        }
        desiredWidth -= reservedSpace;
        for (var i2 = 0; i2 < words.length; i2++) {
          word = splitByGrapheme ? words[i2] : fabric3.util.string.graphemeSplit(words[i2]);
          wordWidth = this._measureWord(word, lineIndex, offset2);
          offset2 += word.length;
          lineWidth += infixWidth + wordWidth - additionalSpace;
          if (lineWidth > desiredWidth && !lineJustStarted) {
            graphemeLines.push(line);
            line = [];
            lineWidth = wordWidth;
            lineJustStarted = true;
          } else {
            lineWidth += additionalSpace;
          }
          if (!lineJustStarted && !splitByGrapheme) {
            line.push(infix);
          }
          line = line.concat(word);
          infixWidth = splitByGrapheme ? 0 : this._measureWord([infix], lineIndex, offset2);
          offset2++;
          lineJustStarted = false;
          if (wordWidth > largestWordWidth) {
            largestWordWidth = wordWidth;
          }
        }
        i2 && graphemeLines.push(line);
        if (largestWordWidth + reservedSpace > this.dynamicMinWidth) {
          this.dynamicMinWidth = largestWordWidth - additionalSpace + reservedSpace;
        }
        return graphemeLines;
      },
      isEndOfWrapping: function(lineIndex) {
        if (!this._styleMap[lineIndex + 1]) {
          return true;
        }
        if (this._styleMap[lineIndex + 1].line !== this._styleMap[lineIndex].line) {
          return true;
        }
        return false;
      },
      missingNewlineOffset: function(lineIndex) {
        if (this.splitByGrapheme) {
          return this.isEndOfWrapping(lineIndex) ? 1 : 0;
        }
        return 1;
      },
      _splitTextIntoLines: function(text2) {
        var newText = fabric3.Text.prototype._splitTextIntoLines.call(this, text2), graphemeLines = this._wrapText(newText.lines, this.width), lines = new Array(graphemeLines.length);
        for (var i2 = 0; i2 < graphemeLines.length; i2++) {
          lines[i2] = graphemeLines[i2].join("");
        }
        newText.lines = lines;
        newText.graphemeLines = graphemeLines;
        return newText;
      },
      getMinWidth: function() {
        return Math.max(this.minWidth, this.dynamicMinWidth);
      },
      _removeExtraneousStyles: function() {
        var linesToKeep = {};
        for (var prop in this._styleMap) {
          if (this._textLines[prop]) {
            linesToKeep[this._styleMap[prop].line] = 1;
          }
        }
        for (var prop in this.styles) {
          if (!linesToKeep[prop]) {
            delete this.styles[prop];
          }
        }
      },
      toObject: function(propertiesToInclude) {
        return this.callSuper("toObject", ["minWidth", "splitByGrapheme"].concat(propertiesToInclude));
      }
    });
    fabric3.Textbox.fromObject = function(object, callback) {
      return fabric3.Object._fromObject("Textbox", object, callback, "text");
    };
  })(exports2);
  (function() {
    var controlsUtils = fabric2.controlsUtils, scaleSkewStyleHandler = controlsUtils.scaleSkewCursorStyleHandler, scaleStyleHandler = controlsUtils.scaleCursorStyleHandler, scalingEqually = controlsUtils.scalingEqually, scalingYOrSkewingX = controlsUtils.scalingYOrSkewingX, scalingXOrSkewingY = controlsUtils.scalingXOrSkewingY, scaleOrSkewActionName = controlsUtils.scaleOrSkewActionName, objectControls = fabric2.Object.prototype.controls;
    objectControls.ml = new fabric2.Control({
      x: -0.5,
      y: 0,
      cursorStyleHandler: scaleSkewStyleHandler,
      actionHandler: scalingXOrSkewingY,
      getActionName: scaleOrSkewActionName
    });
    objectControls.mr = new fabric2.Control({
      x: 0.5,
      y: 0,
      cursorStyleHandler: scaleSkewStyleHandler,
      actionHandler: scalingXOrSkewingY,
      getActionName: scaleOrSkewActionName
    });
    objectControls.mb = new fabric2.Control({
      x: 0,
      y: 0.5,
      cursorStyleHandler: scaleSkewStyleHandler,
      actionHandler: scalingYOrSkewingX,
      getActionName: scaleOrSkewActionName
    });
    objectControls.mt = new fabric2.Control({
      x: 0,
      y: -0.5,
      cursorStyleHandler: scaleSkewStyleHandler,
      actionHandler: scalingYOrSkewingX,
      getActionName: scaleOrSkewActionName
    });
    objectControls.tl = new fabric2.Control({
      x: -0.5,
      y: -0.5,
      cursorStyleHandler: scaleStyleHandler,
      actionHandler: scalingEqually
    });
    objectControls.tr = new fabric2.Control({
      x: 0.5,
      y: -0.5,
      cursorStyleHandler: scaleStyleHandler,
      actionHandler: scalingEqually
    });
    objectControls.bl = new fabric2.Control({
      x: -0.5,
      y: 0.5,
      cursorStyleHandler: scaleStyleHandler,
      actionHandler: scalingEqually
    });
    objectControls.br = new fabric2.Control({
      x: 0.5,
      y: 0.5,
      cursorStyleHandler: scaleStyleHandler,
      actionHandler: scalingEqually
    });
    objectControls.mtr = new fabric2.Control({
      x: 0,
      y: -0.5,
      actionHandler: controlsUtils.rotationWithSnapping,
      cursorStyleHandler: controlsUtils.rotationStyleHandler,
      offsetY: -40,
      withConnection: true,
      actionName: "rotate"
    });
    if (fabric2.Textbox) {
      var textBoxControls = fabric2.Textbox.prototype.controls = {};
      textBoxControls.mtr = objectControls.mtr;
      textBoxControls.tr = objectControls.tr;
      textBoxControls.br = objectControls.br;
      textBoxControls.tl = objectControls.tl;
      textBoxControls.bl = objectControls.bl;
      textBoxControls.mt = objectControls.mt;
      textBoxControls.mb = objectControls.mb;
      textBoxControls.mr = new fabric2.Control({
        x: 0.5,
        y: 0,
        actionHandler: controlsUtils.changeWidth,
        cursorStyleHandler: scaleSkewStyleHandler,
        actionName: "resizing"
      });
      textBoxControls.ml = new fabric2.Control({
        x: -0.5,
        y: 0,
        actionHandler: controlsUtils.changeWidth,
        cursorStyleHandler: scaleSkewStyleHandler,
        actionName: "resizing"
      });
    }
  })();
})(fabric);
const DEFAULT_OBJ_CONFIG = {
  lockScalingFlip: true,
  originY: "center",
  originX: "center",
  lockMovementX: true,
  lockMovementY: true,
  borderColor: "transparent"
};
function randomString(length = 36) {
  let random = "";
  const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  for (let i2 = 0; i2 < length; i2 += 1) {
    random += possible.charAt(Math.floor(Math.random() * possible.length));
  }
  return random;
}
function state() {
  return useStore$1.getState();
}
function tools() {
  return state().editor.tools;
}
function fabricCanvas() {
  return state().fabric;
}
function initFabric(canvasEl) {
  var _a2;
  const fabricCanvas2 = new fabric.fabric.Canvas(canvasEl, {
    width: 1,
    height: 1
  });
  fabricCanvas2.preserveObjectStacking = true;
  fabricCanvas2.selection = false;
  fabricCanvas2.renderOnAddRemove = false;
  const textureSize = state().config.textureSize;
  if (textureSize)
    fabric.fabric.textureSize = textureSize;
  const userConfig = (_a2 = state().config.objectDefaults) == null ? void 0 : _a2.global;
  const objectDefaults = __spreadValues(__spreadValues({}, userConfig), DEFAULT_OBJ_CONFIG);
  Object.keys(objectDefaults).forEach((key) => {
    fabric.fabric.Object.prototype[key] = objectDefaults[key];
  });
  fabricCanvas2.on("object:added", (e2) => {
    var _a3, _b;
    if (e2.target && !((_b = (_a3 = e2.target) == null ? void 0 : _a3.data) == null ? void 0 : _b.id)) {
      if (!e2.target.data)
        e2.target.data = {};
      e2.target.data.id = randomString(10);
    }
  });
  const objectControls = fabric.fabric.Object.prototype.controls;
  Object.keys(objectControls).forEach((key) => {
    delete objectControls[key];
  });
  return fabricCanvas2;
}
class ZoomTool {
  constructor() {
    __publicField(this, "maxZoom", 2);
    __publicField(this, "minZoom", 1);
    __publicField(this, "step", 0.05);
    if (this.allowUserZoom) {
      this.bindMouseWheel();
    }
    useStore$1.subscribe((s2) => s2.stageSize, () => {
      setTimeout(() => {
        this.fitToScreen();
      }, 1);
    });
  }
  get allowUserZoom() {
    var _a2, _b, _c, _d;
    return (_d = (_c = (_b = (_a2 = state().config) == null ? void 0 : _a2.tools) == null ? void 0 : _b.zoom) == null ? void 0 : _c.allowUserZoom) != null ? _d : true;
  }
  get currentZoom() {
    return state().zoom;
  }
  zoomIn(amount = this.step) {
    this.set(this.currentZoom + amount);
  }
  canZoomIn(amount = this.step) {
    return this.currentZoom + amount <= this.maxZoom;
  }
  canZoomOut(amount = this.step) {
    return this.currentZoom - amount >= this.minZoom;
  }
  zoomOut(amount = this.step) {
    this.set(this.currentZoom - amount);
  }
  set(newZoom, resize = true) {
    if (newZoom < this.minZoom || newZoom > this.maxZoom)
      return;
    const width = index$1.round(state().original.width * newZoom, 0);
    const height = index$1.round(state().original.height * newZoom, 0);
    fabricCanvas().setZoom(newZoom);
    if (resize) {
      fabricCanvas().setDimensions({
        width,
        height
      });
    }
    state().setZoom(newZoom);
  }
  fitToScreen() {
    var _a2, _b;
    if (!((_b = (_a2 = state().config.tools) == null ? void 0 : _a2.zoom) == null ? void 0 : _b.fitImageToScreen)) {
      return;
    }
    const {
      width,
      height
    } = state().stageSize;
    const stageHeight = Math.max(height, 1);
    const stageWidth = Math.max(width, 1);
    if (state().original.height > stageHeight || state().original.width > stageWidth) {
      const scale2 = Math.min(stageHeight / state().original.height, stageWidth / state().original.width);
      this.minZoom = Math.min(scale2, 1);
    } else {
      this.minZoom = 1;
    }
    this.set(this.minZoom);
  }
  bindMouseWheel() {
    fabricCanvas().on("mouse:wheel", (opt) => {
      opt.e.preventDefault();
      opt.e.stopPropagation();
      if (opt.e.deltaY < 0) {
        this.zoomIn();
      } else {
        this.zoomOut();
      }
    });
  }
}
const staticObjectConfig = {
  selectable: false,
  evented: false,
  lockMovementX: true,
  lockMovementY: true,
  lockRotation: true,
  lockScalingX: true,
  lockScalingY: true,
  lockUniScaling: true,
  hasControls: false,
  hasBorders: false,
  hasRotatingPoint: false,
  strokeWidth: 0
};
function loadFabricImage(data) {
  return new Promise((resolve) => {
    fabric.fabric.util.loadImage(data, (img) => resolve(new fabric.fabric.Image(img)), null, state().config.crossOrigin ? "anonymous" : void 0);
  });
}
function canvasIsEmpty() {
  return !state().config.image && !state().config.blankCanvasSize && (!fabricCanvas() || fabricCanvas().getObjects().length === 0);
}
async function fetchStateJsonFromUrl(url) {
  const response = await fetch(url);
  return response.json();
}
class PixieCanvas {
  constructor() {
    __publicField(this, "minWidth", 50);
    __publicField(this, "minHeight", 50);
  }
  resize(width, height, {
    applyZoom = false,
    resizeHelper = true
  } = {}) {
    const currentZoom = state().zoom;
    fabricCanvas().setWidth(width * (applyZoom ? currentZoom : 1));
    fabricCanvas().setHeight(height * (applyZoom ? currentZoom : 1));
    state().setOriginal(width, height);
    if (resizeHelper) {
      tools().transform.resetStraightenAnchor();
    }
  }
  async addMainImage(url, loadStateName = "mainImage") {
    var _a2, _b;
    state().toggleLoading(loadStateName);
    const img = await loadFabricImage(url);
    if (!img)
      return;
    this.clear();
    img.set(staticObjectConfig);
    img.name = ObjectName.MainImage;
    fabricCanvas().add(img);
    this.resize(img.width, img.height);
    img.center();
    img.setCoords();
    tools().zoom.fitToScreen();
    state().toggleLoading(false);
    (_b = (_a2 = state().config).onMainImageLoaded) == null ? void 0 : _b.call(_a2, img);
    return img;
  }
  openNew(width, height, bgColor) {
    width = Math.max(this.minWidth, width);
    height = Math.max(this.minHeight, height);
    this.clear();
    this.resize(width, height);
    fabricCanvas().backgroundColor = bgColor;
    tools().zoom.fitToScreen();
    state().toggleLoading("newCanvas");
    requestAnimationFrame(() => {
      state().toggleLoading(false);
    });
    return Promise.resolve({
      width,
      height
    });
  }
  getMainImage() {
    return fabricCanvas().getObjects().find((obj) => obj.name === ObjectName.MainImage);
  }
  render() {
    fabricCanvas().requestRenderAll();
  }
  async loadInitialContent() {
    var _a2, _b;
    const image = state().config.image;
    const size = state().config.blankCanvasSize;
    const stateJson = state().config.state;
    if (image && image.endsWith("json")) {
      const stateObj = await fetchStateJsonFromUrl(image);
      await tools().import.loadState(stateObj);
    } else if (image && image.startsWith('{"canvas')) {
      await tools().import.loadState(image);
    } else if (image) {
      await this.addMainImage(image);
    } else if (stateJson) {
      await tools().import.loadState(stateJson);
    } else if (size) {
      await this.openNew(size.width, size.height);
    }
    if (canvasIsEmpty() && ((_b = (_a2 = state().config.ui) == null ? void 0 : _a2.openImageDialog) == null ? void 0 : _b.show)) {
      state().togglePanel("newImage", true);
    }
    return new Promise((resolve) => {
      setTimeout(() => {
        tools().history.addInitial();
        resolve();
      }, 10);
    });
  }
  clear() {
    fabricCanvas().clear();
    tools().frame.remove();
    tools().transform.resetStraightenAnchor();
  }
}
function isSvgSticker(obj) {
  return obj.name === ObjectName.Sticker && "forEachObject" in obj;
}
const SIZE_AND_POSITION_PROPS = ["fontSize", "fontFamily", "left", "top", "width", "height", "scaleX", "scaleY", "flipX", "flipY", "angle", "src", "strokeWidth"];
function fireObjModifiedEvent(values = {}) {
  fabricCanvas().fire("object:modified", buildObjModifiedEvent(values));
}
function buildObjModifiedEvent(values) {
  return {
    values,
    sizeOrPositionChanged: sizeOrPositionChanged(values)
  };
}
function sizeOrPositionChanged(values) {
  return Object.keys(values).some((r2) => SIZE_AND_POSITION_PROPS.includes(r2));
}
function setActiveTool(name = null) {
  if (state().dirty) {
    return;
  }
  tools().zoom.fitToScreen();
  const [toolName, overlayName] = getToolForObj(fabricCanvas().getActiveObject());
  if (name) {
    state().setActiveTool(name, toolName === name ? overlayName : null);
  } else {
    state().setActiveTool(toolName, overlayName);
  }
}
function getToolForObj(obj) {
  switch (obj == null ? void 0 : obj.name) {
    case ObjectName.Text:
      return [ToolName.TEXT, ActiveToolOverlay.Text];
    case ObjectName.Sticker:
    case ObjectName.Image:
      return [ToolName.STICKERS, ActiveToolOverlay.ActiveObject];
    case ObjectName.Shape:
      return [ToolName.SHAPES, ActiveToolOverlay.ActiveObject];
    default:
      return [null, null];
  }
}
function bindToFabricSelectionEvents() {
  state().fabric.on("selection:created", (e2) => {
    if (!shouldPreventObjDeselect(e2)) {
      selectNewObj(e2.target);
    }
  });
  state().fabric.on("selection:updated", (e2) => {
    if (!shouldPreventObjDeselect(e2)) {
      selectNewObj(e2.target);
    }
  });
  state().fabric.on("selection:cleared", () => {
    selectNewObj();
  });
}
function shouldPreventObjDeselect(e2) {
  const [toolName] = getToolForObj(e2.target);
  const objIsHandledByActiveTool = toolName === state().activeTool;
  if (state().dirty && (!e2.target || !objIsHandledByActiveTool)) {
    if (e2.deselected) {
      tools().objects.select(e2.deselected[0]);
    }
    return true;
  }
  return false;
}
function selectNewObj(obj) {
  if ((obj == null ? void 0 : obj.data.id) === state().objects.active.id) {
    return;
  }
  state().objects.setActive(obj != null ? obj : null);
  setActiveTool();
}
class ObjectTool {
  constructor() {
    this.syncObjects();
    bindToFabricSelectionEvents();
    state().fabric.on("text:editing:entered", () => {
      state().objects.setIsEditingText(true);
    });
    state().fabric.on("text:editing:exited", () => {
      state().objects.setIsEditingText(false);
    });
    state().fabric.on("object:added", () => {
      this.syncObjects();
    });
    state().fabric.on("object:removed", () => {
      this.syncObjects();
    });
  }
  getAll() {
    return fabricCanvas().getObjects().filter((obj) => {
      var _a2;
      return !((_a2 = obj == null ? void 0 : obj.data) == null ? void 0 : _a2.pixieInternal);
    });
  }
  get(name) {
    return this.getAll().find((obj) => obj.name === name);
  }
  getById(id2) {
    return this.getAll().find((obj) => obj.data.id === id2);
  }
  isActive(objectOrId) {
    var _a2;
    const objId = typeof objectOrId === "string" ? objectOrId : objectOrId.data.id;
    return ((_a2 = state().objects.active) == null ? void 0 : _a2.id) === objId;
  }
  getActive() {
    return fabricCanvas().getActiveObject();
  }
  has(name) {
    return this.getAll().findIndex((obj) => obj.name === name) > -1;
  }
  select(objOrId) {
    const obj = typeof objOrId === "string" ? this.getById(objOrId) : objOrId;
    if (!obj)
      return;
    fabricCanvas().setActiveObject(obj);
    fabricCanvas().requestRenderAll();
  }
  deselectActive() {
    fabricCanvas().discardActiveObject();
    fabricCanvas().requestRenderAll();
  }
  setValues(values, obj) {
    obj = obj || this.getActive();
    if (!obj)
      return;
    let fontChanged = false;
    if (isSvgSticker(obj) && values.fill !== obj.fill) {
      obj.forEachObject((path) => path.set("fill", values.fill));
    }
    if (isText(obj)) {
      if (values.fontFamily !== obj.fontFamily || values.fontSize !== obj.fontSize) {
        fontChanged = true;
      }
      if (obj.selectionStart !== obj.selectionEnd) {
        obj.setSelectionStyles(values);
      } else {
        obj.set(values);
      }
    } else {
      obj.set(values);
    }
    if (fontChanged) {
      setTimeout(() => {
        fabricCanvas().requestRenderAll();
      }, 50);
    } else {
      fabricCanvas().requestRenderAll();
    }
    state().objects.setActive(obj);
    fireObjModifiedEvent(values);
  }
  move(direction, amount = 1, obj) {
    obj = obj || this.getActive();
    if (!obj)
      return;
    if (direction === "up") {
      this.setValues({
        top: obj.top - amount
      });
    } else if (direction === "down") {
      this.setValues({
        top: obj.top + amount
      });
    } else if (direction === "left") {
      this.setValues({
        left: obj.left - amount
      });
    } else if (direction === "right") {
      this.setValues({
        left: obj.left + amount
      });
    }
    tools().canvas.render();
  }
  bringToFront(obj) {
    obj = obj || this.getActive();
    if (!obj)
      return;
    obj.bringToFront();
    tools().canvas.render();
  }
  sendToBack(obj) {
    obj = obj || this.getActive();
    if (!obj)
      return;
    obj.sendToBack();
    tools().canvas.render();
  }
  flipHorizontally(obj) {
    obj = obj || this.getActive();
    if (!obj)
      return;
    this.setValues({
      flipX: !obj.flipX
    });
    tools().canvas.render();
  }
  duplicate(obj) {
    const original = obj || this.getActive();
    if (!original)
      return;
    this.deselectActive();
    original.clone((clonedObj) => {
      clonedObj.set({
        left: original.left + 40,
        top: original.top + 40,
        data: __spreadProps(__spreadValues({}, original.data), {
          id: randomString(10)
        }),
        name: original.name
      });
      fabricCanvas().add(clonedObj);
      this.select(clonedObj);
      tools().canvas.render();
    });
  }
  delete(obj) {
    obj = obj || this.getActive();
    if (!obj)
      return;
    this.deselectActive();
    fabricCanvas().remove(obj);
    fabricCanvas().requestRenderAll();
    tools().history.addHistoryItem({
      name: "deletedObject"
    });
  }
  syncObjects() {
    const partial = this.getAll().map((o2) => {
      var _a2;
      return {
        name: o2.name,
        selectable: (_a2 = o2.selectable) != null ? _a2 : false,
        id: o2.data.id
      };
    });
    useStore$1.setState({
      objects: __spreadProps(__spreadValues({}, state().objects), {
        all: partial
      })
    });
  }
}
const DEFAULT_SERIALIZED_EDITOR_STATE = {
  frame: null,
  fonts: []
};
function getCurrentCanvasState(customProps = []) {
  var _a2;
  customProps = [...Object.keys(staticObjectConfig), "crossOrigin", "name", "displayName", "data", ...customProps];
  const canvas = fabricCanvas().toJSON(customProps);
  canvas.objects = canvas.objects.filter((obj) => !obj.data.pixieInternal).map((obj) => {
    if (obj.type === "image" && state().config.crossOrigin) {
      obj.crossOrigin = "anonymous";
    }
    if (isText(obj)) {
      obj.selectable = true;
      obj.lockMovementX = false;
      obj.lockMovementY = false;
      obj.lockUniScaling = false;
    }
    return __spreadProps(__spreadValues({}, obj), {
      data: obj.data ? __spreadValues({}, obj.data) : {}
    });
  });
  const activeFrame = tools().frame.active.config ? {
    name: tools().frame.active.config.name,
    sizePercent: tools().frame.active.currentSizeInPercent
  } : null;
  return {
    canvas,
    editor: {
      frame: activeFrame,
      zoom: state().zoom,
      activeObjectId: ((_a2 = state().objects.active) == null ? void 0 : _a2.id) || null
    },
    canvasWidth: state().original.width,
    canvasHeight: state().original.height
  };
}
function createHistoryItem(params) {
  if (!params.state) {
    params.state = getCurrentCanvasState();
  }
  const state2 = params.state || getCurrentCanvasState();
  return __spreadProps(__spreadValues({}, state2), {
    name: params.name,
    id: randomString(15)
  });
}
const TEXT_CONTROLS_PADDING = 15;
class TextTool {
  constructor() {
    __publicField(this, "minWidth", 250);
  }
  add(text2, providedConfig = {}) {
    var _a2, _b, _c;
    text2 = text2 || ((_b = (_a2 = state().config.tools) == null ? void 0 : _a2.text) == null ? void 0 : _b.defaultText);
    if (!text2)
      return;
    const options = __spreadProps(__spreadValues(__spreadValues({}, (_c = state().config.objectDefaults) == null ? void 0 : _c.text), providedConfig), {
      name: ObjectName.Text,
      padding: TEXT_CONTROLS_PADDING,
      editingBorderColor: defaultObjectProps.fill
    });
    const itext = new fabric.fabric.IText(text2, options);
    fabricCanvas().add(itext);
    this.autoPositionText(itext);
    tools().objects.select(itext);
  }
  autoPositionText(text2) {
    const canvasWidth = fabricCanvas().getWidth();
    const canvasHeight = fabricCanvas().getHeight();
    const minWidth = Math.min(fabricCanvas().getWidth(), this.minWidth);
    text2.scaleToWidth(Math.max(canvasWidth / 3, minWidth));
    if (text2.getScaledHeight() > canvasHeight) {
      text2.scaleToHeight(canvasHeight - text2.getScaledHeight() - 20);
    }
    text2.viewportCenter();
    fabricCanvas().getObjects("i-text").forEach((obj) => {
      if (obj === text2)
        return;
      if (obj.intersectsWithObject(text2)) {
        const offset2 = obj.top - text2.top + obj.getScaledHeight();
        let newTop = text2.top + offset2;
        if (newTop > state().original.height - obj.getScaledHeight()) {
          newTop = 0;
        }
        text2.set("top", newTop);
        text2.setCoords();
      }
    });
  }
}
function isAbsoluteUrl(url) {
  if (!url)
    return false;
  return /^[a-zA-Z][a-zA-Z\d+\-.]*?:/.test(url);
}
function assetUrl(uri) {
  if (!uri)
    return "";
  if (isAbsoluteUrl(uri)) {
    return uri;
  }
  const baseUrl = state().config.baseUrl ? `${state().config.baseUrl}/` : "";
  return `${baseUrl}${uri}`;
}
function loadFonts(fonts) {
  const promises = fonts.map(async (fontConfig) => {
    const loadedFont = Array.from(document.fonts.values()).find((current) => {
      return current.family === fontConfig.family;
    });
    if (loadedFont) {
      return loadedFont.loaded;
    }
    const fontFace = new FontFace(fontConfig.family, `url(${assetUrl(fontConfig.src)})`, fontConfig.descriptors);
    document.fonts.add(fontFace);
    return fontFace.load();
  });
  return Promise.all(promises);
}
class HistoryTool {
  async undo() {
    if (this.canUndo()) {
      const prev = state().history.items[state().history.pointer - 1];
      await this.load(prev);
    }
  }
  async redo() {
    if (this.canRedo()) {
      const next = state().history.items[state().history.pointer + 1];
      await this.load(next);
    }
  }
  canUndo() {
    return state().history.canUndo;
  }
  canRedo() {
    return state().history.canRedo;
  }
  reload() {
    return this.load(state().history.items[state().history.pointer]);
  }
  replaceCurrent() {
    const current = state().history.items[state().history.pointer];
    const items = [...state().history.items];
    items[state().history.pointer] = createHistoryItem({
      name: current.name,
      state: current
    });
  }
  addHistoryItem(params) {
    const item = createHistoryItem(params);
    const stateUntilPointer = state().history.items.slice(0, state().history.pointer + 1);
    const newItems = [...stateUntilPointer, item];
    state().history.update(newItems.length - 1, newItems);
  }
  load(item) {
    item = __spreadProps(__spreadValues({}, item), {
      editor: item.editor || DEFAULT_SERIALIZED_EDITOR_STATE
    });
    return new Promise((resolve) => {
      loadFonts(getUsedFonts(item.canvas.objects)).then(() => {
        fabricCanvas().loadFromJSON(item.canvas, () => {
          tools().zoom.set(1);
          if (item.canvasWidth && item.canvasHeight) {
            tools().canvas.resize(item.canvasWidth, item.canvasHeight, {
              resizeHelper: false,
              applyZoom: false
            });
          }
          tools().frame.remove();
          if (item.editor.frame) {
            tools().frame.add(item.editor.frame.name, item.editor.frame.sizePercent);
          }
          tools().objects.syncObjects();
          tools().objects.getAll().forEach((o2) => {
            if (!o2.data.pixieInternal && o2.originX === "left" && o2.originY === "top") {
              const point = o2.getPointByOrigin("center", "center");
              o2.set("left", point.x);
              o2.set("top", point.y);
            }
            o2.set(__spreadValues({}, DEFAULT_OBJ_CONFIG));
            if (o2.type === "i-text") {
              o2.padding = TEXT_CONTROLS_PADDING;
            }
          });
          tools().canvas.render();
          fabricCanvas().calcOffset();
          tools().zoom.fitToScreen();
          state().history.updatePointerById(item.id);
          tools().transform.resetStraightenAnchor();
          resolve();
        });
      });
    });
  }
  addInitial(stateObj) {
    const initial = state().history.items.find((i2) => i2.name === "initial");
    if (!initial && (stateObj || !canvasIsEmpty())) {
      this.addHistoryItem({
        name: "initial",
        state: stateObj
      });
    }
  }
}
function getUsedFonts(objects) {
  const fonts = [];
  objects.forEach((obj) => {
    var _a2, _b, _c;
    if (!isText(obj))
      return;
    const fontConfig = (_c = (_b = (_a2 = state().config.tools) == null ? void 0 : _a2.text) == null ? void 0 : _b.items) == null ? void 0 : _c.find((f2) => f2.family === obj.fontFamily);
    if (fontConfig) {
      fonts.push(fontConfig);
    }
  });
  return fonts;
}
class MergeTool {
  canMerge() {
    return tools().objects.getAll().filter((obj) => obj.name !== ObjectName.MainImage).length > 0;
  }
  async apply() {
    state().toggleLoading("merge");
    const data = tools().export.getDataUrl();
    if (data) {
      await tools().canvas.addMainImage(data, "merge");
    }
  }
}
const filterList = [{
  name: "grayscale"
}, {
  name: "blackWhite",
  fabricType: "blackwhite"
}, {
  name: "sharpen",
  uses: "Convolute",
  matrix: [0, -1, 0, -1, 5, -1, 0, -1, 0]
}, {
  name: "invert"
}, {
  name: "vintage"
}, {
  name: "polaroid"
}, {
  name: "kodachrome"
}, {
  name: "technicolor"
}, {
  name: "brownie"
}, {
  name: "sepia"
}, {
  name: "removeColor",
  fabricType: "removecolor",
  options: {
    distance: {
      type: "slider",
      current: 0.1,
      min: 0,
      max: 1,
      step: 0.01
    },
    color: {
      current: "#fff",
      type: "colorPicker"
    }
  }
}, {
  name: "brightness",
  options: {
    brightness: {
      type: "slider",
      current: 0.1,
      min: -1,
      max: 1,
      step: 0.1
    }
  }
}, {
  name: "gamma",
  options: {
    red: {
      type: "slider",
      current: 0.1,
      min: 0.2,
      max: 2.2,
      step: 3921e-6
    },
    green: {
      type: "slider",
      current: 0.1,
      min: 0.2,
      max: 2.2,
      step: 3921e-6
    },
    blue: {
      type: "slider",
      current: 0.1,
      min: 0.2,
      max: 2.2,
      step: 3921e-6
    }
  },
  apply: (filter2) => {
    filter2.gamma = [filter2.red, filter2.green, filter2.blue];
  }
}, {
  name: "noise",
  options: {
    noise: {
      type: "slider",
      current: 40,
      min: 1,
      max: 600
    }
  }
}, {
  name: "pixelate",
  options: {
    blocksize: {
      type: "slider",
      min: 1,
      max: 40,
      current: 6
    }
  }
}, {
  name: "blur",
  uses: "Convolute",
  matrix: [1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9]
}, {
  name: "emboss",
  uses: "Convolute",
  matrix: [1, 1, 1, 1, 0.7, -1, -1, -1, -1]
}, {
  name: "blendColor",
  fabricType: "blendcolor",
  options: {
    alpha: {
      type: "slider",
      current: 0.5,
      min: 0.1,
      max: 1,
      step: 0.1
    },
    mode: {
      current: "add",
      type: "select",
      available: [{
        key: "add"
      }, {
        key: "multiply"
      }, {
        key: "subtract"
      }, {
        key: "diff"
      }, {
        key: "screen"
      }, {
        key: "lighten"
      }, {
        key: "darken"
      }]
    },
    color: {
      type: "colorPicker",
      current: "#FF4081"
    }
  }
}];
const filterNameMessages = defineMessages({
  grayscale: {
    id: "hanSko",
    defaultMessage: [{
      "type": 0,
      "value": "grayscale"
    }]
  },
  blackWhite: {
    id: "PPBwfo",
    defaultMessage: [{
      "type": 0,
      "value": "Black & White"
    }]
  },
  sharpen: {
    id: "zigryQ",
    defaultMessage: [{
      "type": 0,
      "value": "Sharpen"
    }]
  },
  invert: {
    id: "LmfbOm",
    defaultMessage: [{
      "type": 0,
      "value": "Invert"
    }]
  },
  vintage: {
    id: "I9oSmn",
    defaultMessage: [{
      "type": 0,
      "value": "Vintage"
    }]
  },
  polaroid: {
    id: "bWw3nL",
    defaultMessage: [{
      "type": 0,
      "value": "Polaroid"
    }]
  },
  kodachrome: {
    id: "ntXTEb",
    defaultMessage: [{
      "type": 0,
      "value": "Kodachrome"
    }]
  },
  technicolor: {
    id: "eiirdl",
    defaultMessage: [{
      "type": 0,
      "value": "Technicolor"
    }]
  },
  brownie: {
    id: "7Vuh3m",
    defaultMessage: [{
      "type": 0,
      "value": "Brownie"
    }]
  },
  sepia: {
    id: "Ax70Ky",
    defaultMessage: [{
      "type": 0,
      "value": "Sepia"
    }]
  },
  removeColor: {
    id: "t+ijui",
    defaultMessage: [{
      "type": 0,
      "value": "Remove Color"
    }]
  },
  brightness: {
    id: "/4ssxy",
    defaultMessage: [{
      "type": 0,
      "value": "Brightness"
    }]
  },
  gamma: {
    id: "BQrhdi",
    defaultMessage: [{
      "type": 0,
      "value": "Gamma"
    }]
  },
  noise: {
    id: "N0/0z5",
    defaultMessage: [{
      "type": 0,
      "value": "Noise"
    }]
  },
  pixelate: {
    id: "thCGjq",
    defaultMessage: [{
      "type": 0,
      "value": "Pixelate"
    }]
  },
  blur: {
    id: "VXV22v",
    defaultMessage: [{
      "type": 0,
      "value": "Blur"
    }]
  },
  emboss: {
    id: "+EGmqP",
    defaultMessage: [{
      "type": 0,
      "value": "Emboss"
    }]
  },
  blendColor: {
    id: "3wuUmC",
    defaultMessage: [{
      "type": 0,
      "value": "Blend Color"
    }]
  }
});
const filterOptionMessages = defineMessages({
  distance: {
    id: "b1UO8a",
    defaultMessage: [{
      "type": 0,
      "value": "distance"
    }]
  },
  color: {
    id: "uHla4C",
    defaultMessage: [{
      "type": 0,
      "value": "color"
    }]
  },
  brightness: {
    id: "UFDwMY",
    defaultMessage: [{
      "type": 0,
      "value": "brightness"
    }]
  },
  red: {
    id: "2qELFK",
    defaultMessage: [{
      "type": 0,
      "value": "red"
    }]
  },
  green: {
    id: "biDOz4",
    defaultMessage: [{
      "type": 0,
      "value": "green"
    }]
  },
  blue: {
    id: "QOD43s",
    defaultMessage: [{
      "type": 0,
      "value": "blue"
    }]
  },
  noise: {
    id: "t2y9+Z",
    defaultMessage: [{
      "type": 0,
      "value": "noise"
    }]
  },
  blocksize: {
    id: "90afbG",
    defaultMessage: [{
      "type": 0,
      "value": "blocksize"
    }]
  },
  mode: {
    id: "s3GkYx",
    defaultMessage: [{
      "type": 0,
      "value": "mode"
    }]
  },
  alpha: {
    id: "tyl8L5",
    defaultMessage: [{
      "type": 0,
      "value": "alpha"
    }]
  }
});
function ucFirst(string) {
  if (!string)
    return string;
  return string.charAt(0).toUpperCase() + string.slice(1);
}
class FilterTool {
  constructor() {
    useStore$1.subscribe((s2) => s2.history.pointer, () => {
      this.syncState();
    });
  }
  apply(filterName) {
    state().filter.select(filterName, this.hasOptions(filterName));
    const filter2 = this.getByName(filterName);
    if (this.isApplied(filter2.name)) {
      this.remove(filter2.name);
      return;
    }
    const newFilter = this.create(filter2);
    this.getImages().forEach((image) => {
      var _a2;
      (_a2 = image.filters) == null ? void 0 : _a2.push(newFilter);
      image.applyFilters();
    });
    this.syncState();
    tools().canvas.render();
  }
  remove(filterName) {
    state().filter.deselect(filterName);
    const filter2 = this.getByName(filterName);
    this.getImages().forEach((image) => {
      var _a2;
      const i2 = this.findFilterIndex(filter2.name, image.filters);
      (_a2 = image.filters) == null ? void 0 : _a2.splice(i2, 1);
      image.applyFilters();
    });
    this.syncState();
    tools().canvas.render();
  }
  getAll() {
    return filterList;
  }
  getByName(name) {
    return filterList.find((f2) => f2.name === name);
  }
  isApplied(name) {
    const mainImage = tools().canvas.getMainImage();
    if (!mainImage)
      return false;
    return this.findFilterIndex(name, mainImage.filters) > -1;
  }
  applyValue(filterName, optionName, optionValue) {
    const filter2 = this.getByName(filterName);
    this.getImages().forEach((image) => {
      const fabricFilter = (image.filters || []).find((curr) => curr.type.toLowerCase() === filter2.name.toLowerCase());
      if (!fabricFilter)
        return;
      fabricFilter[optionName] = optionValue;
      if (filter2.apply) {
        filter2.apply(fabricFilter, optionName, optionValue);
      }
      image.applyFilters();
    });
    tools().canvas.render();
  }
  addCustom(name, filter2, editableOptions, initialConfig) {
    const imgFilters = fabric.fabric.Image.filters;
    imgFilters[ucFirst(name)] = fabric.fabric.util.createClass(imgFilters.BaseFilter, filter2);
    imgFilters[ucFirst(name)].fromObject = imgFilters.BaseFilter.fromObject;
    filterList.push({
      name,
      options: editableOptions,
      initialConfig
    });
  }
  create(config) {
    const initialConfig = config.initialConfig || {};
    let filter2;
    if (config.uses) {
      initialConfig.matrix = config.matrix;
      filter2 = new fabric.fabric.Image.filters[ucFirst(config.uses)](initialConfig);
    } else {
      Object.entries(config.options || {}).forEach(([key, value]) => {
        initialConfig[key] = value.current;
      });
      filter2 = new fabric.fabric.Image.filters[ucFirst(config.name)](initialConfig);
    }
    filter2.name = config.name;
    return filter2;
  }
  hasOptions(name) {
    return !!this.getByName(name).options;
  }
  findFilterIndex(name, fabricFilters) {
    if (!(fabricFilters == null ? void 0 : fabricFilters.length))
      return -1;
    const filterConfig = this.getByName(name);
    return fabricFilters.findIndex((fabricFilter) => {
      return this.configMatchesFabricFilter(filterConfig, fabricFilter);
    });
  }
  syncState() {
    var _a2;
    const applied = [];
    const fabricFilters = ((_a2 = this.getImages()[0]) == null ? void 0 : _a2.filters) || [];
    fabricFilters.forEach((fabricFilter) => {
      const filterConfig = this.getByFabricFilter(fabricFilter);
      if (filterConfig) {
        applied.push(filterConfig.name);
      }
    });
    useStore$1.setState({
      filter: __spreadProps(__spreadValues({}, state().filter), {
        applied
      })
    });
  }
  getByFabricFilter(fabricFilter) {
    return filterList.find((filterConfig) => {
      return this.configMatchesFabricFilter(filterConfig, fabricFilter);
    });
  }
  configMatchesFabricFilter(filterConfig, fabricFilter) {
    const type = fabricFilter.type.toLowerCase().replace(" ", "");
    if (type === filterConfig.fabricType || type === filterConfig.name) {
      return true;
    }
    return type === "convolute" && this.matrixAreEqual(filterConfig.matrix, fabricFilter.matrix);
  }
  matrixAreEqual(matrix1, matrix2) {
    if (!matrix1 || !matrix2 || matrix1.length !== matrix2.length)
      return false;
    for (let i2 = matrix1.length; i2--; ) {
      if (matrix1[i2] !== matrix2[i2])
        return false;
    }
    return true;
  }
  getImages() {
    return tools().objects.getAll().filter((obj) => {
      return obj.name === ObjectName.Image || ObjectName.MainImage;
    });
  }
}
function clampResizePayload(value) {
  if (value.width < getMinWidth(value.usePercentages)) {
    value.width = getMinWidth(value.usePercentages);
    if (value.maintainAspect) {
      value.height = aspectToHeight(value.width, value.usePercentages);
    }
  }
  if (value.width > getMaxWidth(value.usePercentages)) {
    value.width = getMaxWidth(value.usePercentages);
    if (value.maintainAspect) {
      value.height = aspectToHeight(value.width, value.usePercentages);
    }
  }
  if (value.height < getMinHeight(value.usePercentages)) {
    value.height = getMinHeight(value.usePercentages);
    if (value.maintainAspect) {
      value.width = aspectToWidth(value.height, value.usePercentages);
    }
  }
  if (value.height > getMaxHeight(value.usePercentages)) {
    value.height = getMaxHeight(value.usePercentages);
    if (value.maintainAspect) {
      value.width = aspectToWidth(value.height, value.usePercentages);
    }
  }
  return value;
}
function getMinWidth(usePercentages) {
  var _a2, _b;
  const minWidth = ((_b = (_a2 = state().config.tools) == null ? void 0 : _a2.resize) == null ? void 0 : _b.minWidth) || 50;
  if (usePercentages) {
    return Math.ceil(minWidth * 100 / state().original.width);
  }
  return minWidth;
}
function getMaxWidth(usePercentages) {
  var _a2, _b;
  const maxWidth = ((_b = (_a2 = state().config.tools) == null ? void 0 : _a2.resize) == null ? void 0 : _b.maxWidth) || 2400;
  if (usePercentages) {
    return Math.ceil(maxWidth * 100 / state().original.width);
  }
  return maxWidth;
}
function getMinHeight(usePercentages) {
  var _a2, _b;
  const minHeight = ((_b = (_a2 = state().config.tools) == null ? void 0 : _a2.resize) == null ? void 0 : _b.minHeight) || 50;
  if (usePercentages) {
    return Math.ceil(minHeight * 100 / state().original.height);
  }
  return minHeight;
}
function getMaxHeight(usePercentages) {
  var _a2, _b;
  const maxHeight = ((_b = (_a2 = state().config.tools) == null ? void 0 : _a2.resize) == null ? void 0 : _b.maxHeight) || 2400;
  if (usePercentages) {
    return Math.ceil(maxHeight * 100 / state().original.height);
  }
  return maxHeight;
}
function aspectToWidth(newHeight, usePercentages) {
  if (usePercentages) {
    return newHeight;
  }
  const hRatio = state().original.height / newHeight;
  return Math.floor(state().original.width / hRatio);
}
function aspectToHeight(newWidth, usePercentages) {
  if (usePercentages) {
    return newWidth;
  }
  const wRatio = state().original.width / newWidth;
  return Math.floor(state().original.height / wRatio);
}
class ResizeTool {
  apply(payload) {
    const {
      width,
      height,
      usePercentages
    } = clampResizePayload(payload);
    const currentWidth = Math.ceil(state().original.width);
    const currentHeight = Math.ceil(state().original.height);
    const newWidth = Math.ceil(width);
    const newHeight = Math.ceil(height);
    let widthScale;
    let heightScale;
    if (usePercentages) {
      widthScale = width / 100;
      heightScale = height / 100;
    } else {
      widthScale = width / state().original.width;
      heightScale = height / state().original.height;
    }
    if (currentWidth === newWidth && currentHeight === newHeight)
      return;
    this.resize(widthScale, heightScale);
  }
  resize(widthScale, heightScale) {
    tools().zoom.set(1, false);
    const newHeight = Math.round(state().original.height * heightScale);
    const newWidth = Math.round(state().original.width * widthScale);
    tools().canvas.resize(newWidth, newHeight, {
      applyZoom: false,
      resizeHelper: true
    });
    tools().objects.getAll().forEach((object) => {
      const scaleX = object.scaleX || 1;
      const scaleY = object.scaleY || 1;
      const left = object.left || 0;
      const top = object.top || 0;
      const tempScaleX = scaleX * widthScale;
      const tempScaleY = scaleY * heightScale;
      const tempLeft = left * widthScale;
      const tempTop = top * heightScale;
      object.scaleX = tempScaleX;
      object.scaleY = tempScaleY;
      object.left = tempLeft;
      object.top = tempTop;
      object.setCoords();
    });
    tools().zoom.fitToScreen();
    fabricCanvas().requestRenderAll();
  }
}
function drawCropzone(rect, refs) {
  if (refs.innerZone !== null) {
    refs = refs;
    drawInnerZone(rect, refs);
    drawMask(rect, refs);
    drawLines(rect, refs);
  }
}
function drawInnerZone(rect, refs) {
  refs.innerZone.style.width = `${rect.width}px`;
  refs.innerZone.style.height = `${rect.height}px`;
  refs.innerZone.style.transform = `translate(${rect.left}px, ${rect.top}px)`;
}
function drawMask(rect, refs) {
  const contWidth = state().canvasSize.width;
  const contHeight = state().canvasSize.height;
  refs.maskTop.style.height = `${rect.top}px`;
  refs.maskTop.style.width = `${contWidth}px`;
  refs.maskLeft.style.top = `${rect.top}px`;
  refs.maskLeft.style.height = `${rect.height}px`;
  refs.maskLeft.style.width = `${rect.left}px`;
  const rightLeft = rect.left + rect.width;
  refs.maskRight.style.left = `${rightLeft}px`;
  refs.maskRight.style.top = `${rect.top}px`;
  refs.maskRight.style.height = `${rect.height}px`;
  refs.maskRight.style.width = `${contWidth - rightLeft}px`;
  refs.maskBottom.style.height = `${contHeight - (rect.top + rect.height)}px`;
  refs.maskBottom.style.width = `${contWidth}px`;
}
function drawLines(rect, refs) {
  const horSpace = (rect.width - 2) / 3;
  refs.lineVer1.style.height = `${rect.height}px`;
  refs.lineVer1.style.transform = `translate(${horSpace}px, 0)`;
  refs.lineVer2.style.height = `${rect.height}px`;
  refs.lineVer2.style.transform = `translate(${horSpace * 2}px, 0)`;
  const verSpace = (rect.height - 2) / 3;
  refs.lineHor1.style.width = `${rect.width}px`;
  refs.lineHor1.style.transform = `translate(0, ${verSpace}px)`;
  refs.lineHor2.style.width = `${rect.width}px`;
  refs.lineHor2.style.transform = `translate(0, ${verSpace * 2}px)`;
}
function calcNewSizeFromAspectRatio(aspectRatio, oldWidth, oldHeight) {
  let newWidth = oldWidth;
  let newHeight = oldHeight;
  if (aspectRatio) {
    if (oldHeight * aspectRatio > oldWidth) {
      newHeight = oldWidth / aspectRatio;
    } else {
      newWidth = oldHeight * aspectRatio;
    }
  }
  return {
    width: Math.floor(newWidth),
    height: Math.floor(newHeight)
  };
}
function aspectRatioFromStr(ratio) {
  if (!ratio)
    return null;
  const parts = ratio.split(":");
  return parseInt(parts[0], 10) / parseInt(parts[1], 10);
}
function centerWithinBoundary(boundary, aspectRatio = null) {
  const rect = {
    width: boundary.width,
    height: boundary.height,
    top: 0,
    left: 0,
    angle: 0
  };
  if (aspectRatio) {
    const newSize = calcNewSizeFromAspectRatio(aspectRatio, rect.width, rect.height);
    rect.width = newSize.width;
    rect.height = newSize.height;
  }
  rect.left = (boundary.width - rect.width) / 2;
  rect.top = (boundary.height - rect.height) / 2;
  return rect;
}
class CropTool {
  constructor() {
    __publicField(this, "refs", null);
    __publicField(this, "zone");
  }
  apply(box) {
    var _a2;
    const frameName = (_a2 = tools().frame.active.config) == null ? void 0 : _a2.name;
    const frameSize = tools().frame.active.currentSizeInPercent;
    tools().frame.active.hide();
    return tools().merge.apply().then(() => {
      tools().canvas.resize(Math.round(box.width), Math.round(box.height), {
        applyZoom: true,
        resizeHelper: true
      });
      const img = tools().canvas.getMainImage();
      img.cropX = Math.round(box.left);
      img.cropY = Math.round(box.top);
      img.width = Math.round(box.width);
      img.height = Math.round(box.height);
      img.viewportCenter();
      if (frameName) {
        tools().frame.add(frameName, frameSize);
      }
      tools().zoom.fitToScreen();
      tools().canvas.render();
    });
  }
  drawZone(rect) {
    var _a2;
    if ((_a2 = this.refs) == null ? void 0 : _a2.current) {
      state().crop.setCropzoneRect(rect);
      drawCropzone(rect, this.refs.current);
    }
  }
  resetCropzone(aspectRatioStr) {
    var _a2;
    const boundaryRect = state().canvasSize;
    const aspectRatio = aspectRatioFromStr(aspectRatioStr);
    if (!boundaryRect)
      return;
    (_a2 = this.zone) == null ? void 0 : _a2.setConfig({
      aspectRatio,
      boundaryRect
    });
    state().crop.setAspectRatio(aspectRatioStr);
    const newRect = centerWithinBoundary(boundaryRect, aspectRatio);
    this.drawZone(newRect);
  }
  registerRefs(refs) {
    this.refs = refs;
  }
}
class ShapeTool {
  getShapeByName(name) {
    var _a2, _b;
    const shapes = (_b = (_a2 = state().config.tools) == null ? void 0 : _a2.shapes) == null ? void 0 : _b.items;
    return (shapes == null ? void 0 : shapes.find((shape) => shape.name === name)) || null;
  }
  addBasicShape(shapeName) {
    var _a2;
    const shape = this.getShapeByName(shapeName);
    if (!shape)
      return null;
    const _b = ((_a2 = state().config.objectDefaults) == null ? void 0 : _a2.shape) || {}, {
      width,
      height
    } = _b, userConfig = __objRest(_b, [
      "width",
      "height"
    ]);
    const options = __spreadValues(__spreadValues({}, userConfig), shape.options);
    let fabricShape;
    if (shape.name === "circle") {
      fabricShape = new fabric.fabric.Circle(__spreadProps(__spreadValues({}, options), {
        radius: 100
      }));
    } else if (shape.name === "ellipse") {
      fabricShape = new fabric.fabric.Ellipse(__spreadProps(__spreadValues({}, options), {
        rx: 100,
        ry: 50
      }));
    } else if (shape.type === "Path") {
      fabricShape = new fabric.fabric.Path(options.path, __spreadValues({
        displayName: shape.name
      }, options));
    } else {
      const shapeType = shape.type;
      fabricShape = new fabric.fabric[shapeType](__spreadProps(__spreadValues({}, options), {
        width: 150,
        height: 150
      }));
    }
    this.addAndPositionShape(fabricShape, ObjectName.Shape, {
      width,
      height
    });
    return fabricShape;
  }
  addSticker(categoryName, name) {
    var _a2, _b, _c;
    const category = (_c = (_b = (_a2 = state().config.tools) == null ? void 0 : _a2.stickers) == null ? void 0 : _b.items) == null ? void 0 : _c.find((cat) => cat.name === categoryName);
    if (!category)
      return Promise.resolve();
    if (category.type === "svg") {
      const url = stickerUrl(category, name);
      return this.addSvgSticker(url);
    }
    return this.addRegularSticker(category, name);
  }
  addRegularSticker(category, name) {
    return new Promise((resolve) => {
      fabric.fabric.util.loadImage(stickerUrl(category, name), (img) => {
        var _a2;
        const _b = ((_a2 = state().config.objectDefaults) == null ? void 0 : _a2.sticker) || {}, {
          width,
          height
        } = _b, userConfig = __objRest(_b, [
          "width",
          "height"
        ]);
        const sticker = new fabric.fabric.Image(img, userConfig);
        this.addAndPositionShape(sticker, ObjectName.Sticker, {
          width,
          height
        });
        resolve();
      });
    });
  }
  addSvgSticker(url, objectName = ObjectName.Sticker) {
    return new Promise((resolve) => {
      fabric.fabric.loadSVGFromURL(url, (objects, options) => {
        var _a2;
        const _b = ((_a2 = state().config.objectDefaults) == null ? void 0 : _a2.sticker) || {}, {
          width,
          height
        } = _b, userConfig = __objRest(_b, [
          "width",
          "height"
        ]);
        const sticker = fabric.fabric.util.groupSVGElements(objects, options);
        sticker.set(userConfig);
        this.addAndPositionShape(sticker, objectName, {
          width,
          height
        });
        resolve();
      });
    });
  }
  addAndPositionShape(shape, objectName, {
    width
  }) {
    shape.name = objectName;
    shape.scaleX = 1;
    shape.scaleY = 1;
    fabricCanvas().add(shape);
    const newWidth = width || state().original.width * state().zoom / 4;
    shape.scaleToWidth(Math.min(150, newWidth));
    shape.viewportCenter();
    shape.setCoords();
    tools().canvas.render();
    fabricCanvas().setActiveObject(shape);
  }
}
function stickerUrl(category, stickerName) {
  return assetUrl(`images/stickers/${category.name}/${stickerName}.${category.type}`);
}
class FramePatterns {
  constructor(activeFrame) {
    __publicField(this, "patternCache", []);
    this.activeFrame = activeFrame;
  }
  fillParts(mode) {
    this.patternCache.forEach((part) => {
      this.fillPartWithPattern(part, mode);
    });
  }
  fillPartWithPattern(part, mode) {
    if (!this.activeFrame.parts)
      return;
    part.canvas = new fabric.fabric.StaticCanvas(null);
    part.canvas.add(part.img);
    const pattern = new fabric.fabric.Pattern({
      source: part.canvas.getElement(),
      repeat: mode === "repeat" ? "repeat" : "no-repeat"
    });
    if (this.activeFrame.parts[part.name]) {
      this.activeFrame.parts[part.name].set("fill", pattern);
    }
  }
  scale(value) {
    if (!this.activeFrame.config || !this.patternCache) {
      return;
    }
    const mode = this.activeFrame.config.mode;
    value /= fabricCanvas().getRetinaScaling();
    this.patternCache.forEach((part) => {
      if (!this.activeFrame.parts)
        return;
      if (part.name === "top" || part.name === "bottom") {
        if (mode === "stretch") {
          this.scalePatternToWidth(part.img, this.activeFrame.parts.top.getScaledWidth());
          this.scalePatternToHeight(part.img, value);
        } else {
          part.img.scaleToHeight(value);
        }
      } else if (part.name === "left" || part.name === "right") {
        if (mode === "stretch") {
          this.scalePatternToWidth(part.img, value);
          this.scalePatternToHeight(part.img, this.activeFrame.parts.left.getScaledHeight());
        } else {
          part.img.scaleToWidth(value);
        }
      } else if (mode === "stretch") {
        this.scalePatternToWidth(part.img, value);
        this.scalePatternToHeight(part.img, value);
      } else {
        part.img.scaleToWidth(value);
      }
      part.canvas.setDimensions({
        width: part.img.getScaledWidth(),
        height: part.img.getScaledHeight()
      });
    });
    tools().canvas.render();
  }
  scalePatternToWidth(pattern, value) {
    if (!pattern.width)
      return;
    const boundingRectFactor = pattern.getBoundingRect().width / pattern.getScaledWidth();
    pattern.set("scaleX", value / pattern.width / boundingRectFactor);
    pattern.setCoords();
  }
  scalePatternToHeight(pattern, value) {
    if (!pattern.height)
      return;
    const boundingRectFactor = pattern.getBoundingRect().height / pattern.getScaledHeight();
    pattern.set("scaleY", value / pattern.height / boundingRectFactor);
    pattern.setCoords();
  }
  load(frame2) {
    const promises = this.activeFrame.getPartNames().map((part) => {
      return new Promise((resolve) => {
        const config = __spreadProps(__spreadValues({}, staticObjectConfig), {
          originX: "left",
          originY: "top"
        });
        if (state().config.crossOrigin) {
          config.crossOrigin = "anonymous";
        }
        fabric.fabric.Image.fromURL(this.getPartUrl(frame2, part), (img) => {
          resolve({
            name: part,
            img
          });
        }, config);
      });
    });
    return Promise.all(promises).then((images) => {
      this.patternCache = images;
      this.fillParts(frame2.mode);
    });
  }
  getPartUrl(frame2, part) {
    return assetUrl(`images/frames/${frame2.name}/${part}.png`);
  }
}
class FrameBuilder {
  constructor(activeFrame, patterns) {
    this.activeFrame = activeFrame;
    this.patterns = patterns;
  }
  get defaultColor() {
    var _a2, _b;
    return (_b = (_a2 = state().config.objectDefaults) == null ? void 0 : _a2.global) == null ? void 0 : _b.fill;
  }
  build(frame2, size) {
    this.createParts(frame2);
    this.resize(size);
    this.activeFrame.config = frame2;
    if (frame2.mode === "basic") {
      tools().canvas.render();
      return;
    }
    this.patterns.load(frame2).then(() => {
      this.patterns.scale(size);
      tools().canvas.render();
    });
  }
  createParts(frame2) {
    const parts = {};
    this.activeFrame.getPartNames().forEach((partName) => {
      const fill2 = frame2.mode === "basic" ? this.defaultColor : void 0;
      parts[partName] = new fabric.fabric.Rect(__spreadProps(__spreadValues({}, staticObjectConfig), {
        fill: fill2,
        originX: "left",
        originY: "top",
        name: `frame.rect.${partName}`,
        objectCaching: false,
        data: {
          pixieInternal: true
        }
      }));
      fabricCanvas().add(parts[partName]);
    });
    this.activeFrame.parts = parts;
  }
  resize(value) {
    const fullWidth = state().original.width;
    const fullHeight = state().original.height;
    const frame2 = this.activeFrame;
    const cornerSize = value;
    if (!frame2.parts)
      return;
    frame2.parts.topLeft.set({
      width: cornerSize,
      height: cornerSize
    });
    frame2.parts.topRight.set({
      left: fullWidth - frame2.parts.topLeft.getScaledWidth(),
      width: cornerSize,
      height: cornerSize
    });
    frame2.parts.top.set({
      left: frame2.parts.topLeft.getScaledWidth() - 1,
      width: fullWidth - frame2.parts.topLeft.getScaledWidth() - frame2.parts.topRight.getScaledWidth() + 3,
      height: cornerSize
    });
    frame2.parts.bottomLeft.set({
      top: fullHeight - frame2.parts.topLeft.getScaledHeight(),
      width: cornerSize,
      height: cornerSize
    });
    frame2.parts.left.set({
      top: frame2.parts.topLeft.getScaledHeight() - 1,
      width: cornerSize,
      height: fullHeight - frame2.parts.topLeft.getScaledHeight() - frame2.parts.bottomLeft.getScaledHeight() + 3
    });
    frame2.parts.bottomRight.set({
      left: fullWidth - frame2.parts.bottomLeft.getScaledWidth(),
      top: fullHeight - frame2.parts.topRight.getScaledWidth(),
      width: cornerSize,
      height: cornerSize
    });
    frame2.parts.bottom.set({
      left: frame2.parts.top.left,
      top: fullHeight - frame2.parts.top.getScaledHeight(),
      width: frame2.parts.top.getScaledWidth(),
      height: cornerSize
    });
    frame2.parts.right.set({
      left: fullWidth - frame2.parts.left.getScaledWidth(),
      top: frame2.parts.left.top,
      width: frame2.parts.left.width,
      height: frame2.parts.left.getScaledHeight()
    });
  }
}
class ActiveFrame {
  constructor() {
    __publicField(this, "corners", ["topLeft", "topRight", "bottomLeft", "bottomRight"]);
    __publicField(this, "sides", ["top", "right", "bottom", "left"]);
    __publicField(this, "parts", null);
    __publicField(this, "config", null);
    __publicField(this, "currentSizeInPercent", 100);
  }
  getPartNames() {
    return [...this.corners, ...this.sides];
  }
  hide() {
    if (!this.parts)
      return;
    Object.values(this.parts).forEach((part) => part.set({
      visible: false
    }));
    tools().canvas.render();
  }
  show() {
    if (!this.parts)
      return;
    Object.values(this.parts).forEach((part) => part.set({
      visible: true
    }));
    tools().canvas.render();
  }
  remove() {
    if (!this.parts)
      return;
    this.config = null;
    Object.values(this.parts).forEach((part) => {
      fabricCanvas().remove(part);
    });
    this.parts = null;
    tools().canvas.render();
  }
  is(frame2) {
    if (!this.config)
      return false;
    return this.config.name === frame2.name;
  }
  changeColor(value) {
    var _a2;
    if (((_a2 = this.config) == null ? void 0 : _a2.mode) !== "basic" || !this.parts)
      return;
    Object.values(this.parts).forEach((part) => {
      part.set("fill", value);
    });
    tools().canvas.render();
  }
  getMinSize() {
    var _a2, _b;
    return (_b = (_a2 = this.config) == null ? void 0 : _a2.size.min) != null ? _b : 1;
  }
  getMaxSize() {
    var _a2, _b;
    return (_b = (_a2 = this.config) == null ? void 0 : _a2.size.max) != null ? _b : 35;
  }
}
class FrameTool {
  constructor() {
    __publicField(this, "patterns");
    __publicField(this, "builder");
    __publicField(this, "active");
    this.active = new ActiveFrame();
    this.patterns = new FramePatterns(this.active);
    this.builder = new FrameBuilder(this.active, this.patterns);
    fabricCanvas().on("object:added", () => {
      Object.values(this.active.parts || []).forEach((part) => part.moveTo(98));
    });
  }
  add(frameName, sizePercent) {
    const frame2 = this.getByName(frameName);
    if (!frame2 || this.active.is(frame2))
      return;
    this.active.remove();
    this.active.currentSizeInPercent = sizePercent != null ? sizePercent : frame2.size.default;
    const size = this.calcFrameSizeInPixels(this.active.currentSizeInPercent);
    this.builder.build(frame2, size);
    state().frame.select(frame2);
  }
  resize(percentage) {
    if (!this.active.parts || !this.active.config)
      return;
    if (!percentage) {
      percentage = this.active.currentSizeInPercent;
    } else {
      this.active.currentSizeInPercent = percentage;
    }
    const size = this.calcFrameSizeInPixels(percentage);
    this.builder.resize(size);
    this.patterns.scale(size);
    tools().canvas.render();
  }
  changeColor(value) {
    this.active.changeColor(value);
  }
  remove() {
    this.active.remove();
    state().frame.deselect();
  }
  getByName(frameName) {
    var _a2, _b;
    const items = (_b = (_a2 = state().config.tools) == null ? void 0 : _a2.frame) == null ? void 0 : _b.items;
    if (items) {
      return items.find((frame2) => frame2.name === frameName);
    }
  }
  getActiveFrameConfig() {
    return this.active.config;
  }
  calcFrameSizeInPixels(percentage) {
    const min = Math.min(state().original.width, state().original.height);
    return Math.ceil(percentage / 100 * min);
  }
}
const VLineBrush = (canvas) => {
  const vLinePatternBrush = new fabric.fabric.PatternBrush(canvas);
  vLinePatternBrush.getPatternSrc = function VLineBrushSrc() {
    const patternCanvas = fabric.fabric.document.createElement("canvas");
    patternCanvas.width = 10;
    patternCanvas.height = 10;
    const ctx = patternCanvas.getContext("2d");
    ctx.strokeStyle = this.color;
    ctx.lineWidth = 5;
    ctx.beginPath();
    ctx.moveTo(0, 5);
    ctx.lineTo(10, 5);
    ctx.closePath();
    ctx.stroke();
    return patternCanvas;
  };
  return vLinePatternBrush;
};
const HLineBrush = (canvas) => {
  const hLinePatternBrush = new fabric.fabric.PatternBrush(canvas);
  hLinePatternBrush.getPatternSrc = function HLineBrushSrc() {
    const patternCanvas = document.createElement("canvas");
    patternCanvas.width = 10;
    patternCanvas.height = 10;
    const ctx = patternCanvas.getContext("2d");
    ctx.strokeStyle = this.color;
    ctx.lineWidth = 5;
    ctx.beginPath();
    ctx.moveTo(5, 0);
    ctx.lineTo(5, 10);
    ctx.closePath();
    ctx.stroke();
    return patternCanvas;
  };
  return hLinePatternBrush;
};
const DiamondBrush = (canvas) => {
  const diamondBrush = new fabric.fabric.PatternBrush(canvas);
  diamondBrush.getPatternSrc = function DiamondBrushSrc() {
    const squareWidth = this.width / 2;
    const squareDistance = 5;
    const patternCanvas = document.createElement("canvas");
    const rect = new fabric.fabric.Rect({
      width: squareWidth,
      height: squareWidth,
      angle: 45,
      fill: this.color
    });
    const canvasWidth = rect.getBoundingRect().width;
    patternCanvas.width = canvasWidth + squareDistance;
    patternCanvas.height = canvasWidth + squareDistance;
    rect.set({
      left: canvasWidth / 2,
      top: canvasWidth / 2
    });
    const ctx = patternCanvas.getContext("2d");
    rect.render(ctx);
    return patternCanvas;
  };
  return diamondBrush;
};
const SquareBrush = (canvas) => {
  const squareBrush = new fabric.fabric.PatternBrush(canvas);
  squareBrush.getPatternSrc = function SquareBrushSrc() {
    const squareWidth = 10;
    const squareDistance = 2;
    const patternCanvas = document.createElement("canvas");
    patternCanvas.width = squareWidth + squareDistance;
    patternCanvas.height = squareWidth + squareDistance;
    const ctx = patternCanvas.getContext("2d");
    ctx.fillStyle = this.color;
    ctx.fillRect(0, 0, squareWidth, squareWidth);
    return patternCanvas;
  };
  return squareBrush;
};
class DrawTool {
  constructor() {
    __publicField(this, "customBrushes", {
      VLineBrush,
      HLineBrush,
      DiamondBrush,
      SquareBrush
    });
    __publicField(this, "currentBrush", {
      type: "PencilBrush",
      color: (_f = (_e = state().config.objectDefaults) == null ? void 0 : _e.global) == null ? void 0 : _f.fill,
      width: BrushSizes[1]
    });
    __publicField(this, "onPathCreated", (e2) => {
      e2.path.name = ObjectName.Drawing;
      e2.path.set(getPathConfig());
      state().setDirty(true);
    });
  }
  enable() {
    fabricCanvas().on("path:created", this.onPathCreated);
    fabricCanvas().isDrawingMode = true;
    this.setBrushType(this.currentBrush.type);
    this.setBrushSize(this.currentBrush.width);
  }
  disable() {
    fabricCanvas().off("path:created", this.onPathCreated);
    fabricCanvas().isDrawingMode = false;
  }
  getBrushType() {
    return this.currentBrush.type;
  }
  setBrushType(type) {
    this.currentBrush.type = type;
    fabricCanvas().freeDrawingBrush = type in fabric.fabric ? new fabric.fabric[type](fabricCanvas()) : this.customBrushes[type](fabricCanvas());
    this.applyBrushStyles();
  }
  applyBrushStyles() {
    Object.keys(this.currentBrush).forEach((key) => {
      fabricCanvas().freeDrawingBrush[key] = this.currentBrush[key];
    });
    const brush = fabricCanvas().freeDrawingBrush;
    if (brush.getPatternSrc) {
      brush.source = brush.getPatternSrc.call(brush);
    }
  }
  setBrushSize(size) {
    this.currentBrush.width = size;
    this.applyBrushStyles();
  }
  getBrushSize() {
    return this.currentBrush.width;
  }
  setBrushColor(color2) {
    this.currentBrush.color = color2;
    this.applyBrushStyles();
  }
  getBrushColor() {
    return this.currentBrush.color;
  }
}
function getPathConfig() {
  const staticObjConfig = __spreadValues({}, staticObjectConfig);
  delete staticObjConfig.strokeWidth;
  return staticObjConfig;
}
function extensionFromFilename(fullFileName) {
  var _a2;
  const re = /(?:\.([^.]+))?$/;
  return (_a2 = re.exec(fullFileName)) == null ? void 0 : _a2[1];
}
function getFileMime(file) {
  const extensionsToMime = {
    md: "text/markdown",
    markdown: "text/markdown",
    mp4: "video/mp4",
    mp3: "audio/mp3",
    svg: "image/svg+xml",
    jpg: "image/jpeg",
    png: "image/png",
    gif: "image/gif",
    yaml: "text/yaml",
    yml: "text/yaml"
  };
  const fileExtension = file.name ? extensionFromFilename(file.name) : null;
  if (file.type) {
    return file.type;
  }
  if (fileExtension && fileExtension in extensionsToMime) {
    return extensionsToMime[fileExtension];
  }
  return null;
}
class UploadedFile {
  constructor(file, relativePath) {
    __publicField(this, "name");
    __publicField(this, "relativePath");
    __publicField(this, "size");
    __publicField(this, "mime");
    __publicField(this, "extension");
    __publicField(this, "native");
    __publicField(this, "lastModified");
    __publicField(this, "url", null);
    __publicField(this, "cachedData");
    this.name = file.name;
    this.size = file.size;
    this.mime = getFileMime(file);
    this.lastModified = file.lastModified;
    this.extension = extensionFromFilename(file.name);
    this.native = file;
    relativePath = relativePath || file.webkitRelativePath || null;
    if (relativePath && relativePath.match(/\//g).length > 1) {
      this.relativePath = relativePath;
    }
  }
  get data() {
    return new Promise((resolve) => {
      if (this.cachedData) {
        resolve(this.cachedData);
      }
      const reader = new FileReader();
      reader.addEventListener("load", () => {
        this.cachedData = reader.result;
        resolve(this.cachedData);
      });
      if (this.extension === "json") {
        reader.readAsText(this.native);
      } else {
        reader.readAsDataURL(this.native);
      }
    });
  }
}
function createUploadInput(config = {}) {
  var _a2;
  const old = document.querySelector("#hidden-file-upload-input");
  if (old)
    old.remove();
  const input = document.createElement("input");
  input.type = "file";
  input.multiple = (_a2 = config.multiple) != null ? _a2 : false;
  input.classList.add("hidden");
  input.style.display = "none";
  input.style.visibility = "hidden";
  input.id = "hidden-file-upload-input";
  input.accept = buildUploadInputAccept(config);
  if (config.directory) {
    input.webkitdirectory = true;
  }
  document.body.appendChild(input);
  return input;
}
function buildUploadInputAccept({
  extensions = [],
  types: types2 = []
}) {
  const accept = [];
  if (extensions) {
    extensions = extensions.map((e2) => {
      return e2.startsWith(".") ? e2 : `.${e2}`;
    });
    accept.push(extensions.join(","));
  }
  if (types2) {
    accept.push(types2.join(","));
  }
  return accept.join(",");
}
function openUploadWindow(config = {}) {
  return new Promise((resolve) => {
    const input = createUploadInput(config);
    input.onchange = (e2) => {
      const fileList = e2.target.files;
      if (!fileList) {
        return resolve([]);
      }
      const uploads = Array.from(fileList).map((file) => new UploadedFile(file));
      resolve(uploads);
      input.remove();
    };
    document.body.appendChild(input);
    input.click();
  });
}
let e$1 = { data: "" }, t$1 = (t2) => typeof window == "object" ? ((t2 ? t2.querySelector("#_goober") : window._goober) || Object.assign((t2 || document.head).appendChild(document.createElement("style")), { innerHTML: " ", id: "_goober" })).firstChild : t2 || e$1, l$2 = /(?:([\u0080-\uFFFF\w-%@]+) *:? *([^{;]+?);|([^;}{]*?) *{)|(}\s*)/g, a$2 = /\/\*[^]*?\*\/|\s\s+|\n/g, n$2 = (e2, t2) => {
  let r2 = "", l2 = "", a2 = "";
  for (let o2 in e2) {
    let s2 = e2[o2];
    o2[0] == "@" ? o2[1] == "i" ? r2 = o2 + " " + s2 + ";" : l2 += o2[1] == "f" ? n$2(s2, o2) : o2 + "{" + n$2(s2, o2[1] == "k" ? "" : t2) + "}" : typeof s2 == "object" ? l2 += n$2(s2, t2 ? t2.replace(/([^,])+/g, (e3) => o2.replace(/(^:.*)|([^,])+/g, (t3) => /&/.test(t3) ? t3.replace(/&/g, e3) : e3 ? e3 + " " + t3 : t3)) : o2) : s2 != null && (o2 = /^--/.test(o2) ? o2 : o2.replace(/[A-Z]/g, "-$&").toLowerCase(), a2 += n$2.p ? n$2.p(o2, s2) : o2 + ":" + s2 + ";");
  }
  return r2 + (t2 && a2 ? t2 + "{" + a2 + "}" : a2) + l2;
}, o$2 = {}, s$3 = (e2) => {
  if (typeof e2 == "object") {
    let t2 = "";
    for (let r2 in e2)
      t2 += r2 + s$3(e2[r2]);
    return t2;
  }
  return e2;
}, c$3 = (e2, t2, r2, c2, i2) => {
  let u2 = s$3(e2), p2 = o$2[u2] || (o$2[u2] = ((e3) => {
    let t3 = 0, r3 = 11;
    for (; t3 < e3.length; )
      r3 = 101 * r3 + e3.charCodeAt(t3++) >>> 0;
    return "go" + r3;
  })(u2));
  if (!o$2[p2]) {
    let t3 = u2 !== e2 ? e2 : ((e3) => {
      let t4, r3 = [{}];
      for (; t4 = l$2.exec(e3.replace(a$2, "")); )
        t4[4] ? r3.shift() : t4[3] ? r3.unshift(r3[0][t4[3]] = r3[0][t4[3]] || {}) : r3[0][t4[1]] = t4[2];
      return r3[0];
    })(e2);
    o$2[p2] = n$2(i2 ? { ["@keyframes " + p2]: t3 } : t3, r2 ? "" : "." + p2);
  }
  return ((e3, t3, r3) => {
    t3.data.indexOf(e3) == -1 && (t3.data = r3 ? e3 + t3.data : t3.data + e3);
  })(o$2[p2], t2, c2), p2;
}, i$3 = (e2, t2, r2) => e2.reduce((e3, l2, a2) => {
  let o2 = t2[a2];
  if (o2 && o2.call) {
    let e4 = o2(r2), t3 = e4 && e4.props && e4.props.className || /^go/.test(e4) && e4;
    o2 = t3 ? "." + t3 : e4 && typeof e4 == "object" ? e4.props ? "" : n$2(e4, "") : e4 === false ? "" : e4;
  }
  return e3 + l2 + (o2 == null ? "" : o2);
}, "");
function u$3(e2) {
  let r2 = this || {}, l2 = e2.call ? e2(r2.p) : e2;
  return c$3(l2.unshift ? l2.raw ? i$3(l2, [].slice.call(arguments, 1), r2.p) : l2.reduce((e3, t2) => Object.assign(e3, t2 && t2.call ? t2(r2.p) : t2), {}) : l2, t$1(r2.target), r2.g, r2.o, r2.k);
}
u$3.bind({ g: 1 });
u$3.bind({ k: 1 });
function h$3(e2, t2, r2, l2) {
  n$2.p = t2;
}
function _extends$2() {
  _extends$2 = Object.assign || function(target) {
    for (var i2 = 1; i2 < arguments.length; i2++) {
      var source = arguments[i2];
      for (var key in source) {
        if (Object.prototype.hasOwnProperty.call(source, key)) {
          target[key] = source[key];
        }
      }
    }
    return target;
  };
  return _extends$2.apply(this, arguments);
}
var isFunction = function isFunction2(valOrFunction) {
  return typeof valOrFunction === "function";
};
var resolveValue = function resolveValue2(valOrFunction, arg) {
  return isFunction(valOrFunction) ? valOrFunction(arg) : valOrFunction;
};
var genId = /* @__PURE__ */ function() {
  var count = 0;
  return function() {
    return (++count).toString();
  };
}();
var TOAST_LIMIT = 20;
var ActionType;
(function(ActionType2) {
  ActionType2[ActionType2["ADD_TOAST"] = 0] = "ADD_TOAST";
  ActionType2[ActionType2["UPDATE_TOAST"] = 1] = "UPDATE_TOAST";
  ActionType2[ActionType2["UPSERT_TOAST"] = 2] = "UPSERT_TOAST";
  ActionType2[ActionType2["DISMISS_TOAST"] = 3] = "DISMISS_TOAST";
  ActionType2[ActionType2["REMOVE_TOAST"] = 4] = "REMOVE_TOAST";
  ActionType2[ActionType2["START_PAUSE"] = 5] = "START_PAUSE";
  ActionType2[ActionType2["END_PAUSE"] = 6] = "END_PAUSE";
})(ActionType || (ActionType = {}));
var toastTimeouts = /* @__PURE__ */ new Map();
var addToRemoveQueue = function addToRemoveQueue2(toastId) {
  if (toastTimeouts.has(toastId)) {
    return;
  }
  var timeout = setTimeout(function() {
    toastTimeouts["delete"](toastId);
    dispatch({
      type: ActionType.REMOVE_TOAST,
      toastId
    });
  }, 1e3);
  toastTimeouts.set(toastId, timeout);
};
var clearFromRemoveQueue = function clearFromRemoveQueue2(toastId) {
  var timeout = toastTimeouts.get(toastId);
  if (timeout) {
    clearTimeout(timeout);
  }
};
var reducer = function reducer2(state2, action) {
  switch (action.type) {
    case ActionType.ADD_TOAST:
      return _extends$2({}, state2, {
        toasts: [action.toast].concat(state2.toasts).slice(0, TOAST_LIMIT)
      });
    case ActionType.UPDATE_TOAST:
      if (action.toast.id) {
        clearFromRemoveQueue(action.toast.id);
      }
      return _extends$2({}, state2, {
        toasts: state2.toasts.map(function(t2) {
          return t2.id === action.toast.id ? _extends$2({}, t2, action.toast) : t2;
        })
      });
    case ActionType.UPSERT_TOAST:
      var toast3 = action.toast;
      return state2.toasts.find(function(t2) {
        return t2.id === toast3.id;
      }) ? reducer2(state2, {
        type: ActionType.UPDATE_TOAST,
        toast: toast3
      }) : reducer2(state2, {
        type: ActionType.ADD_TOAST,
        toast: toast3
      });
    case ActionType.DISMISS_TOAST:
      var toastId = action.toastId;
      if (toastId) {
        addToRemoveQueue(toastId);
      } else {
        state2.toasts.forEach(function(toast4) {
          addToRemoveQueue(toast4.id);
        });
      }
      return _extends$2({}, state2, {
        toasts: state2.toasts.map(function(t2) {
          return t2.id === toastId || toastId === void 0 ? _extends$2({}, t2, {
            visible: false
          }) : t2;
        })
      });
    case ActionType.REMOVE_TOAST:
      if (action.toastId === void 0) {
        return _extends$2({}, state2, {
          toasts: []
        });
      }
      return _extends$2({}, state2, {
        toasts: state2.toasts.filter(function(t2) {
          return t2.id !== action.toastId;
        })
      });
    case ActionType.START_PAUSE:
      return _extends$2({}, state2, {
        pausedAt: action.time
      });
    case ActionType.END_PAUSE:
      var diff = action.time - (state2.pausedAt || 0);
      return _extends$2({}, state2, {
        pausedAt: void 0,
        toasts: state2.toasts.map(function(t2) {
          return _extends$2({}, t2, {
            pauseDuration: t2.pauseDuration + diff
          });
        })
      });
  }
};
var listeners = [];
var memoryState = {
  toasts: [],
  pausedAt: void 0
};
var dispatch = function dispatch2(action) {
  memoryState = reducer(memoryState, action);
  listeners.forEach(function(listener) {
    listener(memoryState);
  });
};
var defaultTimeouts = {
  blank: 4e3,
  error: 4e3,
  success: 2e3,
  loading: Infinity,
  custom: 4e3
};
var useStore = function useStore2(toastOptions) {
  if (toastOptions === void 0) {
    toastOptions = {};
  }
  var _useState = useState(memoryState), state2 = _useState[0], setState = _useState[1];
  useEffect(function() {
    listeners.push(setState);
    return function() {
      var index2 = listeners.indexOf(setState);
      if (index2 > -1) {
        listeners.splice(index2, 1);
      }
    };
  }, [state2]);
  var mergedToasts = state2.toasts.map(function(t2) {
    var _toastOptions$t$type, _toastOptions, _toastOptions$t$type2;
    return _extends$2({}, toastOptions, toastOptions[t2.type], t2, {
      duration: t2.duration || ((_toastOptions$t$type = toastOptions[t2.type]) == null ? void 0 : _toastOptions$t$type.duration) || ((_toastOptions = toastOptions) == null ? void 0 : _toastOptions.duration) || defaultTimeouts[t2.type],
      style: _extends$2({}, toastOptions.style, (_toastOptions$t$type2 = toastOptions[t2.type]) == null ? void 0 : _toastOptions$t$type2.style, t2.style)
    });
  });
  return _extends$2({}, state2, {
    toasts: mergedToasts
  });
};
var createToast = function createToast2(message, type, opts) {
  if (type === void 0) {
    type = "blank";
  }
  return _extends$2({
    createdAt: Date.now(),
    visible: true,
    type,
    ariaProps: {
      role: "status",
      "aria-live": "polite"
    },
    message,
    pauseDuration: 0
  }, opts, {
    id: (opts == null ? void 0 : opts.id) || genId()
  });
};
var createHandler = function createHandler2(type) {
  return function(message, options) {
    var toast3 = createToast(message, type, options);
    dispatch({
      type: ActionType.UPSERT_TOAST,
      toast: toast3
    });
    return toast3.id;
  };
};
var toast = function toast2(message, opts) {
  return createHandler("blank")(message, opts);
};
toast.error = /* @__PURE__ */ createHandler("error");
toast.success = /* @__PURE__ */ createHandler("success");
toast.loading = /* @__PURE__ */ createHandler("loading");
toast.custom = /* @__PURE__ */ createHandler("custom");
toast.dismiss = function(toastId) {
  dispatch({
    type: ActionType.DISMISS_TOAST,
    toastId
  });
};
toast.remove = function(toastId) {
  return dispatch({
    type: ActionType.REMOVE_TOAST,
    toastId
  });
};
toast.promise = function(promise, msgs, opts) {
  var id2 = toast.loading(msgs.loading, _extends$2({}, opts, opts == null ? void 0 : opts.loading));
  promise.then(function(p2) {
    toast.success(resolveValue(msgs.success, p2), _extends$2({
      id: id2
    }, opts, opts == null ? void 0 : opts.success));
    return p2;
  })["catch"](function(e2) {
    toast.error(resolveValue(msgs.error, e2), _extends$2({
      id: id2
    }, opts, opts == null ? void 0 : opts.error));
  });
  return promise;
};
var useToaster = function useToaster2(toastOptions) {
  var _useStore = useStore(toastOptions), toasts = _useStore.toasts, pausedAt = _useStore.pausedAt;
  useEffect(function() {
    if (pausedAt) {
      return;
    }
    var now2 = Date.now();
    var timeouts = toasts.map(function(t2) {
      if (t2.duration === Infinity) {
        return;
      }
      var durationLeft = (t2.duration || 0) + t2.pauseDuration - (now2 - t2.createdAt);
      if (durationLeft < 0) {
        if (t2.visible) {
          toast.dismiss(t2.id);
        }
        return;
      }
      return setTimeout(function() {
        return toast.dismiss(t2.id);
      }, durationLeft);
    });
    return function() {
      timeouts.forEach(function(timeout) {
        return timeout && clearTimeout(timeout);
      });
    };
  }, [toasts, pausedAt]);
  var handlers2 = useMemo(function() {
    return {
      startPause: function startPause() {
        dispatch({
          type: ActionType.START_PAUSE,
          time: Date.now()
        });
      },
      endPause: function endPause() {
        if (pausedAt) {
          dispatch({
            type: ActionType.END_PAUSE,
            time: Date.now()
          });
        }
      },
      updateHeight: function updateHeight(toastId, height) {
        return dispatch({
          type: ActionType.UPDATE_TOAST,
          toast: {
            id: toastId,
            height
          }
        });
      },
      calculateOffset: function calculateOffset(toast3, opts) {
        var _relevantToasts$filte;
        var _ref = opts || {}, _ref$reverseOrder = _ref.reverseOrder, reverseOrder = _ref$reverseOrder === void 0 ? false : _ref$reverseOrder, _ref$gutter = _ref.gutter, gutter = _ref$gutter === void 0 ? 8 : _ref$gutter, defaultPosition = _ref.defaultPosition;
        var relevantToasts = toasts.filter(function(t2) {
          return (t2.position || defaultPosition) === (toast3.position || defaultPosition) && t2.height;
        });
        var toastIndex = relevantToasts.findIndex(function(t2) {
          return t2.id === toast3.id;
        });
        var toastsBefore = relevantToasts.filter(function(toast4, i2) {
          return i2 < toastIndex && toast4.visible;
        }).length;
        var offset2 = (_relevantToasts$filte = relevantToasts.filter(function(t2) {
          return t2.visible;
        })).slice.apply(_relevantToasts$filte, reverseOrder ? [toastsBefore + 1] : [0, toastsBefore]).reduce(function(acc, t2) {
          return acc + (t2.height || 0) + gutter;
        }, 0);
        return offset2;
      }
    };
  }, [toasts, pausedAt]);
  return {
    toasts,
    handlers: handlers2
  };
};
h$3();
function showToast(message, {
  type
} = {}) {
  if (type === "error") {
    return toast.error(message);
  }
  return toast(message);
}
class UploadValidator {
  constructor() {
    __publicField(this, "validations", []);
    __publicField(this, "showToast", false);
  }
  validate(file) {
    if (!this.validations.length) {
      this.initValidations();
    }
    const failed = this.validations.find((validation) => {
      return validation.fails(file);
    });
    if (failed && this.showToast && failed.errorMessage) {
      showToast(failed.errorMessage, {
        type: "error"
      });
    }
    return {
      failed: !!failed,
      errorMessage: failed ? failed.errorMessage : null
    };
  }
}
class UploadValidation {
  constructor() {
    __publicField(this, "errorMessage");
  }
  passes(file) {
    return !this.fails(file);
  }
}
function prettyBytes(num) {
  const neg = num < 0;
  const units = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
  if (neg) {
    num = -num;
  }
  if (num < 1) {
    return `${(neg ? "-" : "") + num} B`;
  }
  const exponent = Math.min(Math.floor(Math.log(num) / Math.log(1024)), units.length - 1);
  num = Number(num / Math.pow(1024, exponent));
  const unit = units[exponent];
  if (num >= 10 || num % 1 === 0) {
    return `${(neg ? "-" : "") + num.toFixed(0)} ${unit}`;
  }
  return `${(neg ? "-" : "") + num.toFixed(1)} ${unit}`;
}
class FileSizeValidation extends UploadValidation {
  constructor(params) {
    super();
    this.params = params;
    this.errorMessage = defineMessage({
      id: "+vMr4s",
      defaultMessage: [{
        "type": 0,
        "value": "Maximum file size is "
      }, {
        "type": 1,
        "value": "number"
      }],
      values: {
        number: prettyBytes(+this.params.maxSize)
      }
    });
  }
  fails(file) {
    return this.params.maxSize < file.size;
  }
}
class AllowedExtensionsValidation extends UploadValidation {
  constructor(params) {
    super();
    this.params = params;
    this.errorMessage = defineMessage({
      id: "4pGuOJ",
      defaultMessage: [{
        "type": 0,
        "value": "Only these file types are allowed: "
      }, {
        "type": 1,
        "value": "extensions"
      }],
      values: {
        extensions: this.params.extensions.join(", ")
      }
    });
  }
  fails(file) {
    return !this.params.extensions.some((extension) => {
      var _a2;
      return extension.toLowerCase() === ((_a2 = file.extension) == null ? void 0 : _a2.toLowerCase());
    });
  }
}
function convertToBytes(value, unit) {
  if (value == null)
    return 0;
  switch (unit) {
    case "KB":
      return value * 1024;
    case "MB":
      return value * 1024 ** 2;
    case "GB":
      return value * 1024 ** 3;
    case "TB":
      return value * 1024 ** 4;
    case "PB":
      return value * 1024 ** 5;
    default:
      return value;
  }
}
class ImportToolValidator extends UploadValidator {
  constructor() {
    super(...arguments);
    __publicField(this, "DEFAULT_MAX_FILE_SIZE_MB", 10);
    __publicField(this, "showToast", true);
  }
  initValidations() {
    this.validations.push(new FileSizeValidation({
      maxSize: this.getMaxFileSize()
    }));
    const allowedExtensions = this.getAllowedExtensions();
    if (allowedExtensions && allowedExtensions.length) {
      this.validations.push(new AllowedExtensionsValidation({
        extensions: allowedExtensions
      }));
    }
  }
  getMaxFileSize() {
    var _a2, _b, _c;
    return (_c = (_b = (_a2 = state().config.tools) == null ? void 0 : _a2.import) == null ? void 0 : _b.maxFileSize) != null ? _c : convertToBytes(this.DEFAULT_MAX_FILE_SIZE_MB, "MB");
  }
  getAllowedExtensions() {
    var _a2, _b, _c;
    const imgExtensions = (_c = (_b = (_a2 = state().config.tools) == null ? void 0 : _a2.import) == null ? void 0 : _b.validImgExtensions) != null ? _c : [];
    return [...imgExtensions, "json"];
  }
}
async function addImage(url, fitToScreen = true) {
  const img = await loadFabricImage(url);
  if (!img)
    return;
  return new Promise((resolve) => {
    img.name = ObjectName.Image;
    img.opacity = 0;
    const maxWidth = state().original.width;
    const maxHeight = state().original.height;
    if (fitToScreen && (img.width >= maxWidth || img.height >= maxHeight)) {
      const newWidth = maxWidth - 0.1 * maxWidth;
      const newHeight = maxHeight - 0.1 * maxHeight;
      const scale2 = 1 / Math.min(newHeight / img.getScaledHeight(), newWidth / img.getScaledWidth());
      img.scaleX *= 1 / scale2;
      img.scaleY *= 1 / scale2;
    }
    state().fabric.add(img);
    state().fabric.setActiveObject(img);
    img.viewportCenter();
    img.setCoords();
    state().fabric.requestRenderAll();
    tools().zoom.fitToScreen();
    img.animate("opacity", "1", {
      duration: 425,
      onChange: () => {
        state().fabric.requestRenderAll();
      },
      onComplete: () => {
        resolve(img);
      }
    });
  });
}
function resetEditor(config) {
  tools().canvas.clear();
  tools().frame.remove();
  state().setConfig(__spreadValues({
    image: void 0,
    blankCanvasSize: void 0
  }, config));
  state().reset();
  return new Promise((resolve) => setTimeout(resolve));
}
var UploadInputType = /* @__PURE__ */ ((UploadInputType2) => {
  UploadInputType2["image"] = "image/*";
  UploadInputType2["audio"] = "audio/*";
  UploadInputType2["json"] = "application/json";
  UploadInputType2["video"] = "video/mp4,video/mpeg,video/x-m4v,video/*";
  return UploadInputType2;
})(UploadInputType || {});
class ImportTool {
  constructor() {
    __publicField(this, "validator", new ImportToolValidator());
  }
  async uploadAndAddImage() {
    const file = await this.openUploadWindow();
    await this.openUploadedFile(file);
  }
  async uploadAndReplaceMainImage() {
    const file = await this.openUploadWindow();
    if (file) {
      await this.openBackgroundImage(file);
    }
  }
  async uploadAndOpenStateFile() {
    const file = await this.openUploadWindow(stateContentType);
    if (file) {
      await this.loadState(await file.data);
    }
  }
  async openUploadedFile(file) {
    var _a2, _b, _c;
    if (!file)
      return;
    const fileData = await file.data;
    switch (file.extension) {
      case "json":
        await this.loadState(fileData);
        break;
      case "svg":
        await tools().shape.addSvgSticker(fileData, ObjectName.Image);
        tools().history.addHistoryItem({
          name: "overlayImage"
        });
        break;
      default:
        await addImage(fileData, (_c = (_b = (_a2 = state().config.tools) == null ? void 0 : _a2.import) == null ? void 0 : _b.fitOverlayToScreen) != null ? _c : true);
        tools().history.addHistoryItem({
          name: "overlayImage"
        });
    }
  }
  async loadState(data) {
    state().toggleLoading("state");
    await resetEditor();
    let stateObj;
    if (typeof data === "string") {
      if (data.endsWith(".json")) {
        stateObj = await fetchStateJsonFromUrl(data);
      } else {
        stateObj = JSON.parse(data);
      }
    } else {
      stateObj = data;
    }
    await tools().history.addInitial(stateObj);
    await tools().history.reload();
    state().toggleLoading(false);
  }
  async openUploadWindow(contentTypes) {
    var _a2, _b;
    contentTypes = contentTypes || imgContentTypes();
    const file = (await openUploadWindow(contentTypes))[0];
    if (this.fileIsValid(file)) {
      (_b = (_a2 = state().config).onFileOpen) == null ? void 0 : _b.call(_a2, file);
      return file;
    }
    return null;
  }
  async openBackgroundImage(image) {
    await resetEditor();
    let src;
    if (image instanceof HTMLImageElement) {
      src = image.src;
    } else if (image instanceof UploadedFile) {
      src = await image.data;
    } else {
      src = image;
    }
    const response = await tools().canvas.addMainImage(src);
    await tools().history.addInitial();
    return response;
  }
  fileIsValid(file) {
    return !this.validator.validate(file).failed;
  }
}
function imgContentTypes() {
  var _a2, _b;
  const validExtensions = (_b = (_a2 = state().config.tools) == null ? void 0 : _a2.import) == null ? void 0 : _b.validImgExtensions;
  if (validExtensions) {
    return {
      extensions: validExtensions
    };
  }
  return {
    types: [UploadInputType.image]
  };
}
const stateContentType = {
  types: [".json", UploadInputType.json]
};
class WatermarkTool {
  constructor() {
    __publicField(this, "watermark", null);
    __publicField(this, "lineStyle", {
      stroke: "rgba(255,255,255,0.3)",
      strokeWidth: 5,
      strokeLineCap: "round",
      strokeLineJoin: "round"
    });
  }
  add(watermarkText) {
    this.createGroup();
    this.addText(watermarkText);
    this.addLines();
    fabricCanvas().add(this.watermark);
    tools().canvas.render();
  }
  remove() {
    if (!this.watermark)
      return;
    fabricCanvas().remove(this.watermark);
    this.watermark = null;
    tools().canvas.render();
  }
  createGroup() {
    this.watermark = new fabric.fabric.Group(void 0, __spreadProps(__spreadValues({}, staticObjectConfig), {
      width: state().original.width,
      height: state().original.height,
      excludeFromExport: true,
      top: 0,
      left: 0,
      originX: "left",
      originY: "top"
    }));
  }
  addText(watermarkText) {
    var _a2;
    const text2 = new fabric.fabric.Text(watermarkText, {
      fill: "rgba(255,255,255,0.3)",
      strokeWidth: 2,
      stroke: "rgba(255,255,255,0.4)",
      originX: "center",
      originY: "center",
      fontWeight: 600,
      fontSize: 150,
      fontFamily: "Courier New"
    });
    text2.scaleToWidth(state().original.width / 2);
    (_a2 = this.watermark) == null ? void 0 : _a2.add(text2);
  }
  addLines() {
    var _a2;
    if (!this.watermark)
      return;
    const text2 = (_a2 = this.watermark) == null ? void 0 : _a2.getObjects("text")[0];
    const halfWidth = state().original.width / 2;
    const halfHeight = state().original.height / 2;
    const offsetY = 100;
    const offsetX = text2.width / 4;
    const line1 = new fabric.fabric.Line(void 0, this.lineStyle);
    const line2 = new fabric.fabric.Line(void 0, this.lineStyle);
    const line3 = new fabric.fabric.Line(void 0, this.lineStyle);
    const line4 = new fabric.fabric.Line(void 0, this.lineStyle);
    this.watermark.add(line1, line2, line3, line4);
    line1.set({
      x1: offsetX,
      y1: -offsetY,
      x2: halfWidth,
      y2: -halfHeight
    });
    line2.set({
      x1: offsetX,
      y1: offsetY,
      x2: halfWidth,
      y2: halfHeight
    });
    line3.set({
      x1: -offsetX,
      y1: -offsetY,
      x2: -halfWidth,
      y2: -halfHeight
    });
    line4.set({
      x1: -offsetX,
      y1: offsetY,
      x2: -halfWidth,
      y2: halfHeight
    });
  }
}
var FileSaver_min = { exports: {} };
(function(module2, exports2) {
  (function(a2, b2) {
    b2();
  })(commonjsGlobal, function() {
    function b2(a3, b3) {
      return typeof b3 == "undefined" ? b3 = { autoBom: false } : typeof b3 != "object" && (console.warn("Deprecated: Expected third argument to be a object"), b3 = { autoBom: !b3 }), b3.autoBom && /^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(a3.type) ? new Blob(["\uFEFF", a3], { type: a3.type }) : a3;
    }
    function c2(a3, b3, c3) {
      var d3 = new XMLHttpRequest();
      d3.open("GET", a3), d3.responseType = "blob", d3.onload = function() {
        g2(d3.response, b3, c3);
      }, d3.onerror = function() {
        console.error("could not download file");
      }, d3.send();
    }
    function d2(a3) {
      var b3 = new XMLHttpRequest();
      b3.open("HEAD", a3, false);
      try {
        b3.send();
      } catch (a4) {
      }
      return 200 <= b3.status && 299 >= b3.status;
    }
    function e2(a3) {
      try {
        a3.dispatchEvent(new MouseEvent("click"));
      } catch (c3) {
        var b3 = document.createEvent("MouseEvents");
        b3.initMouseEvent("click", true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null), a3.dispatchEvent(b3);
      }
    }
    var f2 = typeof window == "object" && window.window === window ? window : typeof self == "object" && self.self === self ? self : typeof commonjsGlobal == "object" && commonjsGlobal.global === commonjsGlobal ? commonjsGlobal : void 0, a2 = f2.navigator && /Macintosh/.test(navigator.userAgent) && /AppleWebKit/.test(navigator.userAgent) && !/Safari/.test(navigator.userAgent), g2 = f2.saveAs || (typeof window != "object" || window !== f2 ? function() {
    } : "download" in HTMLAnchorElement.prototype && !a2 ? function(b3, g3, h2) {
      var i2 = f2.URL || f2.webkitURL, j2 = document.createElement("a");
      g3 = g3 || b3.name || "download", j2.download = g3, j2.rel = "noopener", typeof b3 == "string" ? (j2.href = b3, j2.origin === location.origin ? e2(j2) : d2(j2.href) ? c2(b3, g3, h2) : e2(j2, j2.target = "_blank")) : (j2.href = i2.createObjectURL(b3), setTimeout(function() {
        i2.revokeObjectURL(j2.href);
      }, 4e4), setTimeout(function() {
        e2(j2);
      }, 0));
    } : "msSaveOrOpenBlob" in navigator ? function(f3, g3, h2) {
      if (g3 = g3 || f3.name || "download", typeof f3 != "string")
        navigator.msSaveOrOpenBlob(b2(f3, h2), g3);
      else if (d2(f3))
        c2(f3, g3, h2);
      else {
        var i2 = document.createElement("a");
        i2.href = f3, i2.target = "_blank", setTimeout(function() {
          e2(i2);
        });
      }
    } : function(b3, d3, e3, g3) {
      if (g3 = g3 || open("", "_blank"), g3 && (g3.document.title = g3.document.body.innerText = "downloading..."), typeof b3 == "string")
        return c2(b3, d3, e3);
      var h2 = b3.type === "application/octet-stream", i2 = /constructor/i.test(f2.HTMLElement) || f2.safari, j2 = /CriOS\/[\d]+/.test(navigator.userAgent);
      if ((j2 || h2 && i2 || a2) && typeof FileReader != "undefined") {
        var k2 = new FileReader();
        k2.onloadend = function() {
          var a3 = k2.result;
          a3 = j2 ? a3 : a3.replace(/^data:[^;]*;/, "data:attachment/file;"), g3 ? g3.location.href = a3 : location = a3, g3 = null;
        }, k2.readAsDataURL(b3);
      } else {
        var l2 = f2.URL || f2.webkitURL, m2 = l2.createObjectURL(b3);
        g3 ? g3.location = m2 : location.href = m2, g3 = null, setTimeout(function() {
          l2.revokeObjectURL(m2);
        }, 4e4);
      }
    });
    f2.saveAs = g2.saveAs = g2, module2.exports = g2;
  });
})(FileSaver_min);
function b64toBlob(b64Data, contentType, sliceSize) {
  contentType = contentType || "";
  sliceSize = sliceSize || 512;
  const byteCharacters = atob(b64Data);
  const byteArrays = [];
  for (let offset2 = 0; offset2 < byteCharacters.length; offset2 += sliceSize) {
    const slice2 = byteCharacters.slice(offset2, offset2 + sliceSize);
    const byteNumbers = new Array(slice2.length);
    for (let i2 = 0; i2 < slice2.length; i2++) {
      byteNumbers[i2] = slice2.charCodeAt(i2);
    }
    const byteArray = new Uint8Array(byteNumbers);
    byteArrays.push(byteArray);
  }
  return new Blob(byteArrays, {
    type: contentType
  });
}
class ExportTool {
  save(name, format, quality) {
    var _a2, _b, _c;
    const exportConfig = (_a2 = state().config.tools) == null ? void 0 : _a2.export;
    name = name || (exportConfig == null ? void 0 : exportConfig.defaultName);
    format = this.getFormat(format);
    quality = this.getQuality(quality);
    const filename = `${name}.${format}`;
    this.applyWaterMark();
    const data = format === "json" ? this.getJsonState() : this.getDataUrl(format, quality);
    tools().watermark.remove();
    if (!data)
      return;
    if (state().config.saveUrl) {
      fetch(state().config.saveUrl, {
        method: "POST",
        body: JSON.stringify({
          data,
          filename,
          format
        })
      });
    } else if (state().config.onSave) {
      (_c = (_b = state().config).onSave) == null ? void 0 : _c.call(_b, data, filename, format);
    } else {
      const blob = this.getCanvasBlob(format, data);
      FileSaver_min.exports.saveAs(blob, filename);
    }
  }
  getDataUrl(format, quality) {
    this.prepareCanvas();
    try {
      if (format === "svg") {
        return fabricCanvas().toSVG();
      }
      return fabricCanvas().toDataURL({
        format: this.getFormat(format),
        quality: this.getQuality(quality),
        multiplier: Math.max(state().original.width / fabricCanvas().width, state().original.height / fabricCanvas().height)
      });
    } catch (e2) {
      if (e2.message.toLowerCase().includes("tainted")) {
        showToast(defineMessage({
          id: "m45ghm",
          defaultMessage: [{
            "type": 0,
            "value": "Could not export canvas with external image."
          }]
        }), {
          type: "error"
        });
      }
    }
    return null;
  }
  getCanvasBlob(format, data) {
    if (format === "json") {
      return new Blob([data], {
        type: "application/json"
      });
    }
    if (format === "svg") {
      return new Blob([data], {
        type: "image/svg+xml"
      });
    }
    const contentType = `image/${format}`;
    data = data.replace(/data:image\/([a-z]*)?;base64,/, "");
    return b64toBlob(data, contentType);
  }
  getJsonState() {
    return JSON.stringify(getCurrentCanvasState());
  }
  prepareCanvas() {
    fabricCanvas().discardActiveObject();
  }
  applyWaterMark() {
    const watermark = state().config.watermarkText;
    if (watermark) {
      tools().watermark.add(watermark);
    }
  }
  getFormat(format) {
    var _a2;
    const config = (_a2 = state().config.tools) == null ? void 0 : _a2.export;
    format = format || (config == null ? void 0 : config.defaultFormat) || "png";
    if (format === "jpg")
      format = "jpeg";
    return format;
  }
  getQuality(quality) {
    var _a2;
    const config = (_a2 = state().config.tools) == null ? void 0 : _a2.export;
    quality = quality || (config == null ? void 0 : config.defaultQuality) || 0.8;
    return quality;
  }
}
class CornersTool {
  constructor() {
    __publicField(this, "previewRect", null);
  }
  async apply(radius) {
    if (!this.previewRect) {
      this.showPreview();
    }
    this.updatePreview(radius);
    fabricCanvas().remove(this.previewRect);
    fabricCanvas().clipPath = this.previewRect;
    const data = tools().export.getDataUrl();
    if (data) {
      tools().canvas.clear();
    }
    this.hidePreview();
    if (data) {
      await tools().canvas.addMainImage(data);
    }
    fabricCanvas().clipPath = void 0;
  }
  getPreviewRadius() {
    var _a2;
    return ((_a2 = this.previewRect) == null ? void 0 : _a2.rx) || 0;
  }
  updatePreview(radius) {
    if (!this.previewRect)
      return;
    this.previewRect.set({
      rx: radius,
      ry: radius
    });
    tools().canvas.render();
  }
  showPreview() {
    this.previewRect = new fabric.fabric.Rect({
      width: state().original.width,
      height: state().original.height,
      rx: 50,
      ry: 50,
      objectCaching: false,
      fill: "transparent",
      name: "round.rect",
      data: {
        pixieInternal: true
      },
      stroke: "rgba(255,255,255,0.8)",
      strokeWidth: 3,
      strokeDashArray: [4, 4],
      selectable: false,
      evented: false
    });
    fabricCanvas().add(this.previewRect);
    this.previewRect.moveTo(99);
    this.previewRect.viewportCenter();
    tools().canvas.render();
  }
  hidePreview() {
    if (!this.previewRect)
      return;
    fabricCanvas().remove(this.previewRect);
    tools().canvas.render();
    this.previewRect = null;
  }
}
class TransformTool {
  get straightenAnchor() {
    return fabricCanvas().getObjects().find((obj) => obj.name === ObjectName.StraightenAnchor);
  }
  rotateLeft() {
    this.rotateFixed(-90);
  }
  rotateRight() {
    this.rotateFixed(90);
  }
  straighten(degrees2) {
    this.storeObjectsRelationToHelper();
    tools().objects.deselectActive();
    const newAngle = (this.straightenAnchor.data.rotateAngle || 0) + degrees2;
    const scale2 = this.getImageScale(newAngle, this.straightenAnchor);
    this.straightenAnchor.angle = newAngle;
    this.straightenAnchor.scaleX = scale2;
    this.straightenAnchor.scaleY = scale2;
    this.straightenAnchor.data.straightenAngle = degrees2;
    this.transformObjectsBasedOnHelper();
  }
  flip(direction) {
    const prop = direction === "horizontal" ? "flipY" : "flipX";
    tools().objects.getAll().forEach((obj) => {
      obj[prop] = !obj[prop];
    });
    tools().canvas.render();
  }
  rotateFixed(degrees2) {
    tools().zoom.set(1, false);
    tools().objects.deselectActive();
    const currentRotateAngle = this.straightenAnchor.data.rotateAngle || 0;
    degrees2 = Math.round(degrees2 / 90) * 90;
    const newAngle = currentRotateAngle + (this.straightenAnchor.data.straightenAngle || 0) + degrees2;
    tools().canvas.resize(state().original.height, state().original.width, {
      applyZoom: false,
      resizeHelper: false
    });
    this.storeObjectsRelationToHelper();
    this.straightenAnchor.rotate(newAngle);
    this.straightenAnchor.data.rotateAngle = currentRotateAngle + degrees2;
    this.straightenAnchor.center();
    this.transformObjectsBasedOnHelper();
    tools().frame.resize(tools().frame.active.currentSizeInPercent);
    requestAnimationFrame(() => {
      tools().zoom.fitToScreen();
    });
  }
  getImageScale(angle, image) {
    angle = fabric.fabric.util.degreesToRadians(angle);
    const w2 = state().original.width;
    const h2 = state().original.height;
    const cw = w2 / 2;
    const ch = h2 / 2;
    const iw = image.width / 2;
    const ih = image.height / 2;
    const dist = Math.sqrt(cw ** 2 + ch ** 2);
    const diagAngle = Math.asin(ch / dist);
    let a1 = (angle % (Math.PI * 2) + Math.PI * 4) % (Math.PI * 2);
    if (a1 > Math.PI) {
      a1 -= Math.PI;
    }
    if (a1 > Math.PI / 2 && a1 <= Math.PI) {
      a1 = Math.PI / 2 - (a1 - Math.PI / 2);
    }
    const ang1 = Math.PI / 2 - diagAngle - Math.abs(a1);
    const ang2 = Math.abs(diagAngle - Math.abs(a1));
    const dist1 = Math.cos(ang1) * dist;
    const dist2 = Math.cos(ang2) * dist;
    return Math.max(dist2 / iw, dist1 / ih);
  }
  storeObjectsRelationToHelper() {
    tools().objects.getAll().forEach((o2) => {
      if (o2 !== this.straightenAnchor) {
        const relationToCanvas = fabric.fabric.util.multiplyTransformMatrices(fabric.fabric.util.invertTransform(this.straightenAnchor.calcTransformMatrix()), o2.calcTransformMatrix());
        o2.data = __spreadProps(__spreadValues({}, o2.data), {
          relationToCanvas
        });
      }
    });
  }
  transformObjectsBasedOnHelper() {
    tools().objects.getAll().forEach((o2) => {
      if (o2.data.relationToCanvas) {
        const newTransform = fabric.fabric.util.multiplyTransformMatrices(this.straightenAnchor.calcTransformMatrix(), o2.data.relationToCanvas);
        const opt = fabric.fabric.util.qrDecompose(newTransform);
        o2.set({
          flipX: false,
          flipY: false
        });
        o2.setPositionByOrigin({
          x: opt.translateX,
          y: opt.translateY
        }, "center", "center");
        o2.set(opt);
        o2.setCoords();
        o2.data.relationToCanvas = null;
      }
    });
  }
  resetStraightenAnchor() {
    const oldHelper = this.straightenAnchor;
    if (oldHelper) {
      fabricCanvas().remove(oldHelper);
    }
    const newHelper = new fabric.fabric.Rect(__spreadProps(__spreadValues({}, staticObjectConfig), {
      name: ObjectName.StraightenAnchor,
      visible: false,
      width: state().original.width,
      height: state().original.height,
      data: {
        pixieInternal: true,
        straightenAngle: 0,
        rotateAngle: 0
      }
    }));
    fabricCanvas().add(newHelper);
    newHelper.viewportCenter();
  }
}
function initTools(canvasEl) {
  const fabric2 = initFabric(canvasEl);
  state().editor.fabric = fabric2;
  useStore$1.setState({
    fabric: fabric2
  });
  state().editor.tools = {
    canvas: new PixieCanvas(),
    objects: new ObjectTool(),
    zoom: new ZoomTool(),
    history: new HistoryTool(),
    filter: new FilterTool(),
    resize: new ResizeTool(),
    crop: new CropTool(),
    merge: new MergeTool(),
    shape: new ShapeTool(),
    frame: new FrameTool(),
    text: new TextTool(),
    draw: new DrawTool(),
    transform: new TransformTool(),
    import: new ImportTool(),
    watermark: new WatermarkTool(),
    export: new ExportTool(),
    corners: new CornersTool()
  };
}
function observeSize(el, callback) {
  const observer = new ResizeObserver((entries) => {
    const rect = entries[0].contentRect;
    callback({
      width: rect.width,
      height: rect.height
    });
  });
  observer.observe(el);
  return () => observer.unobserve(el);
}
function getBoundingClientRect(el) {
  const rect = el.getBoundingClientRect();
  return {
    top: rect.top,
    right: rect.right,
    bottom: rect.bottom,
    left: rect.left,
    width: rect.width,
    height: rect.height
  };
}
var colorString$1 = { exports: {} };
var colorName = {
  "aliceblue": [240, 248, 255],
  "antiquewhite": [250, 235, 215],
  "aqua": [0, 255, 255],
  "aquamarine": [127, 255, 212],
  "azure": [240, 255, 255],
  "beige": [245, 245, 220],
  "bisque": [255, 228, 196],
  "black": [0, 0, 0],
  "blanchedalmond": [255, 235, 205],
  "blue": [0, 0, 255],
  "blueviolet": [138, 43, 226],
  "brown": [165, 42, 42],
  "burlywood": [222, 184, 135],
  "cadetblue": [95, 158, 160],
  "chartreuse": [127, 255, 0],
  "chocolate": [210, 105, 30],
  "coral": [255, 127, 80],
  "cornflowerblue": [100, 149, 237],
  "cornsilk": [255, 248, 220],
  "crimson": [220, 20, 60],
  "cyan": [0, 255, 255],
  "darkblue": [0, 0, 139],
  "darkcyan": [0, 139, 139],
  "darkgoldenrod": [184, 134, 11],
  "darkgray": [169, 169, 169],
  "darkgreen": [0, 100, 0],
  "darkgrey": [169, 169, 169],
  "darkkhaki": [189, 183, 107],
  "darkmagenta": [139, 0, 139],
  "darkolivegreen": [85, 107, 47],
  "darkorange": [255, 140, 0],
  "darkorchid": [153, 50, 204],
  "darkred": [139, 0, 0],
  "darksalmon": [233, 150, 122],
  "darkseagreen": [143, 188, 143],
  "darkslateblue": [72, 61, 139],
  "darkslategray": [47, 79, 79],
  "darkslategrey": [47, 79, 79],
  "darkturquoise": [0, 206, 209],
  "darkviolet": [148, 0, 211],
  "deeppink": [255, 20, 147],
  "deepskyblue": [0, 191, 255],
  "dimgray": [105, 105, 105],
  "dimgrey": [105, 105, 105],
  "dodgerblue": [30, 144, 255],
  "firebrick": [178, 34, 34],
  "floralwhite": [255, 250, 240],
  "forestgreen": [34, 139, 34],
  "fuchsia": [255, 0, 255],
  "gainsboro": [220, 220, 220],
  "ghostwhite": [248, 248, 255],
  "gold": [255, 215, 0],
  "goldenrod": [218, 165, 32],
  "gray": [128, 128, 128],
  "green": [0, 128, 0],
  "greenyellow": [173, 255, 47],
  "grey": [128, 128, 128],
  "honeydew": [240, 255, 240],
  "hotpink": [255, 105, 180],
  "indianred": [205, 92, 92],
  "indigo": [75, 0, 130],
  "ivory": [255, 255, 240],
  "khaki": [240, 230, 140],
  "lavender": [230, 230, 250],
  "lavenderblush": [255, 240, 245],
  "lawngreen": [124, 252, 0],
  "lemonchiffon": [255, 250, 205],
  "lightblue": [173, 216, 230],
  "lightcoral": [240, 128, 128],
  "lightcyan": [224, 255, 255],
  "lightgoldenrodyellow": [250, 250, 210],
  "lightgray": [211, 211, 211],
  "lightgreen": [144, 238, 144],
  "lightgrey": [211, 211, 211],
  "lightpink": [255, 182, 193],
  "lightsalmon": [255, 160, 122],
  "lightseagreen": [32, 178, 170],
  "lightskyblue": [135, 206, 250],
  "lightslategray": [119, 136, 153],
  "lightslategrey": [119, 136, 153],
  "lightsteelblue": [176, 196, 222],
  "lightyellow": [255, 255, 224],
  "lime": [0, 255, 0],
  "limegreen": [50, 205, 50],
  "linen": [250, 240, 230],
  "magenta": [255, 0, 255],
  "maroon": [128, 0, 0],
  "mediumaquamarine": [102, 205, 170],
  "mediumblue": [0, 0, 205],
  "mediumorchid": [186, 85, 211],
  "mediumpurple": [147, 112, 219],
  "mediumseagreen": [60, 179, 113],
  "mediumslateblue": [123, 104, 238],
  "mediumspringgreen": [0, 250, 154],
  "mediumturquoise": [72, 209, 204],
  "mediumvioletred": [199, 21, 133],
  "midnightblue": [25, 25, 112],
  "mintcream": [245, 255, 250],
  "mistyrose": [255, 228, 225],
  "moccasin": [255, 228, 181],
  "navajowhite": [255, 222, 173],
  "navy": [0, 0, 128],
  "oldlace": [253, 245, 230],
  "olive": [128, 128, 0],
  "olivedrab": [107, 142, 35],
  "orange": [255, 165, 0],
  "orangered": [255, 69, 0],
  "orchid": [218, 112, 214],
  "palegoldenrod": [238, 232, 170],
  "palegreen": [152, 251, 152],
  "paleturquoise": [175, 238, 238],
  "palevioletred": [219, 112, 147],
  "papayawhip": [255, 239, 213],
  "peachpuff": [255, 218, 185],
  "peru": [205, 133, 63],
  "pink": [255, 192, 203],
  "plum": [221, 160, 221],
  "powderblue": [176, 224, 230],
  "purple": [128, 0, 128],
  "rebeccapurple": [102, 51, 153],
  "red": [255, 0, 0],
  "rosybrown": [188, 143, 143],
  "royalblue": [65, 105, 225],
  "saddlebrown": [139, 69, 19],
  "salmon": [250, 128, 114],
  "sandybrown": [244, 164, 96],
  "seagreen": [46, 139, 87],
  "seashell": [255, 245, 238],
  "sienna": [160, 82, 45],
  "silver": [192, 192, 192],
  "skyblue": [135, 206, 235],
  "slateblue": [106, 90, 205],
  "slategray": [112, 128, 144],
  "slategrey": [112, 128, 144],
  "snow": [255, 250, 250],
  "springgreen": [0, 255, 127],
  "steelblue": [70, 130, 180],
  "tan": [210, 180, 140],
  "teal": [0, 128, 128],
  "thistle": [216, 191, 216],
  "tomato": [255, 99, 71],
  "turquoise": [64, 224, 208],
  "violet": [238, 130, 238],
  "wheat": [245, 222, 179],
  "white": [255, 255, 255],
  "whitesmoke": [245, 245, 245],
  "yellow": [255, 255, 0],
  "yellowgreen": [154, 205, 50]
};
var simpleSwizzle = { exports: {} };
var isArrayish$1 = function isArrayish(obj) {
  if (!obj || typeof obj === "string") {
    return false;
  }
  return obj instanceof Array || Array.isArray(obj) || obj.length >= 0 && (obj.splice instanceof Function || Object.getOwnPropertyDescriptor(obj, obj.length - 1) && obj.constructor.name !== "String");
};
var isArrayish2 = isArrayish$1;
var concat = Array.prototype.concat;
var slice = Array.prototype.slice;
var swizzle$1 = simpleSwizzle.exports = function swizzle(args) {
  var results = [];
  for (var i2 = 0, len = args.length; i2 < len; i2++) {
    var arg = args[i2];
    if (isArrayish2(arg)) {
      results = concat.call(results, slice.call(arg));
    } else {
      results.push(arg);
    }
  }
  return results;
};
swizzle$1.wrap = function(fn2) {
  return function() {
    return fn2(swizzle$1(arguments));
  };
};
var colorNames = colorName;
var swizzle2 = simpleSwizzle.exports;
var hasOwnProperty = Object.hasOwnProperty;
var reverseNames = {};
for (var name in colorNames) {
  if (hasOwnProperty.call(colorNames, name)) {
    reverseNames[colorNames[name]] = name;
  }
}
var cs = colorString$1.exports = {
  to: {},
  get: {}
};
cs.get = function(string) {
  var prefix2 = string.substring(0, 3).toLowerCase();
  var val;
  var model;
  switch (prefix2) {
    case "hsl":
      val = cs.get.hsl(string);
      model = "hsl";
      break;
    case "hwb":
      val = cs.get.hwb(string);
      model = "hwb";
      break;
    default:
      val = cs.get.rgb(string);
      model = "rgb";
      break;
  }
  if (!val) {
    return null;
  }
  return { model, value: val };
};
cs.get.rgb = function(string) {
  if (!string) {
    return null;
  }
  var abbr = /^#([a-f0-9]{3,4})$/i;
  var hex2 = /^#([a-f0-9]{6})([a-f0-9]{2})?$/i;
  var rgba2 = /^rgba?\(\s*([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/;
  var per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/;
  var keyword = /^(\w+)$/;
  var rgb = [0, 0, 0, 1];
  var match;
  var i2;
  var hexAlpha;
  if (match = string.match(hex2)) {
    hexAlpha = match[2];
    match = match[1];
    for (i2 = 0; i2 < 3; i2++) {
      var i22 = i2 * 2;
      rgb[i2] = parseInt(match.slice(i22, i22 + 2), 16);
    }
    if (hexAlpha) {
      rgb[3] = parseInt(hexAlpha, 16) / 255;
    }
  } else if (match = string.match(abbr)) {
    match = match[1];
    hexAlpha = match[3];
    for (i2 = 0; i2 < 3; i2++) {
      rgb[i2] = parseInt(match[i2] + match[i2], 16);
    }
    if (hexAlpha) {
      rgb[3] = parseInt(hexAlpha + hexAlpha, 16) / 255;
    }
  } else if (match = string.match(rgba2)) {
    for (i2 = 0; i2 < 3; i2++) {
      rgb[i2] = parseInt(match[i2 + 1], 0);
    }
    if (match[4]) {
      if (match[5]) {
        rgb[3] = parseFloat(match[4]) * 0.01;
      } else {
        rgb[3] = parseFloat(match[4]);
      }
    }
  } else if (match = string.match(per)) {
    for (i2 = 0; i2 < 3; i2++) {
      rgb[i2] = Math.round(parseFloat(match[i2 + 1]) * 2.55);
    }
    if (match[4]) {
      if (match[5]) {
        rgb[3] = parseFloat(match[4]) * 0.01;
      } else {
        rgb[3] = parseFloat(match[4]);
      }
    }
  } else if (match = string.match(keyword)) {
    if (match[1] === "transparent") {
      return [0, 0, 0, 0];
    }
    if (!hasOwnProperty.call(colorNames, match[1])) {
      return null;
    }
    rgb = colorNames[match[1]];
    rgb[3] = 1;
    return rgb;
  } else {
    return null;
  }
  for (i2 = 0; i2 < 3; i2++) {
    rgb[i2] = clamp$1(rgb[i2], 0, 255);
  }
  rgb[3] = clamp$1(rgb[3], 0, 1);
  return rgb;
};
cs.get.hsl = function(string) {
  if (!string) {
    return null;
  }
  var hsl = /^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d\.]+)%\s*,?\s*([+-]?[\d\.]+)%\s*(?:[,|\/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/;
  var match = string.match(hsl);
  if (match) {
    var alpha2 = parseFloat(match[4]);
    var h2 = (parseFloat(match[1]) % 360 + 360) % 360;
    var s2 = clamp$1(parseFloat(match[2]), 0, 100);
    var l2 = clamp$1(parseFloat(match[3]), 0, 100);
    var a2 = clamp$1(isNaN(alpha2) ? 1 : alpha2, 0, 1);
    return [h2, s2, l2, a2];
  }
  return null;
};
cs.get.hwb = function(string) {
  if (!string) {
    return null;
  }
  var hwb = /^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/;
  var match = string.match(hwb);
  if (match) {
    var alpha2 = parseFloat(match[4]);
    var h2 = (parseFloat(match[1]) % 360 + 360) % 360;
    var w2 = clamp$1(parseFloat(match[2]), 0, 100);
    var b2 = clamp$1(parseFloat(match[3]), 0, 100);
    var a2 = clamp$1(isNaN(alpha2) ? 1 : alpha2, 0, 1);
    return [h2, w2, b2, a2];
  }
  return null;
};
cs.to.hex = function() {
  var rgba2 = swizzle2(arguments);
  return "#" + hexDouble(rgba2[0]) + hexDouble(rgba2[1]) + hexDouble(rgba2[2]) + (rgba2[3] < 1 ? hexDouble(Math.round(rgba2[3] * 255)) : "");
};
cs.to.rgb = function() {
  var rgba2 = swizzle2(arguments);
  return rgba2.length < 4 || rgba2[3] === 1 ? "rgb(" + Math.round(rgba2[0]) + ", " + Math.round(rgba2[1]) + ", " + Math.round(rgba2[2]) + ")" : "rgba(" + Math.round(rgba2[0]) + ", " + Math.round(rgba2[1]) + ", " + Math.round(rgba2[2]) + ", " + rgba2[3] + ")";
};
cs.to.rgb.percent = function() {
  var rgba2 = swizzle2(arguments);
  var r2 = Math.round(rgba2[0] / 255 * 100);
  var g2 = Math.round(rgba2[1] / 255 * 100);
  var b2 = Math.round(rgba2[2] / 255 * 100);
  return rgba2.length < 4 || rgba2[3] === 1 ? "rgb(" + r2 + "%, " + g2 + "%, " + b2 + "%)" : "rgba(" + r2 + "%, " + g2 + "%, " + b2 + "%, " + rgba2[3] + ")";
};
cs.to.hsl = function() {
  var hsla2 = swizzle2(arguments);
  return hsla2.length < 4 || hsla2[3] === 1 ? "hsl(" + hsla2[0] + ", " + hsla2[1] + "%, " + hsla2[2] + "%)" : "hsla(" + hsla2[0] + ", " + hsla2[1] + "%, " + hsla2[2] + "%, " + hsla2[3] + ")";
};
cs.to.hwb = function() {
  var hwba = swizzle2(arguments);
  var a2 = "";
  if (hwba.length >= 4 && hwba[3] !== 1) {
    a2 = ", " + hwba[3];
  }
  return "hwb(" + hwba[0] + ", " + hwba[1] + "%, " + hwba[2] + "%" + a2 + ")";
};
cs.to.keyword = function(rgb) {
  return reverseNames[rgb.slice(0, 3)];
};
function clamp$1(num, min, max) {
  return Math.min(Math.max(min, num), max);
}
function hexDouble(num) {
  var str = Math.round(num).toString(16).toUpperCase();
  return str.length < 2 ? "0" + str : str;
}
const cssKeywords = colorName;
const reverseKeywords = {};
for (const key of Object.keys(cssKeywords)) {
  reverseKeywords[cssKeywords[key]] = key;
}
const convert$2 = {
  rgb: { channels: 3, labels: "rgb" },
  hsl: { channels: 3, labels: "hsl" },
  hsv: { channels: 3, labels: "hsv" },
  hwb: { channels: 3, labels: "hwb" },
  cmyk: { channels: 4, labels: "cmyk" },
  xyz: { channels: 3, labels: "xyz" },
  lab: { channels: 3, labels: "lab" },
  lch: { channels: 3, labels: "lch" },
  hex: { channels: 1, labels: ["hex"] },
  keyword: { channels: 1, labels: ["keyword"] },
  ansi16: { channels: 1, labels: ["ansi16"] },
  ansi256: { channels: 1, labels: ["ansi256"] },
  hcg: { channels: 3, labels: ["h", "c", "g"] },
  apple: { channels: 3, labels: ["r16", "g16", "b16"] },
  gray: { channels: 1, labels: ["gray"] }
};
var conversions$2 = convert$2;
for (const model of Object.keys(convert$2)) {
  if (!("channels" in convert$2[model])) {
    throw new Error("missing channels property: " + model);
  }
  if (!("labels" in convert$2[model])) {
    throw new Error("missing channel labels property: " + model);
  }
  if (convert$2[model].labels.length !== convert$2[model].channels) {
    throw new Error("channel and label counts mismatch: " + model);
  }
  const { channels, labels } = convert$2[model];
  delete convert$2[model].channels;
  delete convert$2[model].labels;
  Object.defineProperty(convert$2[model], "channels", { value: channels });
  Object.defineProperty(convert$2[model], "labels", { value: labels });
}
convert$2.rgb.hsl = function(rgb) {
  const r2 = rgb[0] / 255;
  const g2 = rgb[1] / 255;
  const b2 = rgb[2] / 255;
  const min = Math.min(r2, g2, b2);
  const max = Math.max(r2, g2, b2);
  const delta = max - min;
  let h2;
  let s2;
  if (max === min) {
    h2 = 0;
  } else if (r2 === max) {
    h2 = (g2 - b2) / delta;
  } else if (g2 === max) {
    h2 = 2 + (b2 - r2) / delta;
  } else if (b2 === max) {
    h2 = 4 + (r2 - g2) / delta;
  }
  h2 = Math.min(h2 * 60, 360);
  if (h2 < 0) {
    h2 += 360;
  }
  const l2 = (min + max) / 2;
  if (max === min) {
    s2 = 0;
  } else if (l2 <= 0.5) {
    s2 = delta / (max + min);
  } else {
    s2 = delta / (2 - max - min);
  }
  return [h2, s2 * 100, l2 * 100];
};
convert$2.rgb.hsv = function(rgb) {
  let rdif;
  let gdif;
  let bdif;
  let h2;
  let s2;
  const r2 = rgb[0] / 255;
  const g2 = rgb[1] / 255;
  const b2 = rgb[2] / 255;
  const v2 = Math.max(r2, g2, b2);
  const diff = v2 - Math.min(r2, g2, b2);
  const diffc = function(c2) {
    return (v2 - c2) / 6 / diff + 1 / 2;
  };
  if (diff === 0) {
    h2 = 0;
    s2 = 0;
  } else {
    s2 = diff / v2;
    rdif = diffc(r2);
    gdif = diffc(g2);
    bdif = diffc(b2);
    if (r2 === v2) {
      h2 = bdif - gdif;
    } else if (g2 === v2) {
      h2 = 1 / 3 + rdif - bdif;
    } else if (b2 === v2) {
      h2 = 2 / 3 + gdif - rdif;
    }
    if (h2 < 0) {
      h2 += 1;
    } else if (h2 > 1) {
      h2 -= 1;
    }
  }
  return [
    h2 * 360,
    s2 * 100,
    v2 * 100
  ];
};
convert$2.rgb.hwb = function(rgb) {
  const r2 = rgb[0];
  const g2 = rgb[1];
  let b2 = rgb[2];
  const h2 = convert$2.rgb.hsl(rgb)[0];
  const w2 = 1 / 255 * Math.min(r2, Math.min(g2, b2));
  b2 = 1 - 1 / 255 * Math.max(r2, Math.max(g2, b2));
  return [h2, w2 * 100, b2 * 100];
};
convert$2.rgb.cmyk = function(rgb) {
  const r2 = rgb[0] / 255;
  const g2 = rgb[1] / 255;
  const b2 = rgb[2] / 255;
  const k2 = Math.min(1 - r2, 1 - g2, 1 - b2);
  const c2 = (1 - r2 - k2) / (1 - k2) || 0;
  const m2 = (1 - g2 - k2) / (1 - k2) || 0;
  const y2 = (1 - b2 - k2) / (1 - k2) || 0;
  return [c2 * 100, m2 * 100, y2 * 100, k2 * 100];
};
function comparativeDistance(x2, y2) {
  return (x2[0] - y2[0]) ** 2 + (x2[1] - y2[1]) ** 2 + (x2[2] - y2[2]) ** 2;
}
convert$2.rgb.keyword = function(rgb) {
  const reversed = reverseKeywords[rgb];
  if (reversed) {
    return reversed;
  }
  let currentClosestDistance = Infinity;
  let currentClosestKeyword;
  for (const keyword of Object.keys(cssKeywords)) {
    const value = cssKeywords[keyword];
    const distance = comparativeDistance(rgb, value);
    if (distance < currentClosestDistance) {
      currentClosestDistance = distance;
      currentClosestKeyword = keyword;
    }
  }
  return currentClosestKeyword;
};
convert$2.keyword.rgb = function(keyword) {
  return cssKeywords[keyword];
};
convert$2.rgb.xyz = function(rgb) {
  let r2 = rgb[0] / 255;
  let g2 = rgb[1] / 255;
  let b2 = rgb[2] / 255;
  r2 = r2 > 0.04045 ? ((r2 + 0.055) / 1.055) ** 2.4 : r2 / 12.92;
  g2 = g2 > 0.04045 ? ((g2 + 0.055) / 1.055) ** 2.4 : g2 / 12.92;
  b2 = b2 > 0.04045 ? ((b2 + 0.055) / 1.055) ** 2.4 : b2 / 12.92;
  const x2 = r2 * 0.4124 + g2 * 0.3576 + b2 * 0.1805;
  const y2 = r2 * 0.2126 + g2 * 0.7152 + b2 * 0.0722;
  const z2 = r2 * 0.0193 + g2 * 0.1192 + b2 * 0.9505;
  return [x2 * 100, y2 * 100, z2 * 100];
};
convert$2.rgb.lab = function(rgb) {
  const xyz = convert$2.rgb.xyz(rgb);
  let x2 = xyz[0];
  let y2 = xyz[1];
  let z2 = xyz[2];
  x2 /= 95.047;
  y2 /= 100;
  z2 /= 108.883;
  x2 = x2 > 8856e-6 ? x2 ** (1 / 3) : 7.787 * x2 + 16 / 116;
  y2 = y2 > 8856e-6 ? y2 ** (1 / 3) : 7.787 * y2 + 16 / 116;
  z2 = z2 > 8856e-6 ? z2 ** (1 / 3) : 7.787 * z2 + 16 / 116;
  const l2 = 116 * y2 - 16;
  const a2 = 500 * (x2 - y2);
  const b2 = 200 * (y2 - z2);
  return [l2, a2, b2];
};
convert$2.hsl.rgb = function(hsl) {
  const h2 = hsl[0] / 360;
  const s2 = hsl[1] / 100;
  const l2 = hsl[2] / 100;
  let t2;
  let t3;
  let val;
  if (s2 === 0) {
    val = l2 * 255;
    return [val, val, val];
  }
  if (l2 < 0.5) {
    t2 = l2 * (1 + s2);
  } else {
    t2 = l2 + s2 - l2 * s2;
  }
  const t1 = 2 * l2 - t2;
  const rgb = [0, 0, 0];
  for (let i2 = 0; i2 < 3; i2++) {
    t3 = h2 + 1 / 3 * -(i2 - 1);
    if (t3 < 0) {
      t3++;
    }
    if (t3 > 1) {
      t3--;
    }
    if (6 * t3 < 1) {
      val = t1 + (t2 - t1) * 6 * t3;
    } else if (2 * t3 < 1) {
      val = t2;
    } else if (3 * t3 < 2) {
      val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
    } else {
      val = t1;
    }
    rgb[i2] = val * 255;
  }
  return rgb;
};
convert$2.hsl.hsv = function(hsl) {
  const h2 = hsl[0];
  let s2 = hsl[1] / 100;
  let l2 = hsl[2] / 100;
  let smin = s2;
  const lmin = Math.max(l2, 0.01);
  l2 *= 2;
  s2 *= l2 <= 1 ? l2 : 2 - l2;
  smin *= lmin <= 1 ? lmin : 2 - lmin;
  const v2 = (l2 + s2) / 2;
  const sv = l2 === 0 ? 2 * smin / (lmin + smin) : 2 * s2 / (l2 + s2);
  return [h2, sv * 100, v2 * 100];
};
convert$2.hsv.rgb = function(hsv) {
  const h2 = hsv[0] / 60;
  const s2 = hsv[1] / 100;
  let v2 = hsv[2] / 100;
  const hi = Math.floor(h2) % 6;
  const f2 = h2 - Math.floor(h2);
  const p2 = 255 * v2 * (1 - s2);
  const q2 = 255 * v2 * (1 - s2 * f2);
  const t2 = 255 * v2 * (1 - s2 * (1 - f2));
  v2 *= 255;
  switch (hi) {
    case 0:
      return [v2, t2, p2];
    case 1:
      return [q2, v2, p2];
    case 2:
      return [p2, v2, t2];
    case 3:
      return [p2, q2, v2];
    case 4:
      return [t2, p2, v2];
    case 5:
      return [v2, p2, q2];
  }
};
convert$2.hsv.hsl = function(hsv) {
  const h2 = hsv[0];
  const s2 = hsv[1] / 100;
  const v2 = hsv[2] / 100;
  const vmin = Math.max(v2, 0.01);
  let sl;
  let l2;
  l2 = (2 - s2) * v2;
  const lmin = (2 - s2) * vmin;
  sl = s2 * vmin;
  sl /= lmin <= 1 ? lmin : 2 - lmin;
  sl = sl || 0;
  l2 /= 2;
  return [h2, sl * 100, l2 * 100];
};
convert$2.hwb.rgb = function(hwb) {
  const h2 = hwb[0] / 360;
  let wh = hwb[1] / 100;
  let bl = hwb[2] / 100;
  const ratio = wh + bl;
  let f2;
  if (ratio > 1) {
    wh /= ratio;
    bl /= ratio;
  }
  const i2 = Math.floor(6 * h2);
  const v2 = 1 - bl;
  f2 = 6 * h2 - i2;
  if ((i2 & 1) !== 0) {
    f2 = 1 - f2;
  }
  const n2 = wh + f2 * (v2 - wh);
  let r2;
  let g2;
  let b2;
  switch (i2) {
    default:
    case 6:
    case 0:
      r2 = v2;
      g2 = n2;
      b2 = wh;
      break;
    case 1:
      r2 = n2;
      g2 = v2;
      b2 = wh;
      break;
    case 2:
      r2 = wh;
      g2 = v2;
      b2 = n2;
      break;
    case 3:
      r2 = wh;
      g2 = n2;
      b2 = v2;
      break;
    case 4:
      r2 = n2;
      g2 = wh;
      b2 = v2;
      break;
    case 5:
      r2 = v2;
      g2 = wh;
      b2 = n2;
      break;
  }
  return [r2 * 255, g2 * 255, b2 * 255];
};
convert$2.cmyk.rgb = function(cmyk) {
  const c2 = cmyk[0] / 100;
  const m2 = cmyk[1] / 100;
  const y2 = cmyk[2] / 100;
  const k2 = cmyk[3] / 100;
  const r2 = 1 - Math.min(1, c2 * (1 - k2) + k2);
  const g2 = 1 - Math.min(1, m2 * (1 - k2) + k2);
  const b2 = 1 - Math.min(1, y2 * (1 - k2) + k2);
  return [r2 * 255, g2 * 255, b2 * 255];
};
convert$2.xyz.rgb = function(xyz) {
  const x2 = xyz[0] / 100;
  const y2 = xyz[1] / 100;
  const z2 = xyz[2] / 100;
  let r2;
  let g2;
  let b2;
  r2 = x2 * 3.2406 + y2 * -1.5372 + z2 * -0.4986;
  g2 = x2 * -0.9689 + y2 * 1.8758 + z2 * 0.0415;
  b2 = x2 * 0.0557 + y2 * -0.204 + z2 * 1.057;
  r2 = r2 > 31308e-7 ? 1.055 * r2 ** (1 / 2.4) - 0.055 : r2 * 12.92;
  g2 = g2 > 31308e-7 ? 1.055 * g2 ** (1 / 2.4) - 0.055 : g2 * 12.92;
  b2 = b2 > 31308e-7 ? 1.055 * b2 ** (1 / 2.4) - 0.055 : b2 * 12.92;
  r2 = Math.min(Math.max(0, r2), 1);
  g2 = Math.min(Math.max(0, g2), 1);
  b2 = Math.min(Math.max(0, b2), 1);
  return [r2 * 255, g2 * 255, b2 * 255];
};
convert$2.xyz.lab = function(xyz) {
  let x2 = xyz[0];
  let y2 = xyz[1];
  let z2 = xyz[2];
  x2 /= 95.047;
  y2 /= 100;
  z2 /= 108.883;
  x2 = x2 > 8856e-6 ? x2 ** (1 / 3) : 7.787 * x2 + 16 / 116;
  y2 = y2 > 8856e-6 ? y2 ** (1 / 3) : 7.787 * y2 + 16 / 116;
  z2 = z2 > 8856e-6 ? z2 ** (1 / 3) : 7.787 * z2 + 16 / 116;
  const l2 = 116 * y2 - 16;
  const a2 = 500 * (x2 - y2);
  const b2 = 200 * (y2 - z2);
  return [l2, a2, b2];
};
convert$2.lab.xyz = function(lab) {
  const l2 = lab[0];
  const a2 = lab[1];
  const b2 = lab[2];
  let x2;
  let y2;
  let z2;
  y2 = (l2 + 16) / 116;
  x2 = a2 / 500 + y2;
  z2 = y2 - b2 / 200;
  const y22 = y2 ** 3;
  const x22 = x2 ** 3;
  const z22 = z2 ** 3;
  y2 = y22 > 8856e-6 ? y22 : (y2 - 16 / 116) / 7.787;
  x2 = x22 > 8856e-6 ? x22 : (x2 - 16 / 116) / 7.787;
  z2 = z22 > 8856e-6 ? z22 : (z2 - 16 / 116) / 7.787;
  x2 *= 95.047;
  y2 *= 100;
  z2 *= 108.883;
  return [x2, y2, z2];
};
convert$2.lab.lch = function(lab) {
  const l2 = lab[0];
  const a2 = lab[1];
  const b2 = lab[2];
  let h2;
  const hr = Math.atan2(b2, a2);
  h2 = hr * 360 / 2 / Math.PI;
  if (h2 < 0) {
    h2 += 360;
  }
  const c2 = Math.sqrt(a2 * a2 + b2 * b2);
  return [l2, c2, h2];
};
convert$2.lch.lab = function(lch) {
  const l2 = lch[0];
  const c2 = lch[1];
  const h2 = lch[2];
  const hr = h2 / 360 * 2 * Math.PI;
  const a2 = c2 * Math.cos(hr);
  const b2 = c2 * Math.sin(hr);
  return [l2, a2, b2];
};
convert$2.rgb.ansi16 = function(args, saturation = null) {
  const [r2, g2, b2] = args;
  let value = saturation === null ? convert$2.rgb.hsv(args)[2] : saturation;
  value = Math.round(value / 50);
  if (value === 0) {
    return 30;
  }
  let ansi = 30 + (Math.round(b2 / 255) << 2 | Math.round(g2 / 255) << 1 | Math.round(r2 / 255));
  if (value === 2) {
    ansi += 60;
  }
  return ansi;
};
convert$2.hsv.ansi16 = function(args) {
  return convert$2.rgb.ansi16(convert$2.hsv.rgb(args), args[2]);
};
convert$2.rgb.ansi256 = function(args) {
  const r2 = args[0];
  const g2 = args[1];
  const b2 = args[2];
  if (r2 === g2 && g2 === b2) {
    if (r2 < 8) {
      return 16;
    }
    if (r2 > 248) {
      return 231;
    }
    return Math.round((r2 - 8) / 247 * 24) + 232;
  }
  const ansi = 16 + 36 * Math.round(r2 / 255 * 5) + 6 * Math.round(g2 / 255 * 5) + Math.round(b2 / 255 * 5);
  return ansi;
};
convert$2.ansi16.rgb = function(args) {
  let color2 = args % 10;
  if (color2 === 0 || color2 === 7) {
    if (args > 50) {
      color2 += 3.5;
    }
    color2 = color2 / 10.5 * 255;
    return [color2, color2, color2];
  }
  const mult = (~~(args > 50) + 1) * 0.5;
  const r2 = (color2 & 1) * mult * 255;
  const g2 = (color2 >> 1 & 1) * mult * 255;
  const b2 = (color2 >> 2 & 1) * mult * 255;
  return [r2, g2, b2];
};
convert$2.ansi256.rgb = function(args) {
  if (args >= 232) {
    const c2 = (args - 232) * 10 + 8;
    return [c2, c2, c2];
  }
  args -= 16;
  let rem;
  const r2 = Math.floor(args / 36) / 5 * 255;
  const g2 = Math.floor((rem = args % 36) / 6) / 5 * 255;
  const b2 = rem % 6 / 5 * 255;
  return [r2, g2, b2];
};
convert$2.rgb.hex = function(args) {
  const integer = ((Math.round(args[0]) & 255) << 16) + ((Math.round(args[1]) & 255) << 8) + (Math.round(args[2]) & 255);
  const string = integer.toString(16).toUpperCase();
  return "000000".substring(string.length) + string;
};
convert$2.hex.rgb = function(args) {
  const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
  if (!match) {
    return [0, 0, 0];
  }
  let colorString2 = match[0];
  if (match[0].length === 3) {
    colorString2 = colorString2.split("").map((char) => {
      return char + char;
    }).join("");
  }
  const integer = parseInt(colorString2, 16);
  const r2 = integer >> 16 & 255;
  const g2 = integer >> 8 & 255;
  const b2 = integer & 255;
  return [r2, g2, b2];
};
convert$2.rgb.hcg = function(rgb) {
  const r2 = rgb[0] / 255;
  const g2 = rgb[1] / 255;
  const b2 = rgb[2] / 255;
  const max = Math.max(Math.max(r2, g2), b2);
  const min = Math.min(Math.min(r2, g2), b2);
  const chroma = max - min;
  let grayscale;
  let hue;
  if (chroma < 1) {
    grayscale = min / (1 - chroma);
  } else {
    grayscale = 0;
  }
  if (chroma <= 0) {
    hue = 0;
  } else if (max === r2) {
    hue = (g2 - b2) / chroma % 6;
  } else if (max === g2) {
    hue = 2 + (b2 - r2) / chroma;
  } else {
    hue = 4 + (r2 - g2) / chroma;
  }
  hue /= 6;
  hue %= 1;
  return [hue * 360, chroma * 100, grayscale * 100];
};
convert$2.hsl.hcg = function(hsl) {
  const s2 = hsl[1] / 100;
  const l2 = hsl[2] / 100;
  const c2 = l2 < 0.5 ? 2 * s2 * l2 : 2 * s2 * (1 - l2);
  let f2 = 0;
  if (c2 < 1) {
    f2 = (l2 - 0.5 * c2) / (1 - c2);
  }
  return [hsl[0], c2 * 100, f2 * 100];
};
convert$2.hsv.hcg = function(hsv) {
  const s2 = hsv[1] / 100;
  const v2 = hsv[2] / 100;
  const c2 = s2 * v2;
  let f2 = 0;
  if (c2 < 1) {
    f2 = (v2 - c2) / (1 - c2);
  }
  return [hsv[0], c2 * 100, f2 * 100];
};
convert$2.hcg.rgb = function(hcg) {
  const h2 = hcg[0] / 360;
  const c2 = hcg[1] / 100;
  const g2 = hcg[2] / 100;
  if (c2 === 0) {
    return [g2 * 255, g2 * 255, g2 * 255];
  }
  const pure = [0, 0, 0];
  const hi = h2 % 1 * 6;
  const v2 = hi % 1;
  const w2 = 1 - v2;
  let mg = 0;
  switch (Math.floor(hi)) {
    case 0:
      pure[0] = 1;
      pure[1] = v2;
      pure[2] = 0;
      break;
    case 1:
      pure[0] = w2;
      pure[1] = 1;
      pure[2] = 0;
      break;
    case 2:
      pure[0] = 0;
      pure[1] = 1;
      pure[2] = v2;
      break;
    case 3:
      pure[0] = 0;
      pure[1] = w2;
      pure[2] = 1;
      break;
    case 4:
      pure[0] = v2;
      pure[1] = 0;
      pure[2] = 1;
      break;
    default:
      pure[0] = 1;
      pure[1] = 0;
      pure[2] = w2;
  }
  mg = (1 - c2) * g2;
  return [
    (c2 * pure[0] + mg) * 255,
    (c2 * pure[1] + mg) * 255,
    (c2 * pure[2] + mg) * 255
  ];
};
convert$2.hcg.hsv = function(hcg) {
  const c2 = hcg[1] / 100;
  const g2 = hcg[2] / 100;
  const v2 = c2 + g2 * (1 - c2);
  let f2 = 0;
  if (v2 > 0) {
    f2 = c2 / v2;
  }
  return [hcg[0], f2 * 100, v2 * 100];
};
convert$2.hcg.hsl = function(hcg) {
  const c2 = hcg[1] / 100;
  const g2 = hcg[2] / 100;
  const l2 = g2 * (1 - c2) + 0.5 * c2;
  let s2 = 0;
  if (l2 > 0 && l2 < 0.5) {
    s2 = c2 / (2 * l2);
  } else if (l2 >= 0.5 && l2 < 1) {
    s2 = c2 / (2 * (1 - l2));
  }
  return [hcg[0], s2 * 100, l2 * 100];
};
convert$2.hcg.hwb = function(hcg) {
  const c2 = hcg[1] / 100;
  const g2 = hcg[2] / 100;
  const v2 = c2 + g2 * (1 - c2);
  return [hcg[0], (v2 - c2) * 100, (1 - v2) * 100];
};
convert$2.hwb.hcg = function(hwb) {
  const w2 = hwb[1] / 100;
  const b2 = hwb[2] / 100;
  const v2 = 1 - b2;
  const c2 = v2 - w2;
  let g2 = 0;
  if (c2 < 1) {
    g2 = (v2 - c2) / (1 - c2);
  }
  return [hwb[0], c2 * 100, g2 * 100];
};
convert$2.apple.rgb = function(apple) {
  return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
};
convert$2.rgb.apple = function(rgb) {
  return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
};
convert$2.gray.rgb = function(args) {
  return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
};
convert$2.gray.hsl = function(args) {
  return [0, 0, args[0]];
};
convert$2.gray.hsv = convert$2.gray.hsl;
convert$2.gray.hwb = function(gray) {
  return [0, 100, gray[0]];
};
convert$2.gray.cmyk = function(gray) {
  return [0, 0, 0, gray[0]];
};
convert$2.gray.lab = function(gray) {
  return [gray[0], 0, 0];
};
convert$2.gray.hex = function(gray) {
  const val = Math.round(gray[0] / 100 * 255) & 255;
  const integer = (val << 16) + (val << 8) + val;
  const string = integer.toString(16).toUpperCase();
  return "000000".substring(string.length) + string;
};
convert$2.rgb.gray = function(rgb) {
  const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
  return [val / 255 * 100];
};
const conversions$1 = conversions$2;
function buildGraph() {
  const graph = {};
  const models2 = Object.keys(conversions$1);
  for (let len = models2.length, i2 = 0; i2 < len; i2++) {
    graph[models2[i2]] = {
      distance: -1,
      parent: null
    };
  }
  return graph;
}
function deriveBFS(fromModel) {
  const graph = buildGraph();
  const queue = [fromModel];
  graph[fromModel].distance = 0;
  while (queue.length) {
    const current = queue.pop();
    const adjacents = Object.keys(conversions$1[current]);
    for (let len = adjacents.length, i2 = 0; i2 < len; i2++) {
      const adjacent = adjacents[i2];
      const node = graph[adjacent];
      if (node.distance === -1) {
        node.distance = graph[current].distance + 1;
        node.parent = current;
        queue.unshift(adjacent);
      }
    }
  }
  return graph;
}
function link(from, to) {
  return function(args) {
    return to(from(args));
  };
}
function wrapConversion(toModel, graph) {
  const path = [graph[toModel].parent, toModel];
  let fn2 = conversions$1[graph[toModel].parent][toModel];
  let cur = graph[toModel].parent;
  while (graph[cur].parent) {
    path.unshift(graph[cur].parent);
    fn2 = link(conversions$1[graph[cur].parent][cur], fn2);
    cur = graph[cur].parent;
  }
  fn2.conversion = path;
  return fn2;
}
var route$1 = function(fromModel) {
  const graph = deriveBFS(fromModel);
  const conversion = {};
  const models2 = Object.keys(graph);
  for (let len = models2.length, i2 = 0; i2 < len; i2++) {
    const toModel = models2[i2];
    const node = graph[toModel];
    if (node.parent === null) {
      continue;
    }
    conversion[toModel] = wrapConversion(toModel, graph);
  }
  return conversion;
};
const conversions = conversions$2;
const route = route$1;
const convert$1 = {};
const models = Object.keys(conversions);
function wrapRaw(fn2) {
  const wrappedFn = function(...args) {
    const arg0 = args[0];
    if (arg0 === void 0 || arg0 === null) {
      return arg0;
    }
    if (arg0.length > 1) {
      args = arg0;
    }
    return fn2(args);
  };
  if ("conversion" in fn2) {
    wrappedFn.conversion = fn2.conversion;
  }
  return wrappedFn;
}
function wrapRounded(fn2) {
  const wrappedFn = function(...args) {
    const arg0 = args[0];
    if (arg0 === void 0 || arg0 === null) {
      return arg0;
    }
    if (arg0.length > 1) {
      args = arg0;
    }
    const result = fn2(args);
    if (typeof result === "object") {
      for (let len = result.length, i2 = 0; i2 < len; i2++) {
        result[i2] = Math.round(result[i2]);
      }
    }
    return result;
  };
  if ("conversion" in fn2) {
    wrappedFn.conversion = fn2.conversion;
  }
  return wrappedFn;
}
models.forEach((fromModel) => {
  convert$1[fromModel] = {};
  Object.defineProperty(convert$1[fromModel], "channels", { value: conversions[fromModel].channels });
  Object.defineProperty(convert$1[fromModel], "labels", { value: conversions[fromModel].labels });
  const routes = route(fromModel);
  const routeModels = Object.keys(routes);
  routeModels.forEach((toModel) => {
    const fn2 = routes[toModel];
    convert$1[fromModel][toModel] = wrapRounded(fn2);
    convert$1[fromModel][toModel].raw = wrapRaw(fn2);
  });
});
var colorConvert = convert$1;
const colorString = colorString$1.exports;
const convert = colorConvert;
const _slice = [].slice;
const skippedModels = [
  "keyword",
  "gray",
  "hex"
];
const hashedModelKeys = {};
for (const model of Object.keys(convert)) {
  hashedModelKeys[_slice.call(convert[model].labels).sort().join("")] = model;
}
const limiters = {};
function Color(object, model) {
  if (!(this instanceof Color)) {
    return new Color(object, model);
  }
  if (model && model in skippedModels) {
    model = null;
  }
  if (model && !(model in convert)) {
    throw new Error("Unknown model: " + model);
  }
  let i2;
  let channels;
  if (object == null) {
    this.model = "rgb";
    this.color = [0, 0, 0];
    this.valpha = 1;
  } else if (object instanceof Color) {
    this.model = object.model;
    this.color = object.color.slice();
    this.valpha = object.valpha;
  } else if (typeof object === "string") {
    const result = colorString.get(object);
    if (result === null) {
      throw new Error("Unable to parse color from string: " + object);
    }
    this.model = result.model;
    channels = convert[this.model].channels;
    this.color = result.value.slice(0, channels);
    this.valpha = typeof result.value[channels] === "number" ? result.value[channels] : 1;
  } else if (object.length > 0) {
    this.model = model || "rgb";
    channels = convert[this.model].channels;
    const newArray = _slice.call(object, 0, channels);
    this.color = zeroArray(newArray, channels);
    this.valpha = typeof object[channels] === "number" ? object[channels] : 1;
  } else if (typeof object === "number") {
    this.model = "rgb";
    this.color = [
      object >> 16 & 255,
      object >> 8 & 255,
      object & 255
    ];
    this.valpha = 1;
  } else {
    this.valpha = 1;
    const keys = Object.keys(object);
    if ("alpha" in object) {
      keys.splice(keys.indexOf("alpha"), 1);
      this.valpha = typeof object.alpha === "number" ? object.alpha : 0;
    }
    const hashedKeys = keys.sort().join("");
    if (!(hashedKeys in hashedModelKeys)) {
      throw new Error("Unable to parse color from object: " + JSON.stringify(object));
    }
    this.model = hashedModelKeys[hashedKeys];
    const labels = convert[this.model].labels;
    const color2 = [];
    for (i2 = 0; i2 < labels.length; i2++) {
      color2.push(object[labels[i2]]);
    }
    this.color = zeroArray(color2);
  }
  if (limiters[this.model]) {
    channels = convert[this.model].channels;
    for (i2 = 0; i2 < channels; i2++) {
      const limit = limiters[this.model][i2];
      if (limit) {
        this.color[i2] = limit(this.color[i2]);
      }
    }
  }
  this.valpha = Math.max(0, Math.min(1, this.valpha));
  if (Object.freeze) {
    Object.freeze(this);
  }
}
Color.prototype = {
  toString() {
    return this.string();
  },
  toJSON() {
    return this[this.model]();
  },
  string(places) {
    let self2 = this.model in colorString.to ? this : this.rgb();
    self2 = self2.round(typeof places === "number" ? places : 1);
    const args = self2.valpha === 1 ? self2.color : self2.color.concat(this.valpha);
    return colorString.to[self2.model](args);
  },
  percentString(places) {
    const self2 = this.rgb().round(typeof places === "number" ? places : 1);
    const args = self2.valpha === 1 ? self2.color : self2.color.concat(this.valpha);
    return colorString.to.rgb.percent(args);
  },
  array() {
    return this.valpha === 1 ? this.color.slice() : this.color.concat(this.valpha);
  },
  object() {
    const result = {};
    const channels = convert[this.model].channels;
    const labels = convert[this.model].labels;
    for (let i2 = 0; i2 < channels; i2++) {
      result[labels[i2]] = this.color[i2];
    }
    if (this.valpha !== 1) {
      result.alpha = this.valpha;
    }
    return result;
  },
  unitArray() {
    const rgb = this.rgb().color;
    rgb[0] /= 255;
    rgb[1] /= 255;
    rgb[2] /= 255;
    if (this.valpha !== 1) {
      rgb.push(this.valpha);
    }
    return rgb;
  },
  unitObject() {
    const rgb = this.rgb().object();
    rgb.r /= 255;
    rgb.g /= 255;
    rgb.b /= 255;
    if (this.valpha !== 1) {
      rgb.alpha = this.valpha;
    }
    return rgb;
  },
  round(places) {
    places = Math.max(places || 0, 0);
    return new Color(this.color.map(roundToPlace(places)).concat(this.valpha), this.model);
  },
  alpha(value) {
    if (arguments.length > 0) {
      return new Color(this.color.concat(Math.max(0, Math.min(1, value))), this.model);
    }
    return this.valpha;
  },
  red: getset("rgb", 0, maxfn(255)),
  green: getset("rgb", 1, maxfn(255)),
  blue: getset("rgb", 2, maxfn(255)),
  hue: getset(["hsl", "hsv", "hsl", "hwb", "hcg"], 0, (value) => (value % 360 + 360) % 360),
  saturationl: getset("hsl", 1, maxfn(100)),
  lightness: getset("hsl", 2, maxfn(100)),
  saturationv: getset("hsv", 1, maxfn(100)),
  value: getset("hsv", 2, maxfn(100)),
  chroma: getset("hcg", 1, maxfn(100)),
  gray: getset("hcg", 2, maxfn(100)),
  white: getset("hwb", 1, maxfn(100)),
  wblack: getset("hwb", 2, maxfn(100)),
  cyan: getset("cmyk", 0, maxfn(100)),
  magenta: getset("cmyk", 1, maxfn(100)),
  yellow: getset("cmyk", 2, maxfn(100)),
  black: getset("cmyk", 3, maxfn(100)),
  x: getset("xyz", 0, maxfn(100)),
  y: getset("xyz", 1, maxfn(100)),
  z: getset("xyz", 2, maxfn(100)),
  l: getset("lab", 0, maxfn(100)),
  a: getset("lab", 1),
  b: getset("lab", 2),
  keyword(value) {
    if (arguments.length > 0) {
      return new Color(value);
    }
    return convert[this.model].keyword(this.color);
  },
  hex(value) {
    if (arguments.length > 0) {
      return new Color(value);
    }
    return colorString.to.hex(this.rgb().round().color);
  },
  hexa(value) {
    if (arguments.length > 0) {
      return new Color(value);
    }
    const rgbArray = this.rgb().round().color;
    let alphaHex = Math.round(this.valpha * 255).toString(16).toUpperCase();
    if (alphaHex.length === 1) {
      alphaHex = "0" + alphaHex;
    }
    return colorString.to.hex(rgbArray) + alphaHex;
  },
  rgbNumber() {
    const rgb = this.rgb().color;
    return (rgb[0] & 255) << 16 | (rgb[1] & 255) << 8 | rgb[2] & 255;
  },
  luminosity() {
    const rgb = this.rgb().color;
    const lum = [];
    for (const [i2, element] of rgb.entries()) {
      const chan = element / 255;
      lum[i2] = chan <= 0.03928 ? chan / 12.92 : ((chan + 0.055) / 1.055) ** 2.4;
    }
    return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2];
  },
  contrast(color2) {
    const lum1 = this.luminosity();
    const lum2 = color2.luminosity();
    if (lum1 > lum2) {
      return (lum1 + 0.05) / (lum2 + 0.05);
    }
    return (lum2 + 0.05) / (lum1 + 0.05);
  },
  level(color2) {
    const contrastRatio = this.contrast(color2);
    if (contrastRatio >= 7.1) {
      return "AAA";
    }
    return contrastRatio >= 4.5 ? "AA" : "";
  },
  isDark() {
    const rgb = this.rgb().color;
    const yiq = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1e3;
    return yiq < 128;
  },
  isLight() {
    return !this.isDark();
  },
  negate() {
    const rgb = this.rgb();
    for (let i2 = 0; i2 < 3; i2++) {
      rgb.color[i2] = 255 - rgb.color[i2];
    }
    return rgb;
  },
  lighten(ratio) {
    const hsl = this.hsl();
    hsl.color[2] += hsl.color[2] * ratio;
    return hsl;
  },
  darken(ratio) {
    const hsl = this.hsl();
    hsl.color[2] -= hsl.color[2] * ratio;
    return hsl;
  },
  saturate(ratio) {
    const hsl = this.hsl();
    hsl.color[1] += hsl.color[1] * ratio;
    return hsl;
  },
  desaturate(ratio) {
    const hsl = this.hsl();
    hsl.color[1] -= hsl.color[1] * ratio;
    return hsl;
  },
  whiten(ratio) {
    const hwb = this.hwb();
    hwb.color[1] += hwb.color[1] * ratio;
    return hwb;
  },
  blacken(ratio) {
    const hwb = this.hwb();
    hwb.color[2] += hwb.color[2] * ratio;
    return hwb;
  },
  grayscale() {
    const rgb = this.rgb().color;
    const value = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11;
    return Color.rgb(value, value, value);
  },
  fade(ratio) {
    return this.alpha(this.valpha - this.valpha * ratio);
  },
  opaquer(ratio) {
    return this.alpha(this.valpha + this.valpha * ratio);
  },
  rotate(degrees2) {
    const hsl = this.hsl();
    let hue = hsl.color[0];
    hue = (hue + degrees2) % 360;
    hue = hue < 0 ? 360 + hue : hue;
    hsl.color[0] = hue;
    return hsl;
  },
  mix(mixinColor, weight) {
    if (!mixinColor || !mixinColor.rgb) {
      throw new Error('Argument to "mix" was not a Color instance, but rather an instance of ' + typeof mixinColor);
    }
    const color1 = mixinColor.rgb();
    const color2 = this.rgb();
    const p2 = weight === void 0 ? 0.5 : weight;
    const w2 = 2 * p2 - 1;
    const a2 = color1.alpha() - color2.alpha();
    const w1 = ((w2 * a2 === -1 ? w2 : (w2 + a2) / (1 + w2 * a2)) + 1) / 2;
    const w22 = 1 - w1;
    return Color.rgb(w1 * color1.red() + w22 * color2.red(), w1 * color1.green() + w22 * color2.green(), w1 * color1.blue() + w22 * color2.blue(), color1.alpha() * p2 + color2.alpha() * (1 - p2));
  }
};
for (const model of Object.keys(convert)) {
  if (skippedModels.includes(model)) {
    continue;
  }
  const channels = convert[model].channels;
  Color.prototype[model] = function() {
    if (this.model === model) {
      return new Color(this);
    }
    if (arguments.length > 0) {
      return new Color(arguments, model);
    }
    const newAlpha = typeof arguments[channels] === "number" ? channels : this.valpha;
    return new Color(assertArray(convert[this.model][model].raw(this.color)).concat(newAlpha), model);
  };
  Color[model] = function(color2) {
    if (typeof color2 === "number") {
      color2 = zeroArray(_slice.call(arguments), channels);
    }
    return new Color(color2, model);
  };
}
function roundTo(number2, places) {
  return Number(number2.toFixed(places));
}
function roundToPlace(places) {
  return function(number2) {
    return roundTo(number2, places);
  };
}
function getset(model, channel, modifier) {
  model = Array.isArray(model) ? model : [model];
  for (const m2 of model) {
    (limiters[m2] || (limiters[m2] = []))[channel] = modifier;
  }
  model = model[0];
  return function(value) {
    let result;
    if (arguments.length > 0) {
      if (modifier) {
        value = modifier(value);
      }
      result = this[model]();
      result.color[channel] = value;
      return result;
    }
    result = this[model]().color[channel];
    if (modifier) {
      result = modifier(result);
    }
    return result;
  };
}
function maxfn(max) {
  return function(v2) {
    return Math.max(0, Math.min(max, v2));
  };
}
function assertArray(value) {
  return Array.isArray(value) ? value : [value];
}
function zeroArray(array, length) {
  for (let i2 = 0; i2 < length; i2++) {
    if (typeof array[i2] !== "number") {
      array[i2] = 0;
    }
  }
  return array;
}
var color = Color;
function initThemes(rootEl, activeTheme) {
  if (!activeTheme)
    return;
  const defaultTheme = activeTheme.isDark ? DEFAULT_THEMES.find((t2) => t2.isDark) : DEFAULT_THEMES.find((t2) => !t2.isDark);
  const mergedTheme = __spreadProps(__spreadValues(__spreadValues({}, defaultTheme), activeTheme), {
    colors: __spreadValues(__spreadValues({}, defaultTheme.colors), activeTheme.colors)
  });
  Object.entries(mergedTheme.colors).forEach(([key, value]) => {
    rootEl.style.setProperty(key, parseThemeValue(value));
  });
  if (activeTheme.isDark) {
    rootEl.classList.add("dark");
  } else {
    rootEl.classList.remove("dark");
  }
}
function parseThemeValue(value) {
  if (value.endsWith("%") || value.split(" ").length === 3) {
    return value;
  }
  return color(value).rgb().array().slice(0, 3).join(" ");
}
function useActiveTheme() {
  const activeTheme = useStore$1((s2) => {
    var _a2;
    return (_a2 = s2.config.ui) == null ? void 0 : _a2.activeTheme;
  });
  return useStore$1((s2) => {
    var _a2;
    return (((_a2 = s2.config.ui) == null ? void 0 : _a2.themes) || []).find((t2) => t2.name === activeTheme);
  });
}
const OverlayPositionContext = React__default.createContext(null);
const toolbarStyle = "flex flex-shrink-0 items-center justify-between px-12 py-[9px] w-full h-[54px]";
const toolbarAnimation = {
  initial: {
    opacity: 0
  },
  animate: {
    opacity: 1
  },
  exit: {
    opacity: 0,
    position: "absolute"
  },
  transition: {
    type: "tween",
    duration: 0.15
  }
};
function getButtonSizeStyle(size, {
  padding,
  equalWidth
} = {}) {
  switch (size) {
    case "xs":
      return `text-xs h-30 ${equalWidth ? "w-30" : padding || "px-14"}`;
    case "sm":
      return `text-sm h-36 ${equalWidth ? "w-36" : padding || "px-18"}`;
    case "lg":
      return `text-lg h-50 ${equalWidth ? "w-50" : padding || "px-26"}`;
    case "xl":
      return `text-xl h-60 ${equalWidth ? "w-60" : padding || "px-32"}`;
    case "md":
      return `text-base h-42 ${equalWidth ? "w-42" : padding || "px-22"}`;
    default:
      return "";
  }
}
function getIconSizeStyle(size) {
  switch (size) {
    case "xs":
      return "icon-xs";
    case "sm":
      return "icon-sm";
    case "md":
      return "icon-md";
    case "lg":
      return "icon-lg";
    case "xl":
      return "icon-xl";
    default:
      return "";
  }
}
function $parcel$export$w(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $14e5c84cbc2e6e2e$exports = {};
$parcel$export$w($14e5c84cbc2e6e2e$exports, "FocusScope", () => $14e5c84cbc2e6e2e$export$20e40289641fbbb6);
$parcel$export$w($14e5c84cbc2e6e2e$exports, "useFocusManager", () => $14e5c84cbc2e6e2e$export$10c5169755ce7bd7);
$parcel$export$w($14e5c84cbc2e6e2e$exports, "getFocusableTreeWalker", () => $14e5c84cbc2e6e2e$export$2d6ec8fc375ceafa);
$parcel$export$w($14e5c84cbc2e6e2e$exports, "createFocusManager", () => $14e5c84cbc2e6e2e$export$c5251b9e124bf29);
var $1159c3b6ba210e4f$exports = {};
$parcel$export$w($1159c3b6ba210e4f$exports, "focusSafely", () => $1159c3b6ba210e4f$export$80f3e147d781571c);
function $1159c3b6ba210e4f$export$80f3e147d781571c(element) {
  if ($507fabe10e71c6fb$export$630ff653c5ada6a9() === "virtual") {
    let lastFocusedElement = document.activeElement;
    $bbed8b41f857bcc0$export$24490316f764c430(() => {
      if (document.activeElement === lastFocusedElement && document.contains(element))
        $7215afc6de606d6b$export$de79e2c695e052f3(element);
    });
  } else
    $7215afc6de606d6b$export$de79e2c695e052f3(element);
}
function $985a2847ebcbb615$var$isStyleVisible(element) {
  if (!(element instanceof HTMLElement) && !(element instanceof SVGElement))
    return false;
  let { display, visibility } = element.style;
  let isVisible = display !== "none" && visibility !== "hidden" && visibility !== "collapse";
  if (isVisible) {
    const { getComputedStyle: getComputedStyle2 } = element.ownerDocument.defaultView;
    let { display: computedDisplay, visibility: computedVisibility } = getComputedStyle2(element);
    isVisible = computedDisplay !== "none" && computedVisibility !== "hidden" && computedVisibility !== "collapse";
  }
  return isVisible;
}
function $985a2847ebcbb615$var$isAttributeVisible(element, childElement) {
  return !element.hasAttribute("hidden") && (element.nodeName === "DETAILS" && childElement && childElement.nodeName !== "SUMMARY" ? element.hasAttribute("open") : true);
}
function $985a2847ebcbb615$export$e989c0fffaa6b27a(element, childElement) {
  return element.nodeName !== "#comment" && $985a2847ebcbb615$var$isStyleVisible(element) && $985a2847ebcbb615$var$isAttributeVisible(element, childElement) && (!element.parentElement || $985a2847ebcbb615$export$e989c0fffaa6b27a(element.parentElement, element));
}
const $14e5c84cbc2e6e2e$var$FocusContext = /* @__PURE__ */ React__default.createContext(null);
let $14e5c84cbc2e6e2e$var$activeScope = null;
let $14e5c84cbc2e6e2e$var$scopes = /* @__PURE__ */ new Map();
function $14e5c84cbc2e6e2e$export$20e40289641fbbb6(props2) {
  let { children, contain, restoreFocus, autoFocus } = props2;
  let startRef = useRef();
  let endRef = useRef();
  let scopeRef = useRef([]);
  let ctx = useContext($14e5c84cbc2e6e2e$var$FocusContext);
  let parentScope = ctx === null || ctx === void 0 ? void 0 : ctx.scopeRef;
  $f0a04ccd8dbdd83b$export$e5c5a5f917a5871c(() => {
    let node = startRef.current.nextSibling;
    let nodes = [];
    while (node && node !== endRef.current) {
      nodes.push(node);
      node = node.nextSibling;
    }
    scopeRef.current = nodes;
  }, [
    children,
    parentScope
  ]);
  $f0a04ccd8dbdd83b$export$e5c5a5f917a5871c(() => {
    $14e5c84cbc2e6e2e$var$scopes.set(scopeRef, parentScope);
    return () => {
      if ((scopeRef === $14e5c84cbc2e6e2e$var$activeScope || $14e5c84cbc2e6e2e$var$isAncestorScope(scopeRef, $14e5c84cbc2e6e2e$var$activeScope)) && (!parentScope || $14e5c84cbc2e6e2e$var$scopes.has(parentScope)))
        $14e5c84cbc2e6e2e$var$activeScope = parentScope;
      $14e5c84cbc2e6e2e$var$scopes.delete(scopeRef);
    };
  }, [
    scopeRef,
    parentScope
  ]);
  $14e5c84cbc2e6e2e$var$useFocusContainment(scopeRef, contain);
  $14e5c84cbc2e6e2e$var$useRestoreFocus(scopeRef, restoreFocus, contain);
  $14e5c84cbc2e6e2e$var$useAutoFocus(scopeRef, autoFocus);
  let focusManager = $14e5c84cbc2e6e2e$var$createFocusManagerForScope(scopeRef);
  return /* @__PURE__ */ React__default.createElement($14e5c84cbc2e6e2e$var$FocusContext.Provider, {
    value: {
      scopeRef,
      focusManager
    }
  }, /* @__PURE__ */ React__default.createElement("span", {
    "data-focus-scope-start": true,
    hidden: true,
    ref: startRef
  }), children, /* @__PURE__ */ React__default.createElement("span", {
    "data-focus-scope-end": true,
    hidden: true,
    ref: endRef
  }));
}
function $14e5c84cbc2e6e2e$export$10c5169755ce7bd7() {
  var ref;
  return (ref = useContext($14e5c84cbc2e6e2e$var$FocusContext)) === null || ref === void 0 ? void 0 : ref.focusManager;
}
function $14e5c84cbc2e6e2e$var$createFocusManagerForScope(scopeRef) {
  return {
    focusNext(opts = {}) {
      let scope = scopeRef.current;
      let { from, tabbable, wrap: wrap2 } = opts;
      let node = from || document.activeElement;
      let sentinel = scope[0].previousElementSibling;
      let walker = $14e5c84cbc2e6e2e$export$2d6ec8fc375ceafa($14e5c84cbc2e6e2e$var$getScopeRoot(scope), {
        tabbable
      }, scope);
      walker.currentNode = $14e5c84cbc2e6e2e$var$isElementInScope(node, scope) ? node : sentinel;
      let nextNode = walker.nextNode();
      if (!nextNode && wrap2) {
        walker.currentNode = sentinel;
        nextNode = walker.nextNode();
      }
      if (nextNode)
        $14e5c84cbc2e6e2e$var$focusElement(nextNode, true);
      return nextNode;
    },
    focusPrevious(opts = {}) {
      let scope = scopeRef.current;
      let { from, tabbable, wrap: wrap2 } = opts;
      let node = from || document.activeElement;
      let sentinel = scope[scope.length - 1].nextElementSibling;
      let walker = $14e5c84cbc2e6e2e$export$2d6ec8fc375ceafa($14e5c84cbc2e6e2e$var$getScopeRoot(scope), {
        tabbable
      }, scope);
      walker.currentNode = $14e5c84cbc2e6e2e$var$isElementInScope(node, scope) ? node : sentinel;
      let previousNode = walker.previousNode();
      if (!previousNode && wrap2) {
        walker.currentNode = sentinel;
        previousNode = walker.previousNode();
      }
      if (previousNode)
        $14e5c84cbc2e6e2e$var$focusElement(previousNode, true);
      return previousNode;
    },
    focusFirst(opts = {}) {
      let scope = scopeRef.current;
      let { tabbable } = opts;
      let walker = $14e5c84cbc2e6e2e$export$2d6ec8fc375ceafa($14e5c84cbc2e6e2e$var$getScopeRoot(scope), {
        tabbable
      }, scope);
      walker.currentNode = scope[0].previousElementSibling;
      let nextNode = walker.nextNode();
      if (nextNode)
        $14e5c84cbc2e6e2e$var$focusElement(nextNode, true);
      return nextNode;
    },
    focusLast(opts = {}) {
      let scope = scopeRef.current;
      let { tabbable } = opts;
      let walker = $14e5c84cbc2e6e2e$export$2d6ec8fc375ceafa($14e5c84cbc2e6e2e$var$getScopeRoot(scope), {
        tabbable
      }, scope);
      walker.currentNode = scope[scope.length - 1].nextElementSibling;
      let previousNode = walker.previousNode();
      if (previousNode)
        $14e5c84cbc2e6e2e$var$focusElement(previousNode, true);
      return previousNode;
    }
  };
}
const $14e5c84cbc2e6e2e$var$focusableElements = [
  "input:not([disabled]):not([type=hidden])",
  "select:not([disabled])",
  "textarea:not([disabled])",
  "button:not([disabled])",
  "a[href]",
  "area[href]",
  "summary",
  "iframe",
  "object",
  "embed",
  "audio[controls]",
  "video[controls]",
  "[contenteditable]"
];
const $14e5c84cbc2e6e2e$var$FOCUSABLE_ELEMENT_SELECTOR = $14e5c84cbc2e6e2e$var$focusableElements.join(":not([hidden]),") + ",[tabindex]:not([disabled]):not([hidden])";
$14e5c84cbc2e6e2e$var$focusableElements.push('[tabindex]:not([tabindex="-1"]):not([disabled])');
const $14e5c84cbc2e6e2e$var$TABBABLE_ELEMENT_SELECTOR = $14e5c84cbc2e6e2e$var$focusableElements.join(':not([hidden]):not([tabindex="-1"]),');
function $14e5c84cbc2e6e2e$var$getScopeRoot(scope) {
  return scope[0].parentElement;
}
function $14e5c84cbc2e6e2e$var$useFocusContainment(scopeRef, contain) {
  let focusedNode = useRef();
  let raf = useRef(null);
  $f0a04ccd8dbdd83b$export$e5c5a5f917a5871c(() => {
    let scope1 = scopeRef.current;
    if (!contain)
      return;
    let onKeyDown = (e2) => {
      if (e2.key !== "Tab" || e2.altKey || e2.ctrlKey || e2.metaKey || scopeRef !== $14e5c84cbc2e6e2e$var$activeScope)
        return;
      let focusedElement = document.activeElement;
      let scope = scopeRef.current;
      if (!$14e5c84cbc2e6e2e$var$isElementInScope(focusedElement, scope))
        return;
      let walker = $14e5c84cbc2e6e2e$export$2d6ec8fc375ceafa($14e5c84cbc2e6e2e$var$getScopeRoot(scope), {
        tabbable: true
      }, scope);
      walker.currentNode = focusedElement;
      let nextElement = e2.shiftKey ? walker.previousNode() : walker.nextNode();
      if (!nextElement) {
        walker.currentNode = e2.shiftKey ? scope[scope.length - 1].nextElementSibling : scope[0].previousElementSibling;
        nextElement = e2.shiftKey ? walker.previousNode() : walker.nextNode();
      }
      e2.preventDefault();
      if (nextElement)
        $14e5c84cbc2e6e2e$var$focusElement(nextElement, true);
    };
    let onFocus = (e2) => {
      if (!$14e5c84cbc2e6e2e$var$activeScope || $14e5c84cbc2e6e2e$var$isAncestorScope($14e5c84cbc2e6e2e$var$activeScope, scopeRef)) {
        $14e5c84cbc2e6e2e$var$activeScope = scopeRef;
        focusedNode.current = e2.target;
      } else if (scopeRef === $14e5c84cbc2e6e2e$var$activeScope && !$14e5c84cbc2e6e2e$var$isElementInChildScope(e2.target, scopeRef)) {
        if (focusedNode.current)
          focusedNode.current.focus();
        else if ($14e5c84cbc2e6e2e$var$activeScope)
          $14e5c84cbc2e6e2e$var$focusFirstInScope($14e5c84cbc2e6e2e$var$activeScope.current);
      } else if (scopeRef === $14e5c84cbc2e6e2e$var$activeScope)
        focusedNode.current = e2.target;
    };
    let onBlur = (e2) => {
      raf.current = requestAnimationFrame(() => {
        if (scopeRef === $14e5c84cbc2e6e2e$var$activeScope && !$14e5c84cbc2e6e2e$var$isElementInChildScope(document.activeElement, scopeRef)) {
          $14e5c84cbc2e6e2e$var$activeScope = scopeRef;
          focusedNode.current = e2.target;
          focusedNode.current.focus();
        }
      });
    };
    document.addEventListener("keydown", onKeyDown, false);
    document.addEventListener("focusin", onFocus, false);
    scope1.forEach((element) => element.addEventListener("focusin", onFocus, false));
    scope1.forEach((element) => element.addEventListener("focusout", onBlur, false));
    return () => {
      document.removeEventListener("keydown", onKeyDown, false);
      document.removeEventListener("focusin", onFocus, false);
      scope1.forEach((element) => element.removeEventListener("focusin", onFocus, false));
      scope1.forEach((element) => element.removeEventListener("focusout", onBlur, false));
    };
  }, [
    scopeRef,
    contain
  ]);
  useEffect(() => {
    return () => cancelAnimationFrame(raf.current);
  }, [
    raf
  ]);
}
function $14e5c84cbc2e6e2e$var$isElementInAnyScope(element) {
  for (let scope of $14e5c84cbc2e6e2e$var$scopes.keys()) {
    if ($14e5c84cbc2e6e2e$var$isElementInScope(element, scope.current))
      return true;
  }
  return false;
}
function $14e5c84cbc2e6e2e$var$isElementInScope(element, scope) {
  return scope.some((node) => node.contains(element));
}
function $14e5c84cbc2e6e2e$var$isElementInChildScope(element, scope) {
  for (let s2 of $14e5c84cbc2e6e2e$var$scopes.keys()) {
    if ((s2 === scope || $14e5c84cbc2e6e2e$var$isAncestorScope(scope, s2)) && $14e5c84cbc2e6e2e$var$isElementInScope(element, s2.current))
      return true;
  }
  return false;
}
function $14e5c84cbc2e6e2e$var$isAncestorScope(ancestor, scope) {
  let parent = $14e5c84cbc2e6e2e$var$scopes.get(scope);
  if (!parent)
    return false;
  if (parent === ancestor)
    return true;
  return $14e5c84cbc2e6e2e$var$isAncestorScope(ancestor, parent);
}
function $14e5c84cbc2e6e2e$var$focusElement(element, scroll = false) {
  if (element != null && !scroll)
    try {
      $1159c3b6ba210e4f$export$80f3e147d781571c(element);
    } catch (err) {
    }
  else if (element != null)
    try {
      element.focus();
    } catch (err1) {
    }
}
function $14e5c84cbc2e6e2e$var$focusFirstInScope(scope) {
  let sentinel = scope[0].previousElementSibling;
  let walker = $14e5c84cbc2e6e2e$export$2d6ec8fc375ceafa($14e5c84cbc2e6e2e$var$getScopeRoot(scope), {
    tabbable: true
  }, scope);
  walker.currentNode = sentinel;
  $14e5c84cbc2e6e2e$var$focusElement(walker.nextNode());
}
function $14e5c84cbc2e6e2e$var$useAutoFocus(scopeRef, autoFocus) {
  const autoFocusRef = React__default.useRef(autoFocus);
  useEffect(() => {
    if (autoFocusRef.current) {
      $14e5c84cbc2e6e2e$var$activeScope = scopeRef;
      if (!$14e5c84cbc2e6e2e$var$isElementInScope(document.activeElement, $14e5c84cbc2e6e2e$var$activeScope.current))
        $14e5c84cbc2e6e2e$var$focusFirstInScope(scopeRef.current);
    }
    autoFocusRef.current = false;
  }, []);
}
function $14e5c84cbc2e6e2e$var$useRestoreFocus(scopeRef, restoreFocus, contain) {
  const nodeToRestoreRef = useRef(typeof document !== "undefined" ? document.activeElement : null);
  $f0a04ccd8dbdd83b$export$e5c5a5f917a5871c(() => {
    let nodeToRestore = nodeToRestoreRef.current;
    if (!restoreFocus)
      return;
    let onKeyDown = (e2) => {
      if (e2.key !== "Tab" || e2.altKey || e2.ctrlKey || e2.metaKey)
        return;
      let focusedElement = document.activeElement;
      if (!$14e5c84cbc2e6e2e$var$isElementInScope(focusedElement, scopeRef.current))
        return;
      let walker = $14e5c84cbc2e6e2e$export$2d6ec8fc375ceafa(document.body, {
        tabbable: true
      });
      walker.currentNode = focusedElement;
      let nextElement = e2.shiftKey ? walker.previousNode() : walker.nextNode();
      if (!document.body.contains(nodeToRestore) || nodeToRestore === document.body)
        nodeToRestore = null;
      if ((!nextElement || !$14e5c84cbc2e6e2e$var$isElementInScope(nextElement, scopeRef.current)) && nodeToRestore) {
        walker.currentNode = nodeToRestore;
        do
          nextElement = e2.shiftKey ? walker.previousNode() : walker.nextNode();
        while ($14e5c84cbc2e6e2e$var$isElementInScope(nextElement, scopeRef.current));
        e2.preventDefault();
        e2.stopPropagation();
        if (nextElement)
          $14e5c84cbc2e6e2e$var$focusElement(nextElement, true);
        else if (!$14e5c84cbc2e6e2e$var$isElementInAnyScope(nodeToRestore))
          focusedElement.blur();
        else
          $14e5c84cbc2e6e2e$var$focusElement(nodeToRestore, true);
      }
    };
    if (!contain)
      document.addEventListener("keydown", onKeyDown, true);
    return () => {
      if (!contain)
        document.removeEventListener("keydown", onKeyDown, true);
      if (restoreFocus && nodeToRestore && $14e5c84cbc2e6e2e$var$isElementInScope(document.activeElement, scopeRef.current))
        requestAnimationFrame(() => {
          if (document.body.contains(nodeToRestore))
            $14e5c84cbc2e6e2e$var$focusElement(nodeToRestore);
        });
    };
  }, [
    scopeRef,
    restoreFocus,
    contain
  ]);
}
function $14e5c84cbc2e6e2e$export$2d6ec8fc375ceafa(root, opts, scope) {
  let selector = (opts === null || opts === void 0 ? void 0 : opts.tabbable) ? $14e5c84cbc2e6e2e$var$TABBABLE_ELEMENT_SELECTOR : $14e5c84cbc2e6e2e$var$FOCUSABLE_ELEMENT_SELECTOR;
  let walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT, {
    acceptNode(node) {
      var ref;
      if (opts === null || opts === void 0 ? void 0 : (ref = opts.from) === null || ref === void 0 ? void 0 : ref.contains(node))
        return NodeFilter.FILTER_REJECT;
      if (node.matches(selector) && $985a2847ebcbb615$export$e989c0fffaa6b27a(node) && (!scope || $14e5c84cbc2e6e2e$var$isElementInScope(node, scope)))
        return NodeFilter.FILTER_ACCEPT;
      return NodeFilter.FILTER_SKIP;
    }
  });
  if (opts === null || opts === void 0 ? void 0 : opts.from)
    walker.currentNode = opts.from;
  return walker;
}
function $14e5c84cbc2e6e2e$export$c5251b9e124bf29(ref) {
  return {
    focusNext(opts = {}) {
      let root = ref.current;
      let { from, tabbable, wrap: wrap2 } = opts;
      let node = from || document.activeElement;
      let walker = $14e5c84cbc2e6e2e$export$2d6ec8fc375ceafa(root, {
        tabbable
      });
      if (root.contains(node))
        walker.currentNode = node;
      let nextNode = walker.nextNode();
      if (!nextNode && wrap2) {
        walker.currentNode = root;
        nextNode = walker.nextNode();
      }
      if (nextNode)
        $14e5c84cbc2e6e2e$var$focusElement(nextNode, true);
      return nextNode;
    },
    focusPrevious(opts = {}) {
      let root = ref.current;
      let { from, tabbable, wrap: wrap2 } = opts;
      let node = from || document.activeElement;
      let walker = $14e5c84cbc2e6e2e$export$2d6ec8fc375ceafa(root, {
        tabbable
      });
      if (root.contains(node))
        walker.currentNode = node;
      else {
        let next = $14e5c84cbc2e6e2e$var$last(walker);
        if (next)
          $14e5c84cbc2e6e2e$var$focusElement(next, true);
        return next;
      }
      let previousNode = walker.previousNode();
      if (!previousNode && wrap2) {
        walker.currentNode = root;
        previousNode = $14e5c84cbc2e6e2e$var$last(walker);
      }
      if (previousNode)
        $14e5c84cbc2e6e2e$var$focusElement(previousNode, true);
      return previousNode;
    },
    focusFirst(opts = {}) {
      let root = ref.current;
      let { tabbable } = opts;
      let walker = $14e5c84cbc2e6e2e$export$2d6ec8fc375ceafa(root, {
        tabbable
      });
      let nextNode = walker.nextNode();
      if (nextNode)
        $14e5c84cbc2e6e2e$var$focusElement(nextNode, true);
      return nextNode;
    },
    focusLast(opts = {}) {
      let root = ref.current;
      let { tabbable } = opts;
      let walker = $14e5c84cbc2e6e2e$export$2d6ec8fc375ceafa(root, {
        tabbable
      });
      let next = $14e5c84cbc2e6e2e$var$last(walker);
      if (next)
        $14e5c84cbc2e6e2e$var$focusElement(next, true);
      return next;
    }
  };
}
function $14e5c84cbc2e6e2e$var$last(walker) {
  let next;
  let last;
  do {
    last = walker.lastChild();
    if (last)
      next = last;
  } while (last);
  return next;
}
var $503734efc0922182$exports = {};
$parcel$export$w($503734efc0922182$exports, "FocusRing", () => $503734efc0922182$export$1a38b4ad7f578e1d);
var $e63d024ca16f2165$exports = {};
$parcel$export$w($e63d024ca16f2165$exports, "useFocusRing", () => $e63d024ca16f2165$export$4e328f61c538687f);
function $e63d024ca16f2165$export$4e328f61c538687f(props2 = {}) {
  let { autoFocus = false, isTextInput, within } = props2;
  let state2 = useRef({
    isFocused: false,
    isFocusVisible: autoFocus || $507fabe10e71c6fb$export$b9b3dfddab17db27()
  }).current;
  let [isFocused1, setFocused] = useState(false);
  let [isFocusVisibleState, setFocusVisible] = useState(() => state2.isFocused && state2.isFocusVisible);
  let updateState = () => setFocusVisible(state2.isFocused && state2.isFocusVisible);
  let onFocusChange = (isFocused) => {
    state2.isFocused = isFocused;
    setFocused(isFocused);
    updateState();
  };
  $507fabe10e71c6fb$export$ec71b4b83ac08ec3((isFocusVisible) => {
    state2.isFocusVisible = isFocusVisible;
    updateState();
  }, [], {
    isTextInput
  });
  let { focusProps } = $a1ea59d68270f0dd$export$f8168d8dd8fd66e6({
    isDisabled: within,
    onFocusChange
  });
  let { focusWithinProps } = $9ab94262bd0047c7$export$420e68273165f4ec({
    isDisabled: !within,
    onFocusWithinChange: onFocusChange
  });
  return {
    isFocused: isFocused1,
    isFocusVisible: state2.isFocused && isFocusVisibleState,
    focusProps: within ? focusWithinProps : focusProps
  };
}
function $503734efc0922182$export$1a38b4ad7f578e1d(props2) {
  let { children, focusClass, focusRingClass } = props2;
  let { isFocused, isFocusVisible, focusProps } = $e63d024ca16f2165$export$4e328f61c538687f(props2);
  let child = React__default.Children.only(children);
  return /* @__PURE__ */ React__default.cloneElement(child, $3ef42575df84b30b$export$9d1611c77c2fe928(child.props, __spreadProps(__spreadValues({}, focusProps), {
    className: clsx({
      [focusClass || ""]: isFocused,
      [focusRingClass || ""]: isFocusVisible
    })
  })));
}
var $391c6482f25a1991$exports = {};
$parcel$export$w($391c6482f25a1991$exports, "FocusableProvider", () => $391c6482f25a1991$export$13f3202a3e5ddd5);
$parcel$export$w($391c6482f25a1991$exports, "useFocusable", () => $391c6482f25a1991$export$4c014de7c8940b4c);
let $391c6482f25a1991$var$FocusableContext = /* @__PURE__ */ React__default.createContext(null);
function $391c6482f25a1991$var$useFocusableContext(ref) {
  let context = useContext($391c6482f25a1991$var$FocusableContext) || {};
  $e7801be82b4b2a53$export$4debdb1a3f0fa79e(context, ref);
  let _a2 = context, { ref: _2 } = _a2, otherProps = __objRest(_a2, ["ref"]);
  return otherProps;
}
function $391c6482f25a1991$var$FocusableProvider(props2, ref) {
  let _a2 = props2, { children } = _a2, otherProps = __objRest(_a2, ["children"]);
  let context = __spreadProps(__spreadValues({}, otherProps), {
    ref
  });
  return /* @__PURE__ */ React__default.createElement($391c6482f25a1991$var$FocusableContext.Provider, {
    value: context
  }, children);
}
let $391c6482f25a1991$export$13f3202a3e5ddd5 = /* @__PURE__ */ React__default.forwardRef($391c6482f25a1991$var$FocusableProvider);
function $391c6482f25a1991$export$4c014de7c8940b4c(props2, domRef) {
  let { focusProps } = $a1ea59d68270f0dd$export$f8168d8dd8fd66e6(props2);
  let { keyboardProps } = $46d819fcbaf35654$export$8f71654801c2f7cd(props2);
  let interactions = $3ef42575df84b30b$export$9d1611c77c2fe928(focusProps, keyboardProps);
  let domProps = $391c6482f25a1991$var$useFocusableContext(domRef);
  let interactionProps = props2.isDisabled ? {} : domProps;
  let autoFocusRef = useRef(props2.autoFocus);
  useEffect(() => {
    if (autoFocusRef.current && domRef.current)
      domRef.current.focus();
    autoFocusRef.current = false;
  }, []);
  return {
    focusableProps: $3ef42575df84b30b$export$9d1611c77c2fe928(__spreadProps(__spreadValues({}, interactions), {
      tabIndex: props2.excludeFromTabOrder && !props2.isDisabled ? -1 : void 0
    }), interactionProps)
  };
}
function $parcel$export$v(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $4e9d283129286548$exports = {};
$parcel$export$v($4e9d283129286548$exports, "useButton", () => $4e9d283129286548$export$ea18c227d4417cc3);
function $4e9d283129286548$export$ea18c227d4417cc3(props2, ref) {
  let {
    elementType = "button",
    isDisabled,
    onPress,
    onPressStart,
    onPressEnd,
    onPressChange,
    preventFocusOnPress,
    allowFocusWhenDisabled,
    onClick: deprecatedOnClick,
    href,
    target,
    rel,
    type = "button"
  } = props2;
  let additionalProps;
  if (elementType === "button")
    additionalProps = {
      type,
      disabled: isDisabled
    };
  else
    additionalProps = {
      role: "button",
      tabIndex: isDisabled ? void 0 : 0,
      href: elementType === "a" && isDisabled ? void 0 : href,
      target: elementType === "a" ? target : void 0,
      type: elementType === "input" ? type : void 0,
      disabled: elementType === "input" ? isDisabled : void 0,
      "aria-disabled": !isDisabled || elementType === "input" ? void 0 : isDisabled,
      rel: elementType === "a" ? rel : void 0
    };
  let { pressProps, isPressed } = $f6c31cce2adf654f$export$45712eceda6fad21({
    onPressStart,
    onPressEnd,
    onPressChange,
    onPress,
    isDisabled,
    preventFocusOnPress,
    ref
  });
  let { focusableProps } = $391c6482f25a1991$export$4c014de7c8940b4c(props2, ref);
  if (allowFocusWhenDisabled)
    focusableProps.tabIndex = isDisabled ? -1 : focusableProps.tabIndex;
  let buttonProps = $3ef42575df84b30b$export$9d1611c77c2fe928(focusableProps, pressProps, $65484d02dcb7eb3e$export$457c3d6518dd4c6f(props2, {
    labelable: true
  }));
  return {
    isPressed,
    buttonProps: $3ef42575df84b30b$export$9d1611c77c2fe928(additionalProps, buttonProps, {
      "aria-haspopup": props2["aria-haspopup"],
      "aria-expanded": props2["aria-expanded"],
      "aria-controls": props2["aria-controls"],
      "aria-pressed": props2["aria-pressed"],
      onClick: (e2) => {
        if (deprecatedOnClick) {
          deprecatedOnClick(e2);
          console.warn("onClick is deprecated, please use onPress");
        }
      }
    })
  };
}
var $2f16ea8f6283ecbd$exports = {};
$parcel$export$v($2f16ea8f6283ecbd$exports, "useToggleButton", () => $2f16ea8f6283ecbd$export$51e84d46ca0bc451);
function $2f16ea8f6283ecbd$export$51e84d46ca0bc451(props2, state2, ref) {
  const { isSelected } = state2;
  const { isPressed, buttonProps } = $4e9d283129286548$export$ea18c227d4417cc3(__spreadProps(__spreadValues({}, props2), {
    onPress: $ff5963eb1fccf552$export$e08e3b67e392101e(state2.toggle, props2.onPress)
  }), ref);
  return {
    isPressed,
    buttonProps: $3ef42575df84b30b$export$9d1611c77c2fe928(buttonProps, {
      "aria-pressed": isSelected
    })
  };
}
function getSharedButtonStyle(variant, color2) {
  let style2 = [];
  if (variant === "outline") {
    style2 = outline(color2);
  } else if (variant === "text") {
    style2 = text(color2);
  } else if (variant === "flat" || variant === "raised") {
    style2 = contained(color2);
  }
  return [...style2, variant === "raised" && "shadow-md", variant && "align-middle whitespace-nowrap inline-flex items-center transition-button duration-200", "select-none appearance-none no-underline outline-none disabled:pointer-events-none disabled:cursor-default"];
}
function outline(color2) {
  const disabled = "disabled:text-disabled disabled:bg-transparent disabled:border-disabled-bg";
  switch (color2) {
    case "primary":
      return ["text-primary bg-transparent border border-primary/50", "hover:bg-primary/hover hover:border-primary", disabled];
    case "error":
      return ["text-error bg-transparent border border-error/50", "hover:bg-error/4 hover:border-error", disabled];
    case "paper":
      return ["text bg-paper border", "hover:bg-hover", disabled];
    default:
      return ["text-current bg-transparent border", "hover:bg-hover", disabled];
  }
}
function text(color2) {
  const disabled = "disabled:text-disabled disabled:bg-transparent";
  switch (color2) {
    case "primary":
      return ["text-primary bg-transparent border-transparent", "hover:bg-primary/4", disabled];
    case "error":
      return ["text-error bg-transparent border-transparent", "hover:bg-error/4", disabled];
    default:
      return ["text-current bg-transparent border-transparent", "hover:bg-hover", disabled];
  }
}
function contained(color2) {
  const disabled = "disabled:text-disabled disabled:bg-disabled disabled:border-transparent disabled:shadow-none";
  switch (color2) {
    case "primary":
      return ["text-on-primary bg-primary border border-primary", "hover:bg-primary-dark hover:border-primary-dark", disabled];
    case "error":
      return ["text-on-error bg-error border border-error", "hover:bg-error/90 hover:border-error/90", disabled];
    default:
      return ["text-current bg border-background", "hover:bg-hover", disabled];
  }
}
const ButtonBase = React__default.forwardRef((props2, ref) => {
  const {
    children,
    color: color2 = null,
    variant,
    radius,
    justify = "justify-center",
    className,
    href,
    style: style2
  } = props2;
  const {
    isFocusVisible,
    focusProps
  } = $e63d024ca16f2165$export$4e328f61c538687f();
  const {
    buttonProps,
    isPressed
  } = $4e9d283129286548$export$ea18c227d4417cc3(__spreadProps(__spreadValues({}, props2), {
    elementType: href ? "a" : "button"
  }), ref);
  const Element2 = href ? "a" : "button";
  return /* @__PURE__ */ jsx(Element2, __spreadProps(__spreadValues({}, $3ef42575df84b30b$export$9d1611c77c2fe928(buttonProps, focusProps)), {
    ref,
    style: style2,
    className: clsx(isPressed && "translate-y-1", isFocusVisible && "outline outline-offset-2", getSharedButtonStyle(variant, color2), radius, justify, className),
    children
  }));
});
const Button = React__default.forwardRef((_g, ref) => {
  var _h = _g, {
    children,
    startIcon,
    endIcon,
    size,
    className,
    equalWidth = false,
    radius = "rounded",
    variant = "flat"
  } = _h, other = __objRest(_h, [
    "children",
    "startIcon",
    "endIcon",
    "size",
    "className",
    "equalWidth",
    "radius",
    "variant"
  ]);
  const mergedClassName = clsx("font-semibold", getButtonSizeStyle(size, {
    equalWidth
  }), className);
  const iconSize = getIconSizeStyle(size);
  return /* @__PURE__ */ jsxs(ButtonBase, __spreadProps(__spreadValues({
    className: mergedClassName,
    ref,
    radius,
    variant
  }, other), {
    children: [startIcon && /* @__PURE__ */ jsx(InlineIcon, {
      position: "start",
      icon: startIcon,
      size: iconSize
    }), children, endIcon && /* @__PURE__ */ jsx(InlineIcon, {
      position: "end",
      icon: endIcon,
      size: iconSize
    })]
  }));
});
function InlineIcon({
  icon,
  position: position2,
  size
}) {
  const className = clsx("m-auto", size, {
    "-ml-4 mr-8": position2 === "start",
    "-mr-4 ml-8": position2 === "end"
  }, icon.props.className);
  return React__default.cloneElement(icon, {
    className
  });
}
function $parcel$export$u(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $89e587cd0f107a73$exports = {};
$parcel$export$u($89e587cd0f107a73$exports, "Item", () => $89e587cd0f107a73$export$6d08773d2e66f8f2);
function $89e587cd0f107a73$var$Item(props2) {
  return null;
}
$89e587cd0f107a73$var$Item.getCollectionNode = function* getCollectionNode(props2, context) {
  let { childItems, title, children } = props2;
  let rendered = props2.title || props2.children;
  let textValue = props2.textValue || (typeof rendered === "string" ? rendered : "") || props2["aria-label"] || "";
  if (!textValue && !(context === null || context === void 0 ? void 0 : context.suppressTextValueWarning))
    console.warn("<Item> with non-plain text contents is unsupported by type to select for accessibility. Please add a `textValue` prop.");
  yield {
    type: "item",
    props: props2,
    rendered,
    textValue,
    "aria-label": props2["aria-label"],
    hasChildNodes: $89e587cd0f107a73$var$hasChildItems(props2),
    *childNodes() {
      if (childItems)
        for (let child1 of childItems)
          yield {
            type: "item",
            value: child1
          };
      else if (title) {
        let items = [];
        React__default.Children.forEach(children, (child) => {
          items.push({
            type: "item",
            element: child
          });
        });
        yield* items;
      }
    }
  };
};
function $89e587cd0f107a73$var$hasChildItems(props2) {
  if (props2.hasChildItems != null)
    return props2.hasChildItems;
  if (props2.childItems)
    return true;
  if (props2.title && React__default.Children.count(props2.children) > 0)
    return true;
  return false;
}
let $89e587cd0f107a73$export$6d08773d2e66f8f2 = $89e587cd0f107a73$var$Item;
var $c8f15027e29c0fc9$exports = {};
$parcel$export$u($c8f15027e29c0fc9$exports, "Section", () => $c8f15027e29c0fc9$export$6e2c8f0811a474ce);
function $c8f15027e29c0fc9$var$Section(props2) {
  return null;
}
$c8f15027e29c0fc9$var$Section.getCollectionNode = function* getCollectionNode2(props2) {
  let { children, title, items: items1 } = props2;
  yield {
    type: "section",
    hasChildNodes: true,
    rendered: title,
    "aria-label": props2["aria-label"],
    *childNodes() {
      if (typeof children === "function") {
        if (!items1)
          throw new Error("props.children was a function but props.items is missing");
        for (let item of items1)
          yield {
            type: "item",
            value: item,
            renderer: children
          };
      } else {
        let items = [];
        React__default.Children.forEach(children, (child) => {
          items.push({
            type: "item",
            element: child
          });
        });
        yield* items;
      }
    }
  };
};
let $c8f15027e29c0fc9$export$6e2c8f0811a474ce = $c8f15027e29c0fc9$var$Section;
var $54e9526d7573190f$exports = {};
$parcel$export$u($54e9526d7573190f$exports, "useCollection", () => $54e9526d7573190f$export$6cd28814d92fa9c9);
class $04d34f0d1495595c$export$bf788dd355e3a401 {
  build(props2, context) {
    this.context = context;
    return $04d34f0d1495595c$var$iterable(() => this.iterateCollection(props2));
  }
  *iterateCollection(props2) {
    let { children, items } = props2;
    if (typeof children === "function") {
      if (!items)
        throw new Error("props.children was a function but props.items is missing");
      for (let item of props2.items)
        yield* this.getFullNode({
          value: item
        }, {
          renderer: children
        });
    } else {
      let items2 = [];
      React__default.Children.forEach(children, (child) => {
        items2.push(child);
      });
      let index2 = 0;
      for (let item of items2) {
        let nodes = this.getFullNode({
          element: item,
          index: index2
        }, {});
        for (let node of nodes) {
          index2++;
          yield node;
        }
      }
    }
  }
  getKey(item, partialNode, state2, parentKey) {
    if (item.key != null)
      return item.key;
    if (partialNode.type === "cell" && partialNode.key != null)
      return `${parentKey}${partialNode.key}`;
    let v2 = partialNode.value;
    if (v2 != null) {
      var _key;
      let key = (_key = v2.key) !== null && _key !== void 0 ? _key : v2.id;
      if (key == null)
        throw new Error("No key found for item");
      return key;
    }
    return parentKey ? `${parentKey}.${partialNode.index}` : `$.${partialNode.index}`;
  }
  getChildState(state2, partialNode) {
    return {
      renderer: partialNode.renderer || state2.renderer
    };
  }
  *getFullNode(partialNode, state2, parentKey, parentNode) {
    let element = partialNode.element;
    if (!element && partialNode.value && state2 && state2.renderer) {
      let cached = this.cache.get(partialNode.value);
      if (cached && (!cached.shouldInvalidate || !cached.shouldInvalidate(this.context))) {
        cached.index = partialNode.index;
        cached.parentKey = parentNode ? parentNode.key : null;
        yield cached;
        return;
      }
      element = state2.renderer(partialNode.value);
    }
    if (React__default.isValidElement(element)) {
      let type = element.type;
      if (typeof type !== "function" && typeof type.getCollectionNode !== "function") {
        let name = typeof element.type === "function" ? element.type.name : element.type;
        throw new Error(`Unknown element <${name}> in collection.`);
      }
      let childNodes = type.getCollectionNode(element.props, this.context);
      let index2 = partialNode.index;
      let result = childNodes.next();
      while (!result.done && result.value) {
        let childNode = result.value;
        partialNode.index = index2;
        let nodeKey = childNode.key;
        if (!nodeKey)
          nodeKey = childNode.element ? null : this.getKey(element, partialNode, state2, parentKey);
        let nodes = this.getFullNode(__spreadProps(__spreadValues({}, childNode), {
          key: nodeKey,
          index: index2,
          wrapper: $04d34f0d1495595c$var$compose(partialNode.wrapper, childNode.wrapper)
        }), this.getChildState(state2, childNode), parentKey ? `${parentKey}${element.key}` : element.key, parentNode);
        let children = [
          ...nodes
        ];
        for (let node2 of children) {
          node2.value = childNode.value || partialNode.value;
          if (node2.value)
            this.cache.set(node2.value, node2);
          if (partialNode.type && node2.type !== partialNode.type)
            throw new Error(`Unsupported type <${$04d34f0d1495595c$var$capitalize(node2.type)}> in <${$04d34f0d1495595c$var$capitalize(parentNode.type)}>. Only <${$04d34f0d1495595c$var$capitalize(partialNode.type)}> is supported.`);
          index2++;
          yield node2;
        }
        result = childNodes.next(children);
      }
      return;
    }
    if (partialNode.key == null)
      return;
    let builder = this;
    let node = {
      type: partialNode.type,
      props: partialNode.props,
      key: partialNode.key,
      parentKey: parentNode ? parentNode.key : null,
      value: partialNode.value,
      level: parentNode ? parentNode.level + 1 : 0,
      index: partialNode.index,
      rendered: partialNode.rendered,
      textValue: partialNode.textValue,
      "aria-label": partialNode["aria-label"],
      wrapper: partialNode.wrapper,
      shouldInvalidate: partialNode.shouldInvalidate,
      hasChildNodes: partialNode.hasChildNodes,
      childNodes: $04d34f0d1495595c$var$iterable(function* () {
        if (!partialNode.hasChildNodes)
          return;
        let index2 = 0;
        for (let child of partialNode.childNodes()) {
          if (child.key != null)
            child.key = `${node.key}${child.key}`;
          child.index = index2;
          let nodes = builder.getFullNode(child, builder.getChildState(state2, child), node.key, node);
          for (let node1 of nodes) {
            index2++;
            yield node1;
          }
        }
      })
    };
    yield node;
  }
  constructor() {
    this.cache = /* @__PURE__ */ new WeakMap();
  }
}
function $04d34f0d1495595c$var$iterable(iterator) {
  let cache = [];
  let iterable = null;
  return {
    *[Symbol.iterator]() {
      for (let item of cache)
        yield item;
      if (!iterable)
        iterable = iterator();
      for (let item1 of iterable) {
        cache.push(item1);
        yield item1;
      }
    }
  };
}
function $04d34f0d1495595c$var$compose(outer, inner) {
  if (outer && inner)
    return (element) => outer(inner(element));
  if (outer)
    return outer;
  if (inner)
    return inner;
}
function $04d34f0d1495595c$var$capitalize(str) {
  return str[0].toUpperCase() + str.slice(1);
}
function $54e9526d7573190f$export$6cd28814d92fa9c9(props2, factory, context, invalidators = []) {
  let builder = useMemo(() => new $04d34f0d1495595c$export$bf788dd355e3a401(), []);
  let prev = useRef(null);
  return useMemo(() => {
    let nodes = builder.build(props2, context);
    prev.current = factory(nodes, prev.current);
    return prev.current;
  }, [
    builder,
    props2.children,
    props2.items,
    context,
    ...invalidators
  ]);
}
var $c6b7d36982dcfffc$exports = {};
$parcel$export$u($c6b7d36982dcfffc$exports, "getItemCount", () => $c6b7d36982dcfffc$export$77d5aafae4e095b2);
const $c6b7d36982dcfffc$var$cache = /* @__PURE__ */ new WeakMap();
function $c6b7d36982dcfffc$export$77d5aafae4e095b2(collection) {
  let count = $c6b7d36982dcfffc$var$cache.get(collection);
  if (count != null)
    return count;
  count = 0;
  for (let item of collection)
    if (item.type === "section")
      count += $c6b7d36982dcfffc$export$77d5aafae4e095b2(item.childNodes);
    else
      count++;
  $c6b7d36982dcfffc$var$cache.set(collection, count);
  return count;
}
function $parcel$export$t(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $fc909762b330b746$exports = {};
$parcel$export$t($fc909762b330b746$exports, "useOverlayTriggerState", () => $fc909762b330b746$export$61c6a8c84e605fb6);
function $fc909762b330b746$export$61c6a8c84e605fb6(props2) {
  let [isOpen, setOpen] = $bfee1151ccb0650f$export$40bfa8c7b0832715(props2.isOpen, props2.defaultOpen || false, props2.onOpenChange);
  return {
    isOpen,
    open() {
      setOpen(true);
    },
    close() {
      setOpen(false);
    },
    toggle() {
      setOpen(!isOpen);
    }
  };
}
function $parcel$export$s(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $89a94a12744b972a$exports = {};
$parcel$export$s($89a94a12744b972a$exports, "useMenuTriggerState", () => $89a94a12744b972a$export$79fefeb1c2091ac3);
function $89a94a12744b972a$export$79fefeb1c2091ac3(props2) {
  let overlayTriggerState = $fc909762b330b746$export$61c6a8c84e605fb6(props2);
  let [focusStrategy1, setFocusStrategy] = useState(null);
  return __spreadProps(__spreadValues({
    focusStrategy: focusStrategy1
  }, overlayTriggerState), {
    open(focusStrategy = null) {
      setFocusStrategy(focusStrategy);
      overlayTriggerState.open();
    },
    toggle(focusStrategy = null) {
      setFocusStrategy(focusStrategy);
      overlayTriggerState.toggle();
    }
  });
}
function $parcel$export$r(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $70eee6030fd7c1a1$exports = {};
$parcel$export$r($70eee6030fd7c1a1$exports, "MessageDictionary", () => $70eee6030fd7c1a1$export$64839e615120df17);
class $70eee6030fd7c1a1$export$64839e615120df17 {
  getStringForLocale(key, locale) {
    let strings = this.messages[locale];
    if (!strings) {
      strings = $70eee6030fd7c1a1$var$getStringsForLocale(locale, this.messages, this.defaultLocale);
      this.messages[locale] = strings;
    }
    let string = strings[key];
    if (!string)
      throw new Error(`Could not find intl message ${key} in ${locale} locale`);
    return string;
  }
  constructor(messages2, defaultLocale = "en-US") {
    this.messages = __spreadValues({}, messages2);
    this.defaultLocale = defaultLocale;
  }
}
function $70eee6030fd7c1a1$var$getStringsForLocale(locale, strings, defaultLocale = "en-US") {
  if (strings[locale])
    return strings[locale];
  let language = $70eee6030fd7c1a1$var$getLanguage(locale);
  for (let key in strings) {
    if (key.startsWith(language + "-"))
      return strings[key];
  }
  return strings[defaultLocale];
}
function $70eee6030fd7c1a1$var$getLanguage(locale) {
  if (Intl.Locale)
    return new Intl.Locale(locale).language;
  return locale.split("-")[0];
}
var $a96338b8d4eb3cb0$exports = {};
$parcel$export$r($a96338b8d4eb3cb0$exports, "MessageFormatter", () => $a96338b8d4eb3cb0$export$526ebc05ff964723);
class $a96338b8d4eb3cb0$export$526ebc05ff964723 {
  format(key, variables) {
    let message = this.cache[key];
    if (!message) {
      let msg = this.messages.getStringForLocale(key, this.locale);
      if (!msg)
        throw new Error(`Could not find intl message ${key} in ${this.locale} locale`);
      message = new $1Ofoe$intlmessageformat(msg, this.locale);
      this.cache[key] = message;
    }
    let varCopy;
    if (variables)
      varCopy = Object.keys(variables).reduce((acc, key2) => {
        acc[key2] = variables[key2] == null ? false : variables[key2];
        return acc;
      }, {});
    return message.format(varCopy);
  }
  constructor(locale, messages2) {
    this.locale = locale;
    this.messages = messages2;
    this.cache = {};
  }
}
function $parcel$export$q(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $418a5bbf7b2f3448$exports = {};
$parcel$export$q($418a5bbf7b2f3448$exports, "CalendarDate", () => $418a5bbf7b2f3448$export$99faa760c7908e4f);
$parcel$export$q($418a5bbf7b2f3448$exports, "Time", () => $418a5bbf7b2f3448$export$680ea196effce5f);
$parcel$export$q($418a5bbf7b2f3448$exports, "CalendarDateTime", () => $418a5bbf7b2f3448$export$ca871e8dbb80966f);
$parcel$export$q($418a5bbf7b2f3448$exports, "ZonedDateTime", () => $418a5bbf7b2f3448$export$d3b7288e7994edea);
var $9ab2a87bc84c0bfa$exports = {};
$parcel$export$q($9ab2a87bc84c0bfa$exports, "epochFromDate", () => $9ab2a87bc84c0bfa$export$bd4fb2bc8bb06fb);
$parcel$export$q($9ab2a87bc84c0bfa$exports, "toCalendar", () => $9ab2a87bc84c0bfa$export$b4a036af3fc0b032);
$parcel$export$q($9ab2a87bc84c0bfa$exports, "getTimeZoneOffset", () => $9ab2a87bc84c0bfa$export$59c99f3515d3493f);
$parcel$export$q($9ab2a87bc84c0bfa$exports, "possibleAbsolutes", () => $9ab2a87bc84c0bfa$export$136f38efe7caf549);
$parcel$export$q($9ab2a87bc84c0bfa$exports, "toAbsolute", () => $9ab2a87bc84c0bfa$export$5107c82f94518f5c);
$parcel$export$q($9ab2a87bc84c0bfa$exports, "toCalendarDateTime", () => $9ab2a87bc84c0bfa$export$b21e0b124e224484);
$parcel$export$q($9ab2a87bc84c0bfa$exports, "toDate", () => $9ab2a87bc84c0bfa$export$e67a095c620b86fe);
$parcel$export$q($9ab2a87bc84c0bfa$exports, "fromAbsolute", () => $9ab2a87bc84c0bfa$export$1b96692a1ba042ac);
$parcel$export$q($9ab2a87bc84c0bfa$exports, "fromDate", () => $9ab2a87bc84c0bfa$export$e57ff100d91bd4b9);
$parcel$export$q($9ab2a87bc84c0bfa$exports, "fromDateToLocal", () => $9ab2a87bc84c0bfa$export$d7f92bcd3596b086);
$parcel$export$q($9ab2a87bc84c0bfa$exports, "toCalendarDate", () => $9ab2a87bc84c0bfa$export$93522d1a439f3617);
$parcel$export$q($9ab2a87bc84c0bfa$exports, "toDateFields", () => $9ab2a87bc84c0bfa$export$6f4d78149f3f53ac);
$parcel$export$q($9ab2a87bc84c0bfa$exports, "toTimeFields", () => $9ab2a87bc84c0bfa$export$4d0393e732857be5);
$parcel$export$q($9ab2a87bc84c0bfa$exports, "toTime", () => $9ab2a87bc84c0bfa$export$d33f79e3ffc3dc83);
$parcel$export$q($9ab2a87bc84c0bfa$exports, "toZoned", () => $9ab2a87bc84c0bfa$export$84c95a83c799e074);
$parcel$export$q($9ab2a87bc84c0bfa$exports, "toTimeZone", () => $9ab2a87bc84c0bfa$export$538b00033cc11c75);
$parcel$export$q($9ab2a87bc84c0bfa$exports, "zonedToDate", () => $9ab2a87bc84c0bfa$export$83aac07b4c37b25);
$parcel$export$q($9ab2a87bc84c0bfa$exports, "toLocalTimeZone", () => $9ab2a87bc84c0bfa$export$d9b67bc93c097491);
var $571ccebef3ef72f1$exports = {};
$parcel$export$q($571ccebef3ef72f1$exports, "isSameDay", () => $571ccebef3ef72f1$export$ea39ec197993aef0);
$parcel$export$q($571ccebef3ef72f1$exports, "isSameMonth", () => $571ccebef3ef72f1$export$a18c89cbd24170ff);
$parcel$export$q($571ccebef3ef72f1$exports, "startOfMonth", () => $571ccebef3ef72f1$export$a5a3b454ada2268e);
$parcel$export$q($571ccebef3ef72f1$exports, "isSameYear", () => $571ccebef3ef72f1$export$5841f9eb9773f25f);
$parcel$export$q($571ccebef3ef72f1$exports, "startOfYear", () => $571ccebef3ef72f1$export$f91e89d3d0406102);
$parcel$export$q($571ccebef3ef72f1$exports, "isEqualDay", () => $571ccebef3ef72f1$export$91b62ebf2ba703ee);
$parcel$export$q($571ccebef3ef72f1$exports, "isEqualMonth", () => $571ccebef3ef72f1$export$5a8da0c44a3afdf2);
$parcel$export$q($571ccebef3ef72f1$exports, "isEqualYear", () => $571ccebef3ef72f1$export$ea840f5a6dda8147);
$parcel$export$q($571ccebef3ef72f1$exports, "isToday", () => $571ccebef3ef72f1$export$629b0a497aa65267);
$parcel$export$q($571ccebef3ef72f1$exports, "today", () => $571ccebef3ef72f1$export$d0bdf45af03a6ea3);
$parcel$export$q($571ccebef3ef72f1$exports, "getDayOfWeek", () => $571ccebef3ef72f1$export$2061056d06d7cdf7);
$parcel$export$q($571ccebef3ef72f1$exports, "now", () => $571ccebef3ef72f1$export$461939dd4422153);
$parcel$export$q($571ccebef3ef72f1$exports, "compareDate", () => $571ccebef3ef72f1$export$68781ddf31c0090f);
$parcel$export$q($571ccebef3ef72f1$exports, "compareTime", () => $571ccebef3ef72f1$export$c19a80a9721b80f6);
$parcel$export$q($571ccebef3ef72f1$exports, "getHoursInDay", () => $571ccebef3ef72f1$export$126c91c941de7e);
$parcel$export$q($571ccebef3ef72f1$exports, "getLocalTimeZone", () => $571ccebef3ef72f1$export$aa8b41735afcabd2);
$parcel$export$q($571ccebef3ef72f1$exports, "endOfMonth", () => $571ccebef3ef72f1$export$a2258d9c4118825c);
$parcel$export$q($571ccebef3ef72f1$exports, "endOfYear", () => $571ccebef3ef72f1$export$8b7aa55c66d5569e);
$parcel$export$q($571ccebef3ef72f1$exports, "getMinimumMonthInYear", () => $571ccebef3ef72f1$export$5412ac11713b72ad);
$parcel$export$q($571ccebef3ef72f1$exports, "getMinimumDayInMonth", () => $571ccebef3ef72f1$export$b2f4953d301981d5);
$parcel$export$q($571ccebef3ef72f1$exports, "startOfWeek", () => $571ccebef3ef72f1$export$42c81a444fbfb5d4);
$parcel$export$q($571ccebef3ef72f1$exports, "endOfWeek", () => $571ccebef3ef72f1$export$ef8b6d9133084f4e);
$parcel$export$q($571ccebef3ef72f1$exports, "getWeeksInMonth", () => $571ccebef3ef72f1$export$ccc1b2479e7dd654);
$parcel$export$q($571ccebef3ef72f1$exports, "minDate", () => $571ccebef3ef72f1$export$5c333a116e949cdd);
$parcel$export$q($571ccebef3ef72f1$exports, "maxDate", () => $571ccebef3ef72f1$export$a75f2bff57811055);
$parcel$export$q($571ccebef3ef72f1$exports, "isWeekend", () => $571ccebef3ef72f1$export$618d60ea299da42);
$parcel$export$q($571ccebef3ef72f1$exports, "isWeekday", () => $571ccebef3ef72f1$export$ee9d87258e1d19ed);
const $7470da919d0ed06d$export$7a5acbd77d414bd9 = {
  "001": 1,
  AD: 1,
  AE: 6,
  AF: 6,
  AI: 1,
  AL: 1,
  AM: 1,
  AN: 1,
  AT: 1,
  AX: 1,
  AZ: 1,
  BA: 1,
  BE: 1,
  BG: 1,
  BH: 6,
  BM: 1,
  BN: 1,
  BY: 1,
  CH: 1,
  CL: 1,
  CM: 1,
  CR: 1,
  CY: 1,
  CZ: 1,
  DE: 1,
  DJ: 6,
  DK: 1,
  DZ: 6,
  EC: 1,
  EE: 1,
  EG: 6,
  ES: 1,
  FI: 1,
  FJ: 1,
  FO: 1,
  FR: 1,
  GB: 1,
  GE: 1,
  GF: 1,
  GP: 1,
  GR: 1,
  HR: 1,
  HU: 1,
  IE: 1,
  IQ: 6,
  IR: 6,
  IS: 1,
  IT: 1,
  JO: 6,
  KG: 1,
  KW: 6,
  KZ: 1,
  LB: 1,
  LI: 1,
  LK: 1,
  LT: 1,
  LU: 1,
  LV: 1,
  LY: 6,
  MC: 1,
  MD: 1,
  ME: 1,
  MK: 1,
  MN: 1,
  MQ: 1,
  MV: 5,
  MY: 1,
  NL: 1,
  NO: 1,
  NZ: 1,
  OM: 6,
  PL: 1,
  QA: 6,
  RE: 1,
  RO: 1,
  RS: 1,
  RU: 1,
  SD: 6,
  SE: 1,
  SI: 1,
  SK: 1,
  SM: 1,
  SY: 6,
  TJ: 1,
  TM: 1,
  TR: 1,
  UA: 1,
  UY: 1,
  UZ: 1,
  VA: 1,
  VN: 1,
  XK: 1
};
function $571ccebef3ef72f1$export$ea39ec197993aef0(a2, b2) {
  b2 = $9ab2a87bc84c0bfa$export$b4a036af3fc0b032(b2, a2.calendar);
  return a2.era === b2.era && a2.year === b2.year && a2.month === b2.month && a2.day === b2.day;
}
function $571ccebef3ef72f1$export$a18c89cbd24170ff(a2, b2) {
  b2 = $9ab2a87bc84c0bfa$export$b4a036af3fc0b032(b2, a2.calendar);
  a2 = $571ccebef3ef72f1$export$a5a3b454ada2268e(a2);
  b2 = $571ccebef3ef72f1$export$a5a3b454ada2268e(b2);
  return a2.era === b2.era && a2.year === b2.year && a2.month === b2.month;
}
function $571ccebef3ef72f1$export$5841f9eb9773f25f(a2, b2) {
  b2 = $9ab2a87bc84c0bfa$export$b4a036af3fc0b032(b2, a2.calendar);
  a2 = $571ccebef3ef72f1$export$f91e89d3d0406102(a2);
  b2 = $571ccebef3ef72f1$export$f91e89d3d0406102(b2);
  return a2.era === b2.era && a2.year === b2.year;
}
function $571ccebef3ef72f1$export$91b62ebf2ba703ee(a2, b2) {
  return a2.calendar.identifier === b2.calendar.identifier && a2.era === b2.era && a2.year === b2.year && a2.month === b2.month && a2.day === b2.day;
}
function $571ccebef3ef72f1$export$5a8da0c44a3afdf2(a2, b2) {
  a2 = $571ccebef3ef72f1$export$a5a3b454ada2268e(a2);
  b2 = $571ccebef3ef72f1$export$a5a3b454ada2268e(b2);
  return a2.calendar.identifier === b2.calendar.identifier && a2.era === b2.era && a2.year === b2.year && a2.month === b2.month;
}
function $571ccebef3ef72f1$export$ea840f5a6dda8147(a2, b2) {
  a2 = $571ccebef3ef72f1$export$f91e89d3d0406102(a2);
  b2 = $571ccebef3ef72f1$export$f91e89d3d0406102(b2);
  return a2.calendar.identifier === b2.calendar.identifier && a2.era === b2.era && a2.year === b2.year;
}
function $571ccebef3ef72f1$export$629b0a497aa65267(date, timeZone) {
  return $571ccebef3ef72f1$export$ea39ec197993aef0(date, $571ccebef3ef72f1$export$d0bdf45af03a6ea3(timeZone));
}
function $571ccebef3ef72f1$export$2061056d06d7cdf7(date, locale) {
  let julian = date.calendar.toJulianDay(date);
  let dayOfWeek = Math.ceil(julian + 1 - $571ccebef3ef72f1$var$getWeekStart(locale)) % 7;
  if (dayOfWeek < 0)
    dayOfWeek += 7;
  return dayOfWeek;
}
function $571ccebef3ef72f1$export$461939dd4422153(timeZone) {
  return $9ab2a87bc84c0bfa$export$1b96692a1ba042ac(Date.now(), timeZone);
}
function $571ccebef3ef72f1$export$d0bdf45af03a6ea3(timeZone) {
  return $9ab2a87bc84c0bfa$export$93522d1a439f3617($571ccebef3ef72f1$export$461939dd4422153(timeZone));
}
function $571ccebef3ef72f1$export$68781ddf31c0090f(a2, b2) {
  return a2.calendar.toJulianDay(a2) - b2.calendar.toJulianDay(b2);
}
function $571ccebef3ef72f1$export$c19a80a9721b80f6(a2, b2) {
  return $571ccebef3ef72f1$var$timeToMs(a2) - $571ccebef3ef72f1$var$timeToMs(b2);
}
function $571ccebef3ef72f1$var$timeToMs(a2) {
  return a2.hour * 36e5 + a2.minute * 6e4 + a2.second * 1e3 + a2.millisecond;
}
function $571ccebef3ef72f1$export$126c91c941de7e(a2, timeZone) {
  let ms = $9ab2a87bc84c0bfa$export$5107c82f94518f5c(a2, timeZone);
  let tomorrow = a2.add({
    days: 1
  });
  let tomorrowMs = $9ab2a87bc84c0bfa$export$5107c82f94518f5c(tomorrow, timeZone);
  return (tomorrowMs - ms) / 36e5;
}
let $571ccebef3ef72f1$var$localTimeZone = null;
function $571ccebef3ef72f1$export$aa8b41735afcabd2() {
  if ($571ccebef3ef72f1$var$localTimeZone == null)
    $571ccebef3ef72f1$var$localTimeZone = new Intl.DateTimeFormat().resolvedOptions().timeZone;
  return $571ccebef3ef72f1$var$localTimeZone;
}
function $571ccebef3ef72f1$export$a5a3b454ada2268e(date) {
  return date.subtract({
    days: date.day - 1
  });
}
function $571ccebef3ef72f1$export$a2258d9c4118825c(date) {
  return date.add({
    days: date.calendar.getDaysInMonth(date) - date.day
  });
}
function $571ccebef3ef72f1$export$f91e89d3d0406102(date) {
  return $571ccebef3ef72f1$export$a5a3b454ada2268e(date.subtract({
    months: date.month - 1
  }));
}
function $571ccebef3ef72f1$export$8b7aa55c66d5569e(date) {
  return $571ccebef3ef72f1$export$a2258d9c4118825c(date.add({
    months: date.calendar.getMonthsInYear(date) - date.month
  }));
}
function $571ccebef3ef72f1$export$5412ac11713b72ad(date) {
  if (date.calendar.getMinimumMonthInYear)
    return date.calendar.getMinimumMonthInYear(date);
  return 1;
}
function $571ccebef3ef72f1$export$b2f4953d301981d5(date) {
  if (date.calendar.getMinimumDayInMonth)
    return date.calendar.getMinimumDayInMonth(date);
  return 1;
}
function $571ccebef3ef72f1$export$42c81a444fbfb5d4(date, locale) {
  let dayOfWeek = $571ccebef3ef72f1$export$2061056d06d7cdf7(date, locale);
  return date.subtract({
    days: dayOfWeek
  });
}
function $571ccebef3ef72f1$export$ef8b6d9133084f4e(date, locale) {
  return $571ccebef3ef72f1$export$42c81a444fbfb5d4(date, locale).add({
    days: 6
  });
}
const $571ccebef3ef72f1$var$cachedRegions = /* @__PURE__ */ new Map();
function $571ccebef3ef72f1$var$getRegion(locale) {
  if (Intl.Locale) {
    let region = $571ccebef3ef72f1$var$cachedRegions.get(locale);
    if (!region) {
      region = new Intl.Locale(locale).maximize().region;
      $571ccebef3ef72f1$var$cachedRegions.set(locale, region);
    }
    return region;
  }
  let part = locale.split("-")[1];
  return part === "u" ? null : part;
}
function $571ccebef3ef72f1$var$getWeekStart(locale) {
  let region = $571ccebef3ef72f1$var$getRegion(locale);
  return $7470da919d0ed06d$export$7a5acbd77d414bd9[region] || 0;
}
function $571ccebef3ef72f1$export$ccc1b2479e7dd654(date, locale) {
  let days = date.calendar.getDaysInMonth(date);
  return Math.ceil(($571ccebef3ef72f1$export$2061056d06d7cdf7($571ccebef3ef72f1$export$a5a3b454ada2268e(date), locale) + days) / 7);
}
function $571ccebef3ef72f1$export$5c333a116e949cdd(a2, b2) {
  return a2.compare(b2) <= 0 ? a2 : b2;
}
function $571ccebef3ef72f1$export$a75f2bff57811055(a2, b2) {
  return a2.compare(b2) >= 0 ? a2 : b2;
}
const $571ccebef3ef72f1$var$WEEKEND_DATA = {
  AF: [
    4,
    5
  ],
  AE: [
    5,
    6
  ],
  BH: [
    5,
    6
  ],
  DZ: [
    5,
    6
  ],
  EG: [
    5,
    6
  ],
  IL: [
    5,
    6
  ],
  IQ: [
    5,
    6
  ],
  IR: [
    5,
    5
  ],
  JO: [
    5,
    6
  ],
  KW: [
    5,
    6
  ],
  LY: [
    5,
    6
  ],
  OM: [
    5,
    6
  ],
  QA: [
    5,
    6
  ],
  SA: [
    5,
    6
  ],
  SD: [
    5,
    6
  ],
  SY: [
    5,
    6
  ],
  YE: [
    5,
    6
  ]
};
function $571ccebef3ef72f1$export$618d60ea299da42(date, locale) {
  let julian = date.calendar.toJulianDay(date);
  let dayOfWeek = Math.ceil(julian + 1) % 7;
  if (dayOfWeek < 0)
    dayOfWeek += 7;
  let region = $571ccebef3ef72f1$var$getRegion(locale);
  let [start, end] = $571ccebef3ef72f1$var$WEEKEND_DATA[region] || [
    6,
    0
  ];
  return dayOfWeek === start || dayOfWeek === end;
}
function $571ccebef3ef72f1$export$ee9d87258e1d19ed(date, locale) {
  return !$571ccebef3ef72f1$export$618d60ea299da42(date, locale);
}
function $6a413dc772e69324$export$842a2cf37af977e1(amount, numerator) {
  return amount - numerator * Math.floor(amount / numerator);
}
const $22a507fc519bfd45$var$EPOCH = 1721426;
function $22a507fc519bfd45$export$f297eb839006d339(year, month, day) {
  let y1 = year - 1;
  let monthOffset = -2;
  if (month <= 2)
    monthOffset = 0;
  else if ($22a507fc519bfd45$export$553d7fa8e3805fc0(year))
    monthOffset = -1;
  return $22a507fc519bfd45$var$EPOCH - 1 + 365 * y1 + Math.floor(y1 / 4) - Math.floor(y1 / 100) + Math.floor(y1 / 400) + Math.floor((367 * month - 362) / 12 + monthOffset + day);
}
function $22a507fc519bfd45$export$553d7fa8e3805fc0(year) {
  return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}
const $22a507fc519bfd45$var$daysInMonth = {
  standard: [
    31,
    28,
    31,
    30,
    31,
    30,
    31,
    31,
    30,
    31,
    30,
    31
  ],
  leapyear: [
    31,
    29,
    31,
    30,
    31,
    30,
    31,
    31,
    30,
    31,
    30,
    31
  ]
};
class $22a507fc519bfd45$export$80ee6245ec4f29ec {
  fromJulianDay(jd) {
    let jd0 = jd;
    let depoch = jd0 - $22a507fc519bfd45$var$EPOCH;
    let quadricent = Math.floor(depoch / 146097);
    let dqc = $6a413dc772e69324$export$842a2cf37af977e1(depoch, 146097);
    let cent = Math.floor(dqc / 36524);
    let dcent = $6a413dc772e69324$export$842a2cf37af977e1(dqc, 36524);
    let quad = Math.floor(dcent / 1461);
    let dquad = $6a413dc772e69324$export$842a2cf37af977e1(dcent, 1461);
    let yindex = Math.floor(dquad / 365);
    let year = quadricent * 400 + cent * 100 + quad * 4 + yindex + (cent !== 4 && yindex !== 4 ? 1 : 0);
    let yearDay = jd0 - $22a507fc519bfd45$export$f297eb839006d339(year, 1, 1);
    let leapAdj = 2;
    if (jd0 < $22a507fc519bfd45$export$f297eb839006d339(year, 3, 1))
      leapAdj = 0;
    else if ($22a507fc519bfd45$export$553d7fa8e3805fc0(year))
      leapAdj = 1;
    let month = Math.floor(((yearDay + leapAdj) * 12 + 373) / 367);
    let day = jd0 - $22a507fc519bfd45$export$f297eb839006d339(year, month, 1) + 1;
    return new $418a5bbf7b2f3448$export$99faa760c7908e4f(this, year, month, day);
  }
  toJulianDay(date) {
    return $22a507fc519bfd45$export$f297eb839006d339(date.year, date.month, date.day);
  }
  getDaysInMonth(date) {
    return $22a507fc519bfd45$var$daysInMonth[$22a507fc519bfd45$export$553d7fa8e3805fc0(date.year) ? "leapyear" : "standard"][date.month - 1];
  }
  getMonthsInYear(date) {
    return 12;
  }
  getDaysInYear(date) {
    return $22a507fc519bfd45$export$553d7fa8e3805fc0(date.year) ? 366 : 365;
  }
  getYearsInEra(date) {
    return 9999;
  }
  getEras() {
    return [
      "BC",
      "AD"
    ];
  }
  getYearsToAdd(date, years) {
    return date.era === "BC" ? -years : years;
  }
  balanceDate(date) {
    if (date.year <= 0) {
      date.era = date.era === "BC" ? "AD" : "BC";
      date.year = 1 - date.year;
    }
  }
  constructor() {
    this.identifier = "gregory";
  }
}
function $9ab2a87bc84c0bfa$export$bd4fb2bc8bb06fb(date) {
  date = $9ab2a87bc84c0bfa$export$b4a036af3fc0b032(date, new $22a507fc519bfd45$export$80ee6245ec4f29ec());
  return $9ab2a87bc84c0bfa$var$epochFromParts(date.year, date.month, date.day, date.hour, date.minute, date.second, date.millisecond);
}
function $9ab2a87bc84c0bfa$var$epochFromParts(year, month, day, hour, minute, second, millisecond) {
  let date = new Date();
  date.setUTCHours(hour, minute, second, millisecond);
  date.setUTCFullYear(year, month - 1, day);
  return date.getTime();
}
function $9ab2a87bc84c0bfa$export$59c99f3515d3493f(ms, timeZone) {
  if (timeZone === $571ccebef3ef72f1$export$aa8b41735afcabd2())
    return new Date(ms).getTimezoneOffset() * -6e4;
  let { year, month, day, hour, minute, second } = $9ab2a87bc84c0bfa$var$getTimeZoneParts(ms, timeZone);
  let utc = $9ab2a87bc84c0bfa$var$epochFromParts(year, month, day, hour, minute, second, 0);
  return utc - Math.floor(ms / 1e3) * 1e3;
}
const $9ab2a87bc84c0bfa$var$formattersByTimeZone = /* @__PURE__ */ new Map();
function $9ab2a87bc84c0bfa$var$getTimeZoneParts(ms, timeZone) {
  let formatter = $9ab2a87bc84c0bfa$var$formattersByTimeZone.get(timeZone);
  if (!formatter) {
    formatter = new Intl.DateTimeFormat("en-US", {
      timeZone,
      hour12: false,
      era: "short",
      year: "numeric",
      month: "numeric",
      day: "numeric",
      hour: "numeric",
      minute: "numeric",
      second: "numeric"
    });
    $9ab2a87bc84c0bfa$var$formattersByTimeZone.set(timeZone, formatter);
  }
  let parts = formatter.formatToParts(new Date(ms));
  let namedParts = {};
  for (let part of parts)
    if (part.type !== "literal")
      namedParts[part.type] = part.value;
  return {
    year: namedParts.era === "BC" ? -namedParts.year + 1 : +namedParts.year,
    month: +namedParts.month,
    day: +namedParts.day,
    hour: namedParts.hour === "24" ? 0 : +namedParts.hour,
    minute: +namedParts.minute,
    second: +namedParts.second
  };
}
const $9ab2a87bc84c0bfa$var$DAYMILLIS = 864e5;
function $9ab2a87bc84c0bfa$export$136f38efe7caf549(date, timeZone) {
  let ms = $9ab2a87bc84c0bfa$export$bd4fb2bc8bb06fb(date);
  let earlier = ms - $9ab2a87bc84c0bfa$export$59c99f3515d3493f(ms - $9ab2a87bc84c0bfa$var$DAYMILLIS, timeZone);
  let later = ms - $9ab2a87bc84c0bfa$export$59c99f3515d3493f(ms + $9ab2a87bc84c0bfa$var$DAYMILLIS, timeZone);
  return $9ab2a87bc84c0bfa$var$getValidWallTimes(date, timeZone, earlier, later);
}
function $9ab2a87bc84c0bfa$var$getValidWallTimes(date, timeZone, earlier, later) {
  let found = earlier === later ? [
    earlier
  ] : [
    earlier,
    later
  ];
  return found.filter((absolute) => $9ab2a87bc84c0bfa$var$isValidWallTime(date, timeZone, absolute));
}
function $9ab2a87bc84c0bfa$var$isValidWallTime(date, timeZone, absolute) {
  let parts = $9ab2a87bc84c0bfa$var$getTimeZoneParts(absolute, timeZone);
  return date.year === parts.year && date.month === parts.month && date.day === parts.day && date.hour === parts.hour && date.minute === parts.minute && date.second === parts.second;
}
function $9ab2a87bc84c0bfa$export$5107c82f94518f5c(date, timeZone, disambiguation = "compatible") {
  let dateTime = $9ab2a87bc84c0bfa$export$b21e0b124e224484(date);
  if (timeZone === $571ccebef3ef72f1$export$aa8b41735afcabd2() && disambiguation === "compatible") {
    dateTime = $9ab2a87bc84c0bfa$export$b4a036af3fc0b032(dateTime, new $22a507fc519bfd45$export$80ee6245ec4f29ec());
    let date2 = new Date();
    date2.setFullYear(dateTime.year, dateTime.month - 1, dateTime.day);
    date2.setHours(dateTime.hour, dateTime.minute, dateTime.second, dateTime.millisecond);
    return date2.getTime();
  }
  let ms = $9ab2a87bc84c0bfa$export$bd4fb2bc8bb06fb(dateTime);
  let offsetBefore = $9ab2a87bc84c0bfa$export$59c99f3515d3493f(ms - $9ab2a87bc84c0bfa$var$DAYMILLIS, timeZone);
  let offsetAfter = $9ab2a87bc84c0bfa$export$59c99f3515d3493f(ms + $9ab2a87bc84c0bfa$var$DAYMILLIS, timeZone);
  let valid = $9ab2a87bc84c0bfa$var$getValidWallTimes(dateTime, timeZone, ms - offsetBefore, ms - offsetAfter);
  if (valid.length === 1)
    return valid[0];
  if (valid.length > 1)
    switch (disambiguation) {
      case "compatible":
      case "earlier":
        return valid[0];
      case "later":
        return valid[valid.length - 1];
      case "reject":
        throw new RangeError("Multiple possible absolute times found");
    }
  switch (disambiguation) {
    case "earlier":
      return Math.min(ms - offsetBefore, ms - offsetAfter);
    case "compatible":
    case "later":
      return Math.max(ms - offsetBefore, ms - offsetAfter);
    case "reject":
      throw new RangeError("No such absolute time found");
  }
}
function $9ab2a87bc84c0bfa$export$e67a095c620b86fe(dateTime, timeZone, disambiguation = "compatible") {
  return new Date($9ab2a87bc84c0bfa$export$5107c82f94518f5c(dateTime, timeZone, disambiguation));
}
function $9ab2a87bc84c0bfa$export$1b96692a1ba042ac(ms, timeZone) {
  let offset2 = $9ab2a87bc84c0bfa$export$59c99f3515d3493f(ms, timeZone);
  let date = new Date(ms + offset2);
  let year = date.getUTCFullYear();
  let month = date.getUTCMonth() + 1;
  let day = date.getUTCDate();
  let hour = date.getUTCHours();
  let minute = date.getUTCMinutes();
  let second = date.getUTCSeconds();
  let millisecond = date.getUTCMilliseconds();
  return new $418a5bbf7b2f3448$export$d3b7288e7994edea(year, month, day, timeZone, offset2, hour, minute, second, millisecond);
}
function $9ab2a87bc84c0bfa$export$e57ff100d91bd4b9(date, timeZone) {
  return $9ab2a87bc84c0bfa$export$1b96692a1ba042ac(date.getTime(), timeZone);
}
function $9ab2a87bc84c0bfa$export$d7f92bcd3596b086(date) {
  return $9ab2a87bc84c0bfa$export$e57ff100d91bd4b9(date, $571ccebef3ef72f1$export$aa8b41735afcabd2());
}
function $9ab2a87bc84c0bfa$export$93522d1a439f3617(dateTime) {
  return new $418a5bbf7b2f3448$export$99faa760c7908e4f(dateTime.calendar, dateTime.era, dateTime.year, dateTime.month, dateTime.day);
}
function $9ab2a87bc84c0bfa$export$6f4d78149f3f53ac(date) {
  return {
    era: date.era,
    year: date.year,
    month: date.month,
    day: date.day
  };
}
function $9ab2a87bc84c0bfa$export$4d0393e732857be5(date) {
  return {
    hour: date.hour,
    minute: date.minute,
    second: date.second,
    millisecond: date.millisecond
  };
}
function $9ab2a87bc84c0bfa$export$b21e0b124e224484(date, time) {
  let hour = 0, minute = 0, second = 0, millisecond = 0;
  if ("timeZone" in date)
    ({ hour, minute, second, millisecond } = date);
  else if ("hour" in date && !time)
    return date;
  if (time)
    ({ hour, minute, second, millisecond } = time);
  return new $418a5bbf7b2f3448$export$ca871e8dbb80966f(date.calendar, date.era, date.year, date.month, date.day, hour, minute, second, millisecond);
}
function $9ab2a87bc84c0bfa$export$d33f79e3ffc3dc83(dateTime) {
  return new $418a5bbf7b2f3448$export$680ea196effce5f(dateTime.hour, dateTime.minute, dateTime.second, dateTime.millisecond);
}
function $9ab2a87bc84c0bfa$export$b4a036af3fc0b032(date, calendar) {
  if (date.calendar.identifier === calendar.identifier)
    return date;
  let calendarDate = calendar.fromJulianDay(date.calendar.toJulianDay(date));
  let copy = date.copy();
  copy.calendar = calendar;
  copy.era = calendarDate.era;
  copy.year = calendarDate.year;
  copy.month = calendarDate.month;
  copy.day = calendarDate.day;
  return copy;
}
function $9ab2a87bc84c0bfa$export$84c95a83c799e074(date, timeZone, disambiguation) {
  if (date instanceof $418a5bbf7b2f3448$export$d3b7288e7994edea) {
    if (date.timeZone === timeZone)
      return date;
    return $9ab2a87bc84c0bfa$export$538b00033cc11c75(date, timeZone);
  }
  let ms = $9ab2a87bc84c0bfa$export$5107c82f94518f5c(date, timeZone, disambiguation);
  return $9ab2a87bc84c0bfa$export$1b96692a1ba042ac(ms, timeZone);
}
function $9ab2a87bc84c0bfa$export$83aac07b4c37b25(date) {
  let ms = $9ab2a87bc84c0bfa$export$bd4fb2bc8bb06fb(date) - date.offset;
  return new Date(ms);
}
function $9ab2a87bc84c0bfa$export$538b00033cc11c75(date, timeZone) {
  let ms = $9ab2a87bc84c0bfa$export$bd4fb2bc8bb06fb(date) - date.offset;
  return $9ab2a87bc84c0bfa$export$b4a036af3fc0b032($9ab2a87bc84c0bfa$export$1b96692a1ba042ac(ms, timeZone), date.calendar);
}
function $9ab2a87bc84c0bfa$export$d9b67bc93c097491(date) {
  return $9ab2a87bc84c0bfa$export$538b00033cc11c75(date, $571ccebef3ef72f1$export$aa8b41735afcabd2());
}
const $1e1f3157d0513e0f$var$ONE_HOUR = 36e5;
function $1e1f3157d0513e0f$export$e16d8520af44a096(date, duration) {
  let mutableDate = date.copy();
  let days = "hour" in date ? $1e1f3157d0513e0f$var$addTimeFields(date, duration) : 0;
  $1e1f3157d0513e0f$var$addYears(mutableDate, duration.years || 0);
  if (mutableDate.calendar.balanceYearMonth)
    mutableDate.calendar.balanceYearMonth(mutableDate, date);
  mutableDate.month += duration.months || 0;
  $1e1f3157d0513e0f$var$balanceYearMonth(mutableDate);
  $1e1f3157d0513e0f$var$constrainMonthDay(mutableDate);
  mutableDate.day += (duration.weeks || 0) * 7;
  mutableDate.day += duration.days || 0;
  mutableDate.day += days;
  $1e1f3157d0513e0f$var$balanceDay(mutableDate);
  if (mutableDate.calendar.balanceDate)
    mutableDate.calendar.balanceDate(mutableDate);
  return mutableDate;
}
function $1e1f3157d0513e0f$var$addYears(date, years) {
  if (date.calendar.getYearsToAdd)
    years = date.calendar.getYearsToAdd(date, years);
  date.year += years;
}
function $1e1f3157d0513e0f$var$balanceYearMonth(date) {
  while (date.month < 1) {
    $1e1f3157d0513e0f$var$addYears(date, -1);
    date.month += date.calendar.getMonthsInYear(date);
  }
  let monthsInYear = 0;
  while (date.month > (monthsInYear = date.calendar.getMonthsInYear(date))) {
    date.month -= monthsInYear;
    $1e1f3157d0513e0f$var$addYears(date, 1);
  }
}
function $1e1f3157d0513e0f$var$balanceDay(date) {
  while (date.day < 1) {
    date.month--;
    $1e1f3157d0513e0f$var$balanceYearMonth(date);
    date.day += date.calendar.getDaysInMonth(date);
  }
  while (date.day > date.calendar.getDaysInMonth(date)) {
    date.day -= date.calendar.getDaysInMonth(date);
    date.month++;
    $1e1f3157d0513e0f$var$balanceYearMonth(date);
  }
}
function $1e1f3157d0513e0f$var$constrainMonthDay(date) {
  date.month = Math.max(1, Math.min(date.calendar.getMonthsInYear(date), date.month));
  date.day = Math.max(1, Math.min(date.calendar.getDaysInMonth(date), date.day));
}
function $1e1f3157d0513e0f$export$c4e2ecac49351ef2(date) {
  if (date.calendar.constrainDate)
    date.calendar.constrainDate(date);
  date.year = Math.max(1, Math.min(date.calendar.getYearsInEra(date), date.year));
  $1e1f3157d0513e0f$var$constrainMonthDay(date);
}
function $1e1f3157d0513e0f$export$3e2544e88a25bff8(duration) {
  let inverseDuration = {};
  for (let key in duration)
    if (typeof duration[key] === "number")
      inverseDuration[key] = -duration[key];
  return inverseDuration;
}
function $1e1f3157d0513e0f$export$4e2d2ead65e5f7e3(date, duration) {
  return $1e1f3157d0513e0f$export$e16d8520af44a096(date, $1e1f3157d0513e0f$export$3e2544e88a25bff8(duration));
}
function $1e1f3157d0513e0f$export$adaa4cf7ef1b65be(date, fields) {
  let mutableDate = date.copy();
  if (fields.era != null)
    mutableDate.era = fields.era;
  if (fields.year != null)
    mutableDate.year = fields.year;
  if (fields.month != null)
    mutableDate.month = fields.month;
  if (fields.day != null)
    mutableDate.day = fields.day;
  $1e1f3157d0513e0f$export$c4e2ecac49351ef2(mutableDate);
  return mutableDate;
}
function $1e1f3157d0513e0f$export$e5d5e1c1822b6e56(value, fields) {
  let mutableValue = value.copy();
  if (fields.hour != null)
    mutableValue.hour = fields.hour;
  if (fields.minute != null)
    mutableValue.minute = fields.minute;
  if (fields.second != null)
    mutableValue.second = fields.second;
  if (fields.millisecond != null)
    mutableValue.millisecond = fields.millisecond;
  $1e1f3157d0513e0f$export$7555de1e070510cb(mutableValue);
  return mutableValue;
}
function $1e1f3157d0513e0f$var$balanceTime(time) {
  time.second += Math.floor(time.millisecond / 1e3);
  time.millisecond = $1e1f3157d0513e0f$var$nonNegativeMod(time.millisecond, 1e3);
  time.minute += Math.floor(time.second / 60);
  time.second = $1e1f3157d0513e0f$var$nonNegativeMod(time.second, 60);
  time.hour += Math.floor(time.minute / 60);
  time.minute = $1e1f3157d0513e0f$var$nonNegativeMod(time.minute, 60);
  let days = Math.floor(time.hour / 24);
  time.hour = $1e1f3157d0513e0f$var$nonNegativeMod(time.hour, 24);
  return days;
}
function $1e1f3157d0513e0f$export$7555de1e070510cb(time) {
  time.millisecond = Math.max(0, Math.min(time.millisecond, 1e3));
  time.second = Math.max(0, Math.min(time.second, 59));
  time.minute = Math.max(0, Math.min(time.minute, 59));
  time.hour = Math.max(0, Math.min(time.hour, 23));
}
function $1e1f3157d0513e0f$var$nonNegativeMod(a2, b2) {
  let result = a2 % b2;
  if (result < 0)
    result += b2;
  return result;
}
function $1e1f3157d0513e0f$var$addTimeFields(time, duration) {
  time.hour += duration.hours || 0;
  time.minute += duration.minutes || 0;
  time.second += duration.seconds || 0;
  time.millisecond += duration.milliseconds || 0;
  return $1e1f3157d0513e0f$var$balanceTime(time);
}
function $1e1f3157d0513e0f$export$7ed87b6bc2506470(time, duration) {
  let res = time.copy();
  $1e1f3157d0513e0f$var$addTimeFields(res, duration);
  return res;
}
function $1e1f3157d0513e0f$export$fe34d3a381cd7501(time, duration) {
  return $1e1f3157d0513e0f$export$7ed87b6bc2506470(time, $1e1f3157d0513e0f$export$3e2544e88a25bff8(duration));
}
function $1e1f3157d0513e0f$export$d52ced6badfb9a4c(value, field, amount, options) {
  let mutable = value.copy();
  switch (field) {
    case "era": {
      let eras = value.calendar.getEras();
      let eraIndex = eras.indexOf(value.era);
      if (eraIndex < 0)
        throw new Error("Invalid era: " + value.era);
      eraIndex = $1e1f3157d0513e0f$var$cycleValue(eraIndex, amount, 0, eras.length - 1, options === null || options === void 0 ? void 0 : options.round);
      mutable.era = eras[eraIndex];
      $1e1f3157d0513e0f$export$c4e2ecac49351ef2(mutable);
      break;
    }
    case "year":
      if (mutable.calendar.getYearsToAdd)
        amount = mutable.calendar.getYearsToAdd(mutable, amount);
      mutable.year = $1e1f3157d0513e0f$var$cycleValue(value.year, amount, -Infinity, 9999, options === null || options === void 0 ? void 0 : options.round);
      if (mutable.year === -Infinity)
        mutable.year = 1;
      if (mutable.calendar.balanceYearMonth)
        mutable.calendar.balanceYearMonth(mutable, value);
      break;
    case "month":
      mutable.month = $1e1f3157d0513e0f$var$cycleValue(value.month, amount, 1, value.calendar.getMonthsInYear(value), options === null || options === void 0 ? void 0 : options.round);
      break;
    case "day":
      mutable.day = $1e1f3157d0513e0f$var$cycleValue(value.day, amount, 1, value.calendar.getDaysInMonth(value), options === null || options === void 0 ? void 0 : options.round);
      break;
    default:
      throw new Error("Unsupported field " + field);
  }
  if (value.calendar.balanceDate)
    value.calendar.balanceDate(mutable);
  $1e1f3157d0513e0f$export$c4e2ecac49351ef2(mutable);
  return mutable;
}
function $1e1f3157d0513e0f$export$dd02b3e0007dfe28(value, field, amount, options) {
  let mutable = value.copy();
  switch (field) {
    case "hour": {
      let hours = value.hour;
      let min = 0;
      let max = 23;
      if ((options === null || options === void 0 ? void 0 : options.hourCycle) === 12) {
        let isPM = hours >= 12;
        min = isPM ? 12 : 0;
        max = isPM ? 23 : 11;
      }
      mutable.hour = $1e1f3157d0513e0f$var$cycleValue(hours, amount, min, max, options === null || options === void 0 ? void 0 : options.round);
      break;
    }
    case "minute":
      mutable.minute = $1e1f3157d0513e0f$var$cycleValue(value.minute, amount, 0, 59, options === null || options === void 0 ? void 0 : options.round);
      break;
    case "second":
      mutable.second = $1e1f3157d0513e0f$var$cycleValue(value.second, amount, 0, 59, options === null || options === void 0 ? void 0 : options.round);
      break;
    case "millisecond":
      mutable.millisecond = $1e1f3157d0513e0f$var$cycleValue(value.millisecond, amount, 0, 999, options === null || options === void 0 ? void 0 : options.round);
      break;
    default:
      throw new Error("Unsupported field " + field);
  }
  return mutable;
}
function $1e1f3157d0513e0f$var$cycleValue(value, amount, min, max, round2 = false) {
  if (round2) {
    value += Math.sign(amount);
    if (value < min)
      value = max;
    let div = Math.abs(amount);
    if (amount > 0)
      value = Math.ceil(value / div) * div;
    else
      value = Math.floor(value / div) * div;
    if (value > max)
      value = min;
  } else {
    value += amount;
    if (value < min)
      value = max - (min - value - 1);
    else if (value > max)
      value = min + (value - max - 1);
  }
  return value;
}
function $1e1f3157d0513e0f$export$96b1d28349274637(dateTime, duration) {
  let ms;
  if (duration.years != null && duration.years !== 0 || duration.months != null && duration.months !== 0 || duration.days != null && duration.days !== 0) {
    let res2 = $1e1f3157d0513e0f$export$e16d8520af44a096($9ab2a87bc84c0bfa$export$b21e0b124e224484(dateTime), {
      years: duration.years,
      months: duration.months,
      days: duration.days
    });
    ms = $9ab2a87bc84c0bfa$export$5107c82f94518f5c(res2, dateTime.timeZone);
  } else
    ms = $9ab2a87bc84c0bfa$export$bd4fb2bc8bb06fb(dateTime) - dateTime.offset;
  ms += duration.milliseconds || 0;
  ms += (duration.seconds || 0) * 1e3;
  ms += (duration.minutes || 0) * 6e4;
  ms += (duration.hours || 0) * 36e5;
  let res = $9ab2a87bc84c0bfa$export$1b96692a1ba042ac(ms, dateTime.timeZone);
  return $9ab2a87bc84c0bfa$export$b4a036af3fc0b032(res, dateTime.calendar);
}
function $1e1f3157d0513e0f$export$6814caac34ca03c7(dateTime, duration) {
  return $1e1f3157d0513e0f$export$96b1d28349274637(dateTime, $1e1f3157d0513e0f$export$3e2544e88a25bff8(duration));
}
function $1e1f3157d0513e0f$export$9a297d111fc86b79(dateTime, field, amount, options) {
  switch (field) {
    case "hour": {
      let min = 0;
      let max = 23;
      if ((options === null || options === void 0 ? void 0 : options.hourCycle) === 12) {
        let isPM = dateTime.hour >= 12;
        min = isPM ? 12 : 0;
        max = isPM ? 23 : 11;
      }
      let plainDateTime = $9ab2a87bc84c0bfa$export$b21e0b124e224484(dateTime);
      let minDate = $9ab2a87bc84c0bfa$export$b4a036af3fc0b032($1e1f3157d0513e0f$export$e5d5e1c1822b6e56(plainDateTime, {
        hour: min
      }), new $22a507fc519bfd45$export$80ee6245ec4f29ec());
      let minAbsolute = [
        $9ab2a87bc84c0bfa$export$5107c82f94518f5c(minDate, dateTime.timeZone, "earlier"),
        $9ab2a87bc84c0bfa$export$5107c82f94518f5c(minDate, dateTime.timeZone, "later")
      ].filter((ms) => $9ab2a87bc84c0bfa$export$1b96692a1ba042ac(ms, dateTime.timeZone).day === minDate.day)[0];
      let maxDate = $9ab2a87bc84c0bfa$export$b4a036af3fc0b032($1e1f3157d0513e0f$export$e5d5e1c1822b6e56(plainDateTime, {
        hour: max
      }), new $22a507fc519bfd45$export$80ee6245ec4f29ec());
      let maxAbsolute = [
        $9ab2a87bc84c0bfa$export$5107c82f94518f5c(maxDate, dateTime.timeZone, "earlier"),
        $9ab2a87bc84c0bfa$export$5107c82f94518f5c(maxDate, dateTime.timeZone, "later")
      ].filter((ms) => $9ab2a87bc84c0bfa$export$1b96692a1ba042ac(ms, dateTime.timeZone).day === maxDate.day).pop();
      let ms1 = $9ab2a87bc84c0bfa$export$bd4fb2bc8bb06fb(dateTime) - dateTime.offset;
      let hours = Math.floor(ms1 / $1e1f3157d0513e0f$var$ONE_HOUR);
      let remainder = ms1 % $1e1f3157d0513e0f$var$ONE_HOUR;
      ms1 = $1e1f3157d0513e0f$var$cycleValue(hours, amount, Math.floor(minAbsolute / $1e1f3157d0513e0f$var$ONE_HOUR), Math.floor(maxAbsolute / $1e1f3157d0513e0f$var$ONE_HOUR), options === null || options === void 0 ? void 0 : options.round) * $1e1f3157d0513e0f$var$ONE_HOUR + remainder;
      return $9ab2a87bc84c0bfa$export$b4a036af3fc0b032($9ab2a87bc84c0bfa$export$1b96692a1ba042ac(ms1, dateTime.timeZone), dateTime.calendar);
    }
    case "minute":
    case "second":
    case "millisecond":
      return $1e1f3157d0513e0f$export$dd02b3e0007dfe28(dateTime, field, amount, options);
    case "era":
    case "year":
    case "month":
    case "day": {
      let res = $1e1f3157d0513e0f$export$d52ced6badfb9a4c($9ab2a87bc84c0bfa$export$b21e0b124e224484(dateTime), field, amount, options);
      let ms = $9ab2a87bc84c0bfa$export$5107c82f94518f5c(res, dateTime.timeZone);
      return $9ab2a87bc84c0bfa$export$b4a036af3fc0b032($9ab2a87bc84c0bfa$export$1b96692a1ba042ac(ms, dateTime.timeZone), dateTime.calendar);
    }
    default:
      throw new Error("Unsupported field " + field);
  }
}
function $1e1f3157d0513e0f$export$31b5430eb18be4f8(dateTime, fields, disambiguation) {
  let plainDateTime = $9ab2a87bc84c0bfa$export$b21e0b124e224484(dateTime);
  let res = $1e1f3157d0513e0f$export$e5d5e1c1822b6e56($1e1f3157d0513e0f$export$adaa4cf7ef1b65be(plainDateTime, fields), fields);
  if (res.compare(plainDateTime) === 0)
    return dateTime;
  let ms = $9ab2a87bc84c0bfa$export$5107c82f94518f5c(res, dateTime.timeZone, disambiguation);
  return $9ab2a87bc84c0bfa$export$b4a036af3fc0b032($9ab2a87bc84c0bfa$export$1b96692a1ba042ac(ms, dateTime.timeZone), dateTime.calendar);
}
var $78b7d46219519df2$exports = {};
$parcel$export$q($78b7d46219519df2$exports, "parseTime", () => $78b7d46219519df2$export$c9698ec7f05a07e1);
$parcel$export$q($78b7d46219519df2$exports, "parseDate", () => $78b7d46219519df2$export$6b862160d295c8e);
$parcel$export$q($78b7d46219519df2$exports, "parseDateTime", () => $78b7d46219519df2$export$588937bcd60ade55);
$parcel$export$q($78b7d46219519df2$exports, "parseZonedDateTime", () => $78b7d46219519df2$export$fd7893f06e92a6a4);
$parcel$export$q($78b7d46219519df2$exports, "dateTimeToString", () => $78b7d46219519df2$export$4223de14708adc63);
$parcel$export$q($78b7d46219519df2$exports, "parseAbsolute", () => $78b7d46219519df2$export$5adfdab05168c219);
$parcel$export$q($78b7d46219519df2$exports, "parseAbsoluteToLocal", () => $78b7d46219519df2$export$8e384432362ed0f0);
$parcel$export$q($78b7d46219519df2$exports, "timeToString", () => $78b7d46219519df2$export$f59dee82248f5ad4);
$parcel$export$q($78b7d46219519df2$exports, "dateToString", () => $78b7d46219519df2$export$60dfd74aa96791bd);
$parcel$export$q($78b7d46219519df2$exports, "zonedDateTimeToString", () => $78b7d46219519df2$export$bf79f1ebf4b18792);
const $78b7d46219519df2$var$TIME_RE = /^(\d{2})(?::(\d{2}))?(?::(\d{2}))?(\.\d+)?$/;
const $78b7d46219519df2$var$DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
const $78b7d46219519df2$var$DATE_TIME_RE = /^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}))?(?::(\d{2}))?(?::(\d{2}))?(\.\d+)?$/;
const $78b7d46219519df2$var$ZONED_DATE_TIME_RE = /^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}))?(?::(\d{2}))?(?::(\d{2}))?(\.\d+)?(?:([+-]\d{2})(?::(\d{2}))?)?\[(.*?)\]$/;
const $78b7d46219519df2$var$ABSOLUTE_RE = /^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}))?(?::(\d{2}))?(?::(\d{2}))?(\.\d+)?(?:(?:([+-]\d{2})(?::(\d{2}))?)|Z)$/;
function $78b7d46219519df2$export$c9698ec7f05a07e1(value) {
  let m2 = value.match($78b7d46219519df2$var$TIME_RE);
  if (!m2)
    throw new Error("Invalid ISO 8601 time string: " + value);
  return new $418a5bbf7b2f3448$export$680ea196effce5f($78b7d46219519df2$var$parseNumber(m2[1], 0, 23), m2[2] ? $78b7d46219519df2$var$parseNumber(m2[2], 0, 59) : 0, m2[3] ? $78b7d46219519df2$var$parseNumber(m2[3], 0, 59) : 0, m2[4] ? $78b7d46219519df2$var$parseNumber(m2[4], 0, Infinity) * 1e3 : 0);
}
function $78b7d46219519df2$export$6b862160d295c8e(value) {
  let m2 = value.match($78b7d46219519df2$var$DATE_RE);
  if (!m2)
    throw new Error("Invalid ISO 8601 date string: " + value);
  let date = new $418a5bbf7b2f3448$export$99faa760c7908e4f($78b7d46219519df2$var$parseNumber(m2[1], 0, 9999), $78b7d46219519df2$var$parseNumber(m2[2], 1, 12), 1);
  date.day = $78b7d46219519df2$var$parseNumber(m2[3], 0, date.calendar.getDaysInMonth(date));
  return date;
}
function $78b7d46219519df2$export$588937bcd60ade55(value) {
  let m2 = value.match($78b7d46219519df2$var$DATE_TIME_RE);
  if (!m2)
    throw new Error("Invalid ISO 8601 date time string: " + value);
  let date = new $418a5bbf7b2f3448$export$ca871e8dbb80966f($78b7d46219519df2$var$parseNumber(m2[1], 1, 9999), $78b7d46219519df2$var$parseNumber(m2[2], 1, 12), 1, m2[4] ? $78b7d46219519df2$var$parseNumber(m2[4], 0, 23) : 0, m2[5] ? $78b7d46219519df2$var$parseNumber(m2[5], 0, 59) : 0, m2[6] ? $78b7d46219519df2$var$parseNumber(m2[6], 0, 59) : 0, m2[7] ? $78b7d46219519df2$var$parseNumber(m2[7], 0, Infinity) * 1e3 : 0);
  date.day = $78b7d46219519df2$var$parseNumber(m2[3], 0, date.calendar.getDaysInMonth(date));
  return date;
}
function $78b7d46219519df2$export$fd7893f06e92a6a4(value, disambiguation) {
  let m2 = value.match($78b7d46219519df2$var$ZONED_DATE_TIME_RE);
  if (!m2)
    throw new Error("Invalid ISO 8601 date time string: " + value);
  let date = new $418a5bbf7b2f3448$export$d3b7288e7994edea($78b7d46219519df2$var$parseNumber(m2[1], 1, 9999), $78b7d46219519df2$var$parseNumber(m2[2], 1, 12), 1, m2[10], 0, m2[4] ? $78b7d46219519df2$var$parseNumber(m2[4], 0, 23) : 0, m2[5] ? $78b7d46219519df2$var$parseNumber(m2[5], 0, 59) : 0, m2[6] ? $78b7d46219519df2$var$parseNumber(m2[6], 0, 59) : 0, m2[7] ? $78b7d46219519df2$var$parseNumber(m2[7], 0, Infinity) * 1e3 : 0);
  date.day = $78b7d46219519df2$var$parseNumber(m2[3], 0, date.calendar.getDaysInMonth(date));
  let plainDateTime = $9ab2a87bc84c0bfa$export$b21e0b124e224484(date);
  let ms;
  if (m2[8]) {
    var ref;
    date.offset = $78b7d46219519df2$var$parseNumber(m2[8], -23, 23) * 36e5 + $78b7d46219519df2$var$parseNumber((ref = m2[9]) !== null && ref !== void 0 ? ref : "0", 0, 59) * 6e4;
    ms = $9ab2a87bc84c0bfa$export$bd4fb2bc8bb06fb(date) - date.offset;
    let absolutes = $9ab2a87bc84c0bfa$export$136f38efe7caf549(plainDateTime, date.timeZone);
    if (!absolutes.includes(ms))
      throw new Error(`Offset ${$78b7d46219519df2$var$offsetToString(date.offset)} is invalid for ${$78b7d46219519df2$export$4223de14708adc63(date)} in ${date.timeZone}`);
  } else
    ms = $9ab2a87bc84c0bfa$export$5107c82f94518f5c($9ab2a87bc84c0bfa$export$b21e0b124e224484(plainDateTime), date.timeZone, disambiguation);
  return $9ab2a87bc84c0bfa$export$1b96692a1ba042ac(ms, date.timeZone);
}
function $78b7d46219519df2$export$5adfdab05168c219(value, timeZone) {
  let m2 = value.match($78b7d46219519df2$var$ABSOLUTE_RE);
  if (!m2)
    throw new Error("Invalid ISO 8601 date time string: " + value);
  let date = new $418a5bbf7b2f3448$export$d3b7288e7994edea($78b7d46219519df2$var$parseNumber(m2[1], 1, 9999), $78b7d46219519df2$var$parseNumber(m2[2], 1, 12), 1, timeZone, 0, m2[4] ? $78b7d46219519df2$var$parseNumber(m2[4], 0, 23) : 0, m2[5] ? $78b7d46219519df2$var$parseNumber(m2[5], 0, 59) : 0, m2[6] ? $78b7d46219519df2$var$parseNumber(m2[6], 0, 59) : 0, m2[7] ? $78b7d46219519df2$var$parseNumber(m2[7], 0, Infinity) * 1e3 : 0);
  date.day = $78b7d46219519df2$var$parseNumber(m2[3], 0, date.calendar.getDaysInMonth(date));
  var ref;
  if (m2[8])
    date.offset = $78b7d46219519df2$var$parseNumber(m2[8], -23, 23) * 36e5 + $78b7d46219519df2$var$parseNumber((ref = m2[9]) !== null && ref !== void 0 ? ref : "0", 0, 59) * 6e4;
  return $9ab2a87bc84c0bfa$export$538b00033cc11c75(date, timeZone);
}
function $78b7d46219519df2$export$8e384432362ed0f0(value) {
  return $78b7d46219519df2$export$5adfdab05168c219(value, $571ccebef3ef72f1$export$aa8b41735afcabd2());
}
function $78b7d46219519df2$var$parseNumber(value, min, max) {
  let val = Number(value);
  if (val < min || val > max)
    throw new RangeError(`Value out of range: ${min} <= ${val} <= ${max}`);
  return val;
}
function $78b7d46219519df2$export$f59dee82248f5ad4(time) {
  return `${String(time.hour).padStart(2, "0")}:${String(time.minute).padStart(2, "0")}:${String(time.second).padStart(2, "0")}${time.millisecond ? String(time.millisecond / 1e3).slice(1) : ""}`;
}
function $78b7d46219519df2$export$60dfd74aa96791bd(date) {
  let gregorianDate = $9ab2a87bc84c0bfa$export$b4a036af3fc0b032(date, new $22a507fc519bfd45$export$80ee6245ec4f29ec());
  return `${String(gregorianDate.year).padStart(4, "0")}-${String(gregorianDate.month).padStart(2, "0")}-${String(gregorianDate.day).padStart(2, "0")}`;
}
function $78b7d46219519df2$export$4223de14708adc63(date) {
  return `${$78b7d46219519df2$export$60dfd74aa96791bd(date)}T${$78b7d46219519df2$export$f59dee82248f5ad4(date)}`;
}
function $78b7d46219519df2$var$offsetToString(offset2) {
  let sign = Math.sign(offset2) < 0 ? "-" : "+";
  offset2 = Math.abs(offset2);
  let offsetHours = Math.floor(offset2 / 36e5);
  let offsetMinutes = offset2 % 36e5 / 6e4;
  return `${sign}${String(offsetHours).padStart(2, "0")}:${String(offsetMinutes).padStart(2, "0")}`;
}
function $78b7d46219519df2$export$bf79f1ebf4b18792(date) {
  return `${$78b7d46219519df2$export$4223de14708adc63(date)}${$78b7d46219519df2$var$offsetToString(date.offset)}[${date.timeZone}]`;
}
function $418a5bbf7b2f3448$var$shiftArgs(args) {
  let calendar = typeof args[0] === "object" ? args.shift() : new $22a507fc519bfd45$export$80ee6245ec4f29ec();
  let era;
  if (typeof args[0] === "string")
    era = args.shift();
  else {
    let eras = calendar.getEras();
    era = eras[eras.length - 1];
  }
  let year = args.shift();
  let month = args.shift();
  let day = args.shift();
  return [
    calendar,
    era,
    year,
    month,
    day
  ];
}
class $418a5bbf7b2f3448$export$99faa760c7908e4f {
  copy() {
    if (this.era)
      return new $418a5bbf7b2f3448$export$99faa760c7908e4f(this.calendar, this.era, this.year, this.month, this.day);
    else
      return new $418a5bbf7b2f3448$export$99faa760c7908e4f(this.calendar, this.year, this.month, this.day);
  }
  add(duration) {
    return $1e1f3157d0513e0f$export$e16d8520af44a096(this, duration);
  }
  subtract(duration) {
    return $1e1f3157d0513e0f$export$4e2d2ead65e5f7e3(this, duration);
  }
  set(fields) {
    return $1e1f3157d0513e0f$export$adaa4cf7ef1b65be(this, fields);
  }
  cycle(field, amount, options) {
    return $1e1f3157d0513e0f$export$d52ced6badfb9a4c(this, field, amount, options);
  }
  toDate(timeZone) {
    return $9ab2a87bc84c0bfa$export$e67a095c620b86fe(this, timeZone);
  }
  toString() {
    return $78b7d46219519df2$export$60dfd74aa96791bd(this);
  }
  compare(b2) {
    return $571ccebef3ef72f1$export$68781ddf31c0090f(this, b2);
  }
  constructor(...args) {
    _type.set(this, {
      writable: true,
      value: void 0
    });
    let [calendar, era, year, month, day] = $418a5bbf7b2f3448$var$shiftArgs(args);
    this.calendar = calendar;
    this.era = era;
    this.year = year;
    this.month = month;
    this.day = day;
    $1e1f3157d0513e0f$export$c4e2ecac49351ef2(this);
  }
}
var _type = /* @__PURE__ */ new WeakMap();
class $418a5bbf7b2f3448$export$680ea196effce5f {
  copy() {
    return new $418a5bbf7b2f3448$export$680ea196effce5f(this.hour, this.minute, this.second, this.millisecond);
  }
  add(duration) {
    return $1e1f3157d0513e0f$export$7ed87b6bc2506470(this, duration);
  }
  subtract(duration) {
    return $1e1f3157d0513e0f$export$fe34d3a381cd7501(this, duration);
  }
  set(fields) {
    return $1e1f3157d0513e0f$export$e5d5e1c1822b6e56(this, fields);
  }
  cycle(field, amount, options) {
    return $1e1f3157d0513e0f$export$dd02b3e0007dfe28(this, field, amount, options);
  }
  toString() {
    return $78b7d46219519df2$export$f59dee82248f5ad4(this);
  }
  compare(b2) {
    return $571ccebef3ef72f1$export$c19a80a9721b80f6(this, b2);
  }
  constructor(hour = 0, minute = 0, second = 0, millisecond = 0) {
    _type1.set(this, {
      writable: true,
      value: void 0
    });
    this.hour = hour;
    this.minute = minute;
    this.second = second;
    this.millisecond = millisecond;
    $1e1f3157d0513e0f$export$7555de1e070510cb(this);
  }
}
var _type1 = /* @__PURE__ */ new WeakMap();
class $418a5bbf7b2f3448$export$ca871e8dbb80966f {
  copy() {
    if (this.era)
      return new $418a5bbf7b2f3448$export$ca871e8dbb80966f(this.calendar, this.era, this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond);
    else
      return new $418a5bbf7b2f3448$export$ca871e8dbb80966f(this.calendar, this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond);
  }
  add(duration) {
    return $1e1f3157d0513e0f$export$e16d8520af44a096(this, duration);
  }
  subtract(duration) {
    return $1e1f3157d0513e0f$export$4e2d2ead65e5f7e3(this, duration);
  }
  set(fields) {
    return $1e1f3157d0513e0f$export$adaa4cf7ef1b65be($1e1f3157d0513e0f$export$e5d5e1c1822b6e56(this, fields), fields);
  }
  cycle(field, amount, options) {
    switch (field) {
      case "era":
      case "year":
      case "month":
      case "day":
        return $1e1f3157d0513e0f$export$d52ced6badfb9a4c(this, field, amount, options);
      default:
        return $1e1f3157d0513e0f$export$dd02b3e0007dfe28(this, field, amount, options);
    }
  }
  toDate(timeZone) {
    return $9ab2a87bc84c0bfa$export$e67a095c620b86fe(this, timeZone);
  }
  toString() {
    return $78b7d46219519df2$export$4223de14708adc63(this);
  }
  compare(b2) {
    let res = $571ccebef3ef72f1$export$68781ddf31c0090f(this, b2);
    if (res === 0)
      return $571ccebef3ef72f1$export$c19a80a9721b80f6(this, $9ab2a87bc84c0bfa$export$b21e0b124e224484(b2));
    return res;
  }
  constructor(...args) {
    _type2.set(this, {
      writable: true,
      value: void 0
    });
    let [calendar, era, year, month, day] = $418a5bbf7b2f3448$var$shiftArgs(args);
    this.calendar = calendar;
    this.era = era;
    this.year = year;
    this.month = month;
    this.day = day;
    this.hour = args.shift() || 0;
    this.minute = args.shift() || 0;
    this.second = args.shift() || 0;
    this.millisecond = args.shift() || 0;
    $1e1f3157d0513e0f$export$c4e2ecac49351ef2(this);
  }
}
var _type2 = /* @__PURE__ */ new WeakMap();
class $418a5bbf7b2f3448$export$d3b7288e7994edea {
  copy() {
    if (this.era)
      return new $418a5bbf7b2f3448$export$d3b7288e7994edea(this.calendar, this.era, this.year, this.month, this.day, this.timeZone, this.offset, this.hour, this.minute, this.second, this.millisecond);
    else
      return new $418a5bbf7b2f3448$export$d3b7288e7994edea(this.calendar, this.year, this.month, this.day, this.timeZone, this.offset, this.hour, this.minute, this.second, this.millisecond);
  }
  add(duration) {
    return $1e1f3157d0513e0f$export$96b1d28349274637(this, duration);
  }
  subtract(duration) {
    return $1e1f3157d0513e0f$export$6814caac34ca03c7(this, duration);
  }
  set(fields, disambiguation) {
    return $1e1f3157d0513e0f$export$31b5430eb18be4f8(this, fields, disambiguation);
  }
  cycle(field, amount, options) {
    return $1e1f3157d0513e0f$export$9a297d111fc86b79(this, field, amount, options);
  }
  toDate() {
    return $9ab2a87bc84c0bfa$export$83aac07b4c37b25(this);
  }
  toString() {
    return $78b7d46219519df2$export$bf79f1ebf4b18792(this);
  }
  toAbsoluteString() {
    return this.toDate().toISOString();
  }
  compare(b2) {
    return this.toDate().getTime() - $9ab2a87bc84c0bfa$export$84c95a83c799e074(b2, this.timeZone).toDate().getTime();
  }
  constructor(...args) {
    _type3.set(this, {
      writable: true,
      value: void 0
    });
    let [calendar, era, year, month, day] = $418a5bbf7b2f3448$var$shiftArgs(args);
    let timeZone = args.shift();
    let offset2 = args.shift();
    this.calendar = calendar;
    this.era = era;
    this.year = year;
    this.month = month;
    this.day = day;
    this.timeZone = timeZone;
    this.offset = offset2;
    this.hour = args.shift() || 0;
    this.minute = args.shift() || 0;
    this.second = args.shift() || 0;
    this.millisecond = args.shift() || 0;
    $1e1f3157d0513e0f$export$c4e2ecac49351ef2(this);
  }
}
var _type3 = /* @__PURE__ */ new WeakMap();
var $ea6cd4c800b471d1$exports = {};
$parcel$export$q($ea6cd4c800b471d1$exports, "DateFormatter", () => $ea6cd4c800b471d1$export$ad991b66133851cf);
let $ea6cd4c800b471d1$var$formatterCache = /* @__PURE__ */ new Map();
class $ea6cd4c800b471d1$export$ad991b66133851cf {
  format(value) {
    return this.formatter.format(value);
  }
  formatToParts(value) {
    return this.formatter.formatToParts(value);
  }
  formatRange(start, end) {
    if (typeof this.formatter.formatRange === "function")
      return this.formatter.formatRange(start, end);
    if (end < start)
      throw new RangeError("End date must be >= start date");
    return `${this.formatter.format(start)} \u2013 ${this.formatter.format(end)}`;
  }
  formatRangeToParts(start, end) {
    if (typeof this.formatter.formatRangeToParts === "function")
      return this.formatter.formatRangeToParts(start, end);
    if (end < start)
      throw new RangeError("End date must be >= start date");
    let startParts = this.formatter.formatToParts(start);
    let endParts = this.formatter.formatToParts(end);
    return [
      ...startParts.map((p2) => __spreadProps(__spreadValues({}, p2), {
        source: "startRange"
      })),
      {
        type: "literal",
        value: " \u2013 ",
        source: "shared"
      },
      ...endParts.map((p2) => __spreadProps(__spreadValues({}, p2), {
        source: "endRange"
      }))
    ];
  }
  resolvedOptions() {
    let resolvedOptions = this.formatter.resolvedOptions();
    if ($ea6cd4c800b471d1$var$hasBuggyResolvedHourCycle()) {
      if (!this.resolvedHourCycle)
        this.resolvedHourCycle = $ea6cd4c800b471d1$var$getResolvedHourCycle(resolvedOptions.locale, this.options);
      resolvedOptions.hourCycle = this.resolvedHourCycle;
      resolvedOptions.hour12 = this.resolvedHourCycle === "h11" || this.resolvedHourCycle === "h12";
    }
    return resolvedOptions;
  }
  constructor(locale, options = {}) {
    this.formatter = $ea6cd4c800b471d1$var$getCachedDateFormatter(locale, options);
    this.options = options;
  }
}
const $ea6cd4c800b471d1$var$hour12Preferences = {
  true: {
    ja: "h11"
  },
  false: {}
};
function $ea6cd4c800b471d1$var$getCachedDateFormatter(locale, options = {}) {
  if (typeof options.hour12 === "boolean" && $ea6cd4c800b471d1$var$hasBuggyHour12Behavior()) {
    options = __spreadValues({}, options);
    let pref = $ea6cd4c800b471d1$var$hour12Preferences[String(options.hour12)][locale.split("-")[0]];
    let defaultHourCycle = options.hour12 ? "h12" : "h23";
    options.hourCycle = pref !== null && pref !== void 0 ? pref : defaultHourCycle;
    delete options.hour12;
  }
  let cacheKey = locale + (options ? Object.entries(options).sort((a2, b2) => a2[0] < b2[0] ? -1 : 1).join() : "");
  if ($ea6cd4c800b471d1$var$formatterCache.has(cacheKey))
    return $ea6cd4c800b471d1$var$formatterCache.get(cacheKey);
  let numberFormatter = new Intl.DateTimeFormat(locale, options);
  $ea6cd4c800b471d1$var$formatterCache.set(cacheKey, numberFormatter);
  return numberFormatter;
}
let $ea6cd4c800b471d1$var$_hasBuggyHour12Behavior = null;
function $ea6cd4c800b471d1$var$hasBuggyHour12Behavior() {
  if ($ea6cd4c800b471d1$var$_hasBuggyHour12Behavior == null)
    $ea6cd4c800b471d1$var$_hasBuggyHour12Behavior = new Intl.DateTimeFormat("en-US", {
      hour: "numeric",
      hour12: false
    }).format(new Date(2020, 2, 3, 0)) === "24";
  return $ea6cd4c800b471d1$var$_hasBuggyHour12Behavior;
}
let $ea6cd4c800b471d1$var$_hasBuggyResolvedHourCycle = null;
function $ea6cd4c800b471d1$var$hasBuggyResolvedHourCycle() {
  if ($ea6cd4c800b471d1$var$_hasBuggyResolvedHourCycle == null)
    $ea6cd4c800b471d1$var$_hasBuggyResolvedHourCycle = new Intl.DateTimeFormat("fr", {
      hour: "numeric",
      hour12: false
    }).resolvedOptions().hourCycle === "h12";
  return $ea6cd4c800b471d1$var$_hasBuggyResolvedHourCycle;
}
function $ea6cd4c800b471d1$var$getResolvedHourCycle(locale, options) {
  if (!options.timeStyle && !options.hour)
    return void 0;
  locale = locale.replace(/(-u-)?-nu-[a-zA-Z0-9]+/, "");
  locale += (locale.includes("-u-") ? "" : "-u") + "-nu-latn";
  let formatter = $ea6cd4c800b471d1$var$getCachedDateFormatter(locale, __spreadProps(__spreadValues({}, options), {
    timeZone: void 0
  }));
  let min = parseInt(formatter.formatToParts(new Date(2020, 2, 3, 0)).find((p2) => p2.type === "hour").value, 10);
  let max = parseInt(formatter.formatToParts(new Date(2020, 2, 3, 23)).find((p2) => p2.type === "hour").value, 10);
  if (min === 0 && max === 23)
    return "h23";
  if (min === 24 && max === 23)
    return "h24";
  if (min === 0 && max === 11)
    return "h11";
  if (min === 12 && max === 11)
    return "h12";
  throw new Error("Unexpected hour cycle result");
}
let $81812865b3bb9d70$var$formatterCache = /* @__PURE__ */ new Map();
let $81812865b3bb9d70$var$supportsSignDisplay = false;
try {
  $81812865b3bb9d70$var$supportsSignDisplay = new Intl.NumberFormat("de-DE", {
    signDisplay: "exceptZero"
  }).resolvedOptions().signDisplay === "exceptZero";
} catch (e2) {
}
let $81812865b3bb9d70$var$supportsUnit = false;
try {
  $81812865b3bb9d70$var$supportsUnit = new Intl.NumberFormat("de-DE", {
    style: "unit",
    unit: "degree"
  }).resolvedOptions().style === "unit";
} catch (e1) {
}
const $81812865b3bb9d70$var$UNITS = {
  degree: {
    narrow: {
      default: "\xB0",
      "ja-JP": " \u5EA6",
      "zh-TW": "\u5EA6",
      "sl-SI": " \xB0"
    }
  }
};
class $81812865b3bb9d70$export$cc77c4ff7e8673c5 {
  format(value) {
    let res = "";
    if (!$81812865b3bb9d70$var$supportsSignDisplay && this.options.signDisplay != null)
      res = $81812865b3bb9d70$export$711b50b3c525e0f2(this.numberFormatter, this.options.signDisplay, value);
    else
      res = this.numberFormatter.format(value);
    if (this.options.style === "unit" && !$81812865b3bb9d70$var$supportsUnit) {
      var ref;
      let { unit, unitDisplay = "short", locale } = this.resolvedOptions();
      let values = (ref = $81812865b3bb9d70$var$UNITS[unit]) === null || ref === void 0 ? void 0 : ref[unitDisplay];
      res += values[locale] || values.default;
    }
    return res;
  }
  formatToParts(value) {
    return this.numberFormatter.formatToParts(value);
  }
  resolvedOptions() {
    let options = this.numberFormatter.resolvedOptions();
    if (!$81812865b3bb9d70$var$supportsSignDisplay && this.options.signDisplay != null)
      options = __spreadProps(__spreadValues({}, options), {
        signDisplay: this.options.signDisplay
      });
    if (!$81812865b3bb9d70$var$supportsUnit && this.options.style === "unit")
      options = __spreadProps(__spreadValues({}, options), {
        style: "unit",
        unit: this.options.unit,
        unitDisplay: this.options.unitDisplay
      });
    return options;
  }
  constructor(locale, options = {}) {
    this.numberFormatter = $81812865b3bb9d70$var$getCachedNumberFormatter(locale, options);
    this.options = options;
  }
}
function $81812865b3bb9d70$var$getCachedNumberFormatter(locale, options = {}) {
  let { numberingSystem } = options;
  if (numberingSystem && locale.indexOf("-u-nu-") === -1)
    locale = `${locale}-u-nu-${numberingSystem}`;
  if (options.style === "unit" && !$81812865b3bb9d70$var$supportsUnit) {
    var ref;
    let { unit, unitDisplay = "short" } = options;
    if (!unit)
      throw new Error('unit option must be provided with style: "unit"');
    if (!((ref = $81812865b3bb9d70$var$UNITS[unit]) === null || ref === void 0 ? void 0 : ref[unitDisplay]))
      throw new Error(`Unsupported unit ${unit} with unitDisplay = ${unitDisplay}`);
    options = __spreadProps(__spreadValues({}, options), {
      style: "decimal"
    });
  }
  let cacheKey = locale + (options ? Object.entries(options).sort((a2, b2) => a2[0] < b2[0] ? -1 : 1).join() : "");
  if ($81812865b3bb9d70$var$formatterCache.has(cacheKey))
    return $81812865b3bb9d70$var$formatterCache.get(cacheKey);
  let numberFormatter = new Intl.NumberFormat(locale, options);
  $81812865b3bb9d70$var$formatterCache.set(cacheKey, numberFormatter);
  return numberFormatter;
}
function $81812865b3bb9d70$export$711b50b3c525e0f2(numberFormat, signDisplay, num) {
  if (signDisplay === "auto")
    return numberFormat.format(num);
  else if (signDisplay === "never")
    return numberFormat.format(Math.abs(num));
  else {
    let needsPositiveSign = false;
    if (signDisplay === "always")
      needsPositiveSign = num > 0 || Object.is(num, 0);
    else if (signDisplay === "exceptZero") {
      if (Object.is(num, -0) || Object.is(num, 0))
        num = Math.abs(num);
      else
        needsPositiveSign = num > 0;
    }
    if (needsPositiveSign) {
      let negative = numberFormat.format(-num);
      let noSign = numberFormat.format(num);
      let minus2 = negative.replace(noSign, "").replace(/\u200e|\u061C/, "");
      if ([
        ...minus2
      ].length !== 1)
        console.warn("@react-aria/i18n polyfill for NumberFormat signDisplay: Unsupported case");
      let positive = negative.replace(noSign, "!!!").replace(minus2, "+").replace("!!!", noSign);
      return positive;
    } else
      return numberFormat.format(num);
  }
}
const $ad41ad2a9f71fc3e$var$CURRENCY_SIGN_REGEX = new RegExp("^.*\\(.*\\).*$");
const $ad41ad2a9f71fc3e$var$NUMBERING_SYSTEMS = [
  "latn",
  "arab",
  "hanidec"
];
class $ad41ad2a9f71fc3e$export$cd11ab140839f11d {
  parse(value) {
    return $ad41ad2a9f71fc3e$var$getNumberParserImpl(this.locale, this.options, value).parse(value);
  }
  isValidPartialNumber(value, minValue, maxValue) {
    return $ad41ad2a9f71fc3e$var$getNumberParserImpl(this.locale, this.options, value).isValidPartialNumber(value, minValue, maxValue);
  }
  getNumberingSystem(value) {
    return $ad41ad2a9f71fc3e$var$getNumberParserImpl(this.locale, this.options, value).options.numberingSystem;
  }
  constructor(locale, options = {}) {
    this.locale = locale;
    this.options = options;
  }
}
const $ad41ad2a9f71fc3e$var$numberParserCache = /* @__PURE__ */ new Map();
function $ad41ad2a9f71fc3e$var$getNumberParserImpl(locale, options, value) {
  let defaultParser = $ad41ad2a9f71fc3e$var$getCachedNumberParser(locale, options);
  if (!locale.includes("-nu-") && !defaultParser.isValidPartialNumber(value)) {
    for (let numberingSystem of $ad41ad2a9f71fc3e$var$NUMBERING_SYSTEMS)
      if (numberingSystem !== defaultParser.options.numberingSystem) {
        let parser = $ad41ad2a9f71fc3e$var$getCachedNumberParser(locale + (locale.includes("-u-") ? "-nu-" : "-u-nu-") + numberingSystem, options);
        if (parser.isValidPartialNumber(value))
          return parser;
      }
  }
  return defaultParser;
}
function $ad41ad2a9f71fc3e$var$getCachedNumberParser(locale, options) {
  let cacheKey = locale + (options ? Object.entries(options).sort((a2, b2) => a2[0] < b2[0] ? -1 : 1).join() : "");
  let parser = $ad41ad2a9f71fc3e$var$numberParserCache.get(cacheKey);
  if (!parser) {
    parser = new $ad41ad2a9f71fc3e$var$NumberParserImpl(locale, options);
    $ad41ad2a9f71fc3e$var$numberParserCache.set(cacheKey, parser);
  }
  return parser;
}
class $ad41ad2a9f71fc3e$var$NumberParserImpl {
  parse(value) {
    let fullySanitizedValue = this.sanitize(value);
    fullySanitizedValue = $ad41ad2a9f71fc3e$var$replaceAll(fullySanitizedValue, this.symbols.group, "").replace(this.symbols.decimal, ".").replace(this.symbols.minusSign, "-").replace(this.symbols.numeral, this.symbols.index);
    let newValue = fullySanitizedValue ? +fullySanitizedValue : NaN;
    if (isNaN(newValue))
      return NaN;
    if (this.options.currencySign === "accounting" && $ad41ad2a9f71fc3e$var$CURRENCY_SIGN_REGEX.test(value))
      newValue = -1 * newValue;
    if (this.options.style === "percent") {
      newValue /= 100;
      var _maximumFractionDigits;
      newValue = +newValue.toFixed(((_maximumFractionDigits = this.options.maximumFractionDigits) !== null && _maximumFractionDigits !== void 0 ? _maximumFractionDigits : 0) + 2);
    }
    return newValue;
  }
  sanitize(value) {
    value = value.replace(this.symbols.literals, "");
    value = value.replace("-", this.symbols.minusSign);
    if (this.options.numberingSystem === "arab") {
      value = value.replace(",", this.symbols.decimal);
      value = value.replace(String.fromCharCode(1548), this.symbols.decimal);
      value = $ad41ad2a9f71fc3e$var$replaceAll(value, ".", this.symbols.group);
    }
    if (this.options.locale === "fr-FR")
      value = $ad41ad2a9f71fc3e$var$replaceAll(value, ".", String.fromCharCode(8239));
    return value;
  }
  isValidPartialNumber(value, minValue = -Infinity, maxValue = Infinity) {
    value = this.sanitize(value);
    if (value.startsWith(this.symbols.minusSign) && minValue < 0)
      value = value.slice(this.symbols.minusSign.length);
    else if (this.symbols.plusSign && value.startsWith(this.symbols.plusSign) && maxValue > 0)
      value = value.slice(this.symbols.plusSign.length);
    if (value.startsWith(this.symbols.group))
      return false;
    value = $ad41ad2a9f71fc3e$var$replaceAll(value, this.symbols.group, "").replace(this.symbols.numeral, "").replace(this.symbols.decimal, "");
    return value.length === 0;
  }
  constructor(locale, options = {}) {
    this.formatter = new Intl.NumberFormat(locale, options);
    this.options = this.formatter.resolvedOptions();
    this.symbols = $ad41ad2a9f71fc3e$var$getSymbols(this.formatter, this.options, options);
  }
}
const $ad41ad2a9f71fc3e$var$nonLiteralParts = /* @__PURE__ */ new Set([
  "decimal",
  "fraction",
  "integer",
  "minusSign",
  "plusSign",
  "group"
]);
function $ad41ad2a9f71fc3e$var$getSymbols(formatter, intlOptions, originalOptions) {
  var ref, ref1, ref2, ref3;
  let allParts = formatter.formatToParts(-10000.111);
  let posAllParts = formatter.formatToParts(10000.111);
  let singularParts = formatter.formatToParts(1);
  var ref4;
  let minusSign = (ref4 = (ref = allParts.find((p2) => p2.type === "minusSign")) === null || ref === void 0 ? void 0 : ref.value) !== null && ref4 !== void 0 ? ref4 : "-";
  let plusSign = (ref1 = posAllParts.find((p2) => p2.type === "plusSign")) === null || ref1 === void 0 ? void 0 : ref1.value;
  if (!plusSign && ((originalOptions === null || originalOptions === void 0 ? void 0 : originalOptions.signDisplay) === "exceptZero" || (originalOptions === null || originalOptions === void 0 ? void 0 : originalOptions.signDisplay) === "always"))
    plusSign = "+";
  let decimal = (ref2 = allParts.find((p2) => p2.type === "decimal")) === null || ref2 === void 0 ? void 0 : ref2.value;
  let group = (ref3 = allParts.find((p2) => p2.type === "group")) === null || ref3 === void 0 ? void 0 : ref3.value;
  let pluralLiterals = allParts.filter((p2) => !$ad41ad2a9f71fc3e$var$nonLiteralParts.has(p2.type)).map((p2) => $ad41ad2a9f71fc3e$var$escapeRegex(p2.value));
  let singularLiterals = singularParts.filter((p2) => !$ad41ad2a9f71fc3e$var$nonLiteralParts.has(p2.type)).map((p2) => $ad41ad2a9f71fc3e$var$escapeRegex(p2.value));
  let sortedLiterals = [
    .../* @__PURE__ */ new Set([
      ...singularLiterals,
      ...pluralLiterals
    ])
  ].sort((a2, b2) => b2.length - a2.length);
  let literals = new RegExp(`${sortedLiterals.join("|")}|[\\p{White_Space}]`, "gu");
  let numerals = [
    ...new Intl.NumberFormat(intlOptions.locale, {
      useGrouping: false
    }).format(9876543210)
  ].reverse();
  let indexes = new Map(numerals.map((d2, i2) => [
    d2,
    i2
  ]));
  let numeral = new RegExp(`[${numerals.join("")}]`, "g");
  let index2 = (d2) => String(indexes.get(d2));
  return {
    minusSign,
    plusSign,
    decimal,
    group,
    literals,
    numeral,
    index: index2
  };
}
function $ad41ad2a9f71fc3e$var$replaceAll(str, find, replace) {
  if (str.replaceAll)
    return str.replaceAll(find, replace);
  return str.split(find).join(replace);
}
function $ad41ad2a9f71fc3e$var$escapeRegex(string) {
  return string.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
}
function $parcel$export$p(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $18f2051aff69b9bf$exports = {};
$parcel$export$p($18f2051aff69b9bf$exports, "I18nProvider", () => $18f2051aff69b9bf$export$a54013f0d02a8f82);
$parcel$export$p($18f2051aff69b9bf$exports, "useLocale", () => $18f2051aff69b9bf$export$43bb16f9c6d9e3f7);
const $148a7a147e38ea7f$var$RTL_SCRIPTS = /* @__PURE__ */ new Set([
  "Arab",
  "Syrc",
  "Samr",
  "Mand",
  "Thaa",
  "Mend",
  "Nkoo",
  "Adlm",
  "Rohg",
  "Hebr"
]);
const $148a7a147e38ea7f$var$RTL_LANGS = /* @__PURE__ */ new Set([
  "ae",
  "ar",
  "arc",
  "bcc",
  "bqi",
  "ckb",
  "dv",
  "fa",
  "glk",
  "he",
  "ku",
  "mzn",
  "nqo",
  "pnb",
  "ps",
  "sd",
  "ug",
  "ur",
  "yi"
]);
function $148a7a147e38ea7f$export$702d680b21cbd764(locale) {
  if (Intl.Locale) {
    let script = new Intl.Locale(locale).maximize().script;
    return $148a7a147e38ea7f$var$RTL_SCRIPTS.has(script);
  }
  let lang = locale.split("-")[0];
  return $148a7a147e38ea7f$var$RTL_LANGS.has(lang);
}
function $1e5a04cdaf7d1af8$export$f09106e7c6677ec5() {
  let locale = typeof navigator !== "undefined" && (navigator.language || navigator.userLanguage) || "en-US";
  return {
    locale,
    direction: $148a7a147e38ea7f$export$702d680b21cbd764(locale) ? "rtl" : "ltr"
  };
}
let $1e5a04cdaf7d1af8$var$currentLocale = $1e5a04cdaf7d1af8$export$f09106e7c6677ec5();
let $1e5a04cdaf7d1af8$var$listeners = /* @__PURE__ */ new Set();
function $1e5a04cdaf7d1af8$var$updateLocale() {
  $1e5a04cdaf7d1af8$var$currentLocale = $1e5a04cdaf7d1af8$export$f09106e7c6677ec5();
  for (let listener of $1e5a04cdaf7d1af8$var$listeners)
    listener($1e5a04cdaf7d1af8$var$currentLocale);
}
function $1e5a04cdaf7d1af8$export$188ec29ebc2bdc3a() {
  let isSSR2 = $9d939cbc98267846$export$535bd6ca7f90a273();
  let [defaultLocale, setDefaultLocale] = useState($1e5a04cdaf7d1af8$var$currentLocale);
  useEffect(() => {
    if ($1e5a04cdaf7d1af8$var$listeners.size === 0)
      window.addEventListener("languagechange", $1e5a04cdaf7d1af8$var$updateLocale);
    $1e5a04cdaf7d1af8$var$listeners.add(setDefaultLocale);
    return () => {
      $1e5a04cdaf7d1af8$var$listeners.delete(setDefaultLocale);
      if ($1e5a04cdaf7d1af8$var$listeners.size === 0)
        window.removeEventListener("languagechange", $1e5a04cdaf7d1af8$var$updateLocale);
    };
  }, []);
  if (isSSR2)
    return {
      locale: "en-US",
      direction: "ltr"
    };
  return defaultLocale;
}
const $18f2051aff69b9bf$var$I18nContext = /* @__PURE__ */ React__default.createContext(null);
function $18f2051aff69b9bf$export$a54013f0d02a8f82(props2) {
  let { locale, children } = props2;
  let defaultLocale = $1e5a04cdaf7d1af8$export$188ec29ebc2bdc3a();
  let value = locale ? {
    locale,
    direction: $148a7a147e38ea7f$export$702d680b21cbd764(locale) ? "rtl" : "ltr"
  } : defaultLocale;
  return /* @__PURE__ */ React__default.createElement($18f2051aff69b9bf$var$I18nContext.Provider, {
    value
  }, children);
}
function $18f2051aff69b9bf$export$43bb16f9c6d9e3f7() {
  let defaultLocale = $1e5a04cdaf7d1af8$export$188ec29ebc2bdc3a();
  let context = useContext($18f2051aff69b9bf$var$I18nContext);
  return context || defaultLocale;
}
var $321bc95feeb923dd$exports = {};
$parcel$export$p($321bc95feeb923dd$exports, "useMessageFormatter", () => $321bc95feeb923dd$export$ec23bf898b1eed85);
const $321bc95feeb923dd$var$cache = /* @__PURE__ */ new WeakMap();
function $321bc95feeb923dd$var$getCachedDictionary(strings) {
  let dictionary = $321bc95feeb923dd$var$cache.get(strings);
  if (!dictionary) {
    dictionary = new $70eee6030fd7c1a1$export$64839e615120df17(strings);
    $321bc95feeb923dd$var$cache.set(strings, dictionary);
  }
  return dictionary;
}
function $321bc95feeb923dd$export$ec23bf898b1eed85(strings) {
  let { locale } = $18f2051aff69b9bf$export$43bb16f9c6d9e3f7();
  let dictionary = useMemo(() => $321bc95feeb923dd$var$getCachedDictionary(strings), [
    strings
  ]);
  let formatter = useMemo(() => new $a96338b8d4eb3cb0$export$526ebc05ff964723(locale, dictionary), [
    locale,
    dictionary
  ]);
  return useCallback((key, variables) => formatter.format(key, variables), [
    formatter
  ]);
}
var $896ba0a80a8f4d36$exports = {};
$parcel$export$p($896ba0a80a8f4d36$exports, "useDateFormatter", () => $896ba0a80a8f4d36$export$85fd5fdf27bacc79);
function $896ba0a80a8f4d36$export$85fd5fdf27bacc79(options) {
  let lastOptions = useRef(null);
  if (options && lastOptions.current && $896ba0a80a8f4d36$var$isEqual(options, lastOptions.current))
    options = lastOptions.current;
  lastOptions.current = options;
  let { locale } = $18f2051aff69b9bf$export$43bb16f9c6d9e3f7();
  return useMemo(() => new $ea6cd4c800b471d1$export$ad991b66133851cf(locale, options), [
    locale,
    options
  ]);
}
function $896ba0a80a8f4d36$var$isEqual(a2, b2) {
  if (a2 === b2)
    return true;
  let aKeys = Object.keys(a2);
  let bKeys = Object.keys(b2);
  if (aKeys.length !== bKeys.length)
    return false;
  for (let key of aKeys) {
    if (b2[key] !== a2[key])
      return false;
  }
  return true;
}
var $a916eb452884faea$exports = {};
$parcel$export$p($a916eb452884faea$exports, "useNumberFormatter", () => $a916eb452884faea$export$b7a616150fdb9f44);
function $a916eb452884faea$export$b7a616150fdb9f44(options = {}) {
  let { locale } = $18f2051aff69b9bf$export$43bb16f9c6d9e3f7();
  return useMemo(() => new $81812865b3bb9d70$export$cc77c4ff7e8673c5(locale, options), [
    locale,
    options
  ]);
}
var $325a3faab7a68acd$exports = {};
$parcel$export$p($325a3faab7a68acd$exports, "useCollator", () => $325a3faab7a68acd$export$a16aca283550c30d);
let $325a3faab7a68acd$var$cache = /* @__PURE__ */ new Map();
function $325a3faab7a68acd$export$a16aca283550c30d(options) {
  let { locale } = $18f2051aff69b9bf$export$43bb16f9c6d9e3f7();
  let cacheKey = locale + (options ? Object.entries(options).sort((a2, b2) => a2[0] < b2[0] ? -1 : 1).join() : "");
  if ($325a3faab7a68acd$var$cache.has(cacheKey))
    return $325a3faab7a68acd$var$cache.get(cacheKey);
  let formatter = new Intl.Collator(locale, options);
  $325a3faab7a68acd$var$cache.set(cacheKey, formatter);
  return formatter;
}
var $bb77f239b46e8c72$exports = {};
$parcel$export$p($bb77f239b46e8c72$exports, "useFilter", () => $bb77f239b46e8c72$export$3274cf84b703fff);
function $bb77f239b46e8c72$export$3274cf84b703fff(options) {
  let collator = $325a3faab7a68acd$export$a16aca283550c30d(__spreadValues({
    usage: "search"
  }, options));
  return {
    startsWith(string, substring) {
      if (substring.length === 0)
        return true;
      string = string.normalize("NFC");
      substring = substring.normalize("NFC");
      return collator.compare(string.slice(0, substring.length), substring) === 0;
    },
    endsWith(string, substring) {
      if (substring.length === 0)
        return true;
      string = string.normalize("NFC");
      substring = substring.normalize("NFC");
      return collator.compare(string.slice(-substring.length), substring) === 0;
    },
    contains(string, substring) {
      if (substring.length === 0)
        return true;
      string = string.normalize("NFC");
      substring = substring.normalize("NFC");
      let scan = 0;
      let sliceLen = substring.length;
      for (; scan + sliceLen <= string.length; scan++) {
        let slice2 = string.slice(scan, scan + sliceLen);
        if (collator.compare(substring, slice2) === 0)
          return true;
      }
      return false;
    }
  };
}
var style = { exports: {} };
var interopRequireDefault = { exports: {} };
(function(module2) {
  function _interopRequireDefault2(obj) {
    return obj && obj.__esModule ? obj : {
      "default": obj
    };
  }
  module2.exports = _interopRequireDefault2, module2.exports.__esModule = true, module2.exports["default"] = module2.exports;
})(interopRequireDefault);
var camelizeStyle = { exports: {} };
var camelize = { exports: {} };
(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = camelize2;
  var rHyphen = /-(.)/g;
  function camelize2(string) {
    return string.replace(rHyphen, function(_2, chr) {
      return chr.toUpperCase();
    });
  }
  module2.exports = exports2["default"];
})(camelize, camelize.exports);
(function(module2, exports2) {
  var _interopRequireDefault2 = interopRequireDefault.exports;
  exports2.__esModule = true;
  exports2.default = camelizeStyleName;
  var _camelize = _interopRequireDefault2(camelize.exports);
  var msPattern = /^-ms-/;
  function camelizeStyleName(string) {
    return (0, _camelize.default)(string.replace(msPattern, "ms-"));
  }
  module2.exports = exports2["default"];
})(camelizeStyle, camelizeStyle.exports);
var hyphenateStyle = { exports: {} };
var hyphenate = { exports: {} };
(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = hyphenate2;
  var rUpper = /([A-Z])/g;
  function hyphenate2(string) {
    return string.replace(rUpper, "-$1").toLowerCase();
  }
  module2.exports = exports2["default"];
})(hyphenate, hyphenate.exports);
(function(module2, exports2) {
  var _interopRequireDefault2 = interopRequireDefault.exports;
  exports2.__esModule = true;
  exports2.default = hyphenateStyleName;
  var _hyphenate = _interopRequireDefault2(hyphenate.exports);
  var msPattern = /^ms-/;
  function hyphenateStyleName(string) {
    return (0, _hyphenate.default)(string).replace(msPattern, "-ms-");
  }
  module2.exports = exports2["default"];
})(hyphenateStyle, hyphenateStyle.exports);
var getComputedStyle$1 = { exports: {} };
(function(module2, exports2) {
  var _interopRequireDefault2 = interopRequireDefault.exports;
  exports2.__esModule = true;
  exports2.default = _getComputedStyle;
  var _camelizeStyle = _interopRequireDefault2(camelizeStyle.exports);
  var rposition = /^(top|right|bottom|left)$/;
  var rnumnonpx = /^([+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|))(?!px)[a-z%]+$/i;
  function _getComputedStyle(node) {
    if (!node)
      throw new TypeError("No Element passed to `getComputedStyle()`");
    var doc = node.ownerDocument;
    return "defaultView" in doc ? doc.defaultView.opener ? node.ownerDocument.defaultView.getComputedStyle(node, null) : window.getComputedStyle(node, null) : {
      getPropertyValue: function getPropertyValue(prop) {
        var style2 = node.style;
        prop = (0, _camelizeStyle.default)(prop);
        if (prop == "float")
          prop = "styleFloat";
        var current = node.currentStyle[prop] || null;
        if (current == null && style2 && style2[prop])
          current = style2[prop];
        if (rnumnonpx.test(current) && !rposition.test(prop)) {
          var left = style2.left;
          var runStyle = node.runtimeStyle;
          var rsLeft = runStyle && runStyle.left;
          if (rsLeft)
            runStyle.left = node.currentStyle.left;
          style2.left = prop === "fontSize" ? "1em" : current;
          current = style2.pixelLeft + "px";
          style2.left = left;
          if (rsLeft)
            runStyle.left = rsLeft;
        }
        return current;
      }
    };
  }
  module2.exports = exports2["default"];
})(getComputedStyle$1, getComputedStyle$1.exports);
var removeStyle = { exports: {} };
(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = removeStyle2;
  function removeStyle2(node, key) {
    return "removeProperty" in node.style ? node.style.removeProperty(key) : node.style.removeAttribute(key);
  }
  module2.exports = exports2["default"];
})(removeStyle, removeStyle.exports);
var properties = {};
var inDOM = { exports: {} };
(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = void 0;
  var _default2 = !!(typeof window !== "undefined" && window.document && window.document.createElement);
  exports2.default = _default2;
  module2.exports = exports2["default"];
})(inDOM, inDOM.exports);
var _interopRequireDefault = interopRequireDefault.exports;
properties.__esModule = true;
properties.default = properties.animationEnd = properties.animationDelay = properties.animationTiming = properties.animationDuration = properties.animationName = properties.transitionEnd = properties.transitionDuration = properties.transitionDelay = properties.transitionTiming = properties.transitionProperty = properties.transform = void 0;
var _inDOM = _interopRequireDefault(inDOM.exports);
var transform = "transform";
properties.transform = transform;
var prefix, transitionEnd, animationEnd;
properties.animationEnd = animationEnd;
properties.transitionEnd = transitionEnd;
var transitionProperty, transitionDuration, transitionTiming, transitionDelay;
properties.transitionDelay = transitionDelay;
properties.transitionTiming = transitionTiming;
properties.transitionDuration = transitionDuration;
properties.transitionProperty = transitionProperty;
var animationName, animationDuration, animationTiming, animationDelay;
properties.animationDelay = animationDelay;
properties.animationTiming = animationTiming;
properties.animationDuration = animationDuration;
properties.animationName = animationName;
if (_inDOM.default) {
  var _getTransitionPropert = getTransitionProperties();
  prefix = _getTransitionPropert.prefix;
  properties.transitionEnd = transitionEnd = _getTransitionPropert.transitionEnd;
  properties.animationEnd = animationEnd = _getTransitionPropert.animationEnd;
  properties.transform = transform = prefix + "-" + transform;
  properties.transitionProperty = transitionProperty = prefix + "-transition-property";
  properties.transitionDuration = transitionDuration = prefix + "-transition-duration";
  properties.transitionDelay = transitionDelay = prefix + "-transition-delay";
  properties.transitionTiming = transitionTiming = prefix + "-transition-timing-function";
  properties.animationName = animationName = prefix + "-animation-name";
  properties.animationDuration = animationDuration = prefix + "-animation-duration";
  properties.animationTiming = animationTiming = prefix + "-animation-delay";
  properties.animationDelay = animationDelay = prefix + "-animation-timing-function";
}
var _default = {
  transform,
  end: transitionEnd,
  property: transitionProperty,
  timing: transitionTiming,
  delay: transitionDelay,
  duration: transitionDuration
};
properties.default = _default;
function getTransitionProperties() {
  var style2 = document.createElement("div").style;
  var vendorMap = {
    O: function O2(e2) {
      return "o" + e2.toLowerCase();
    },
    Moz: function Moz(e2) {
      return e2.toLowerCase();
    },
    Webkit: function Webkit(e2) {
      return "webkit" + e2;
    },
    ms: function ms(e2) {
      return "MS" + e2;
    }
  };
  var vendors = Object.keys(vendorMap);
  var transitionEnd2, animationEnd2;
  var prefix2 = "";
  for (var i2 = 0; i2 < vendors.length; i2++) {
    var vendor = vendors[i2];
    if (vendor + "TransitionProperty" in style2) {
      prefix2 = "-" + vendor.toLowerCase();
      transitionEnd2 = vendorMap[vendor]("TransitionEnd");
      animationEnd2 = vendorMap[vendor]("AnimationEnd");
      break;
    }
  }
  if (!transitionEnd2 && "transitionProperty" in style2)
    transitionEnd2 = "transitionend";
  if (!animationEnd2 && "animationName" in style2)
    animationEnd2 = "animationend";
  style2 = null;
  return {
    animationEnd: animationEnd2,
    transitionEnd: transitionEnd2,
    prefix: prefix2
  };
}
var isTransform = { exports: {} };
(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = isTransform2;
  var supportedTransforms = /^((translate|rotate|scale)(X|Y|Z|3d)?|matrix(3d)?|perspective|skew(X|Y)?)$/i;
  function isTransform2(property) {
    return !!(property && supportedTransforms.test(property));
  }
  module2.exports = exports2["default"];
})(isTransform, isTransform.exports);
(function(module2, exports2) {
  var _interopRequireDefault2 = interopRequireDefault.exports;
  exports2.__esModule = true;
  exports2.default = style2;
  var _camelizeStyle = _interopRequireDefault2(camelizeStyle.exports);
  var _hyphenateStyle = _interopRequireDefault2(hyphenateStyle.exports);
  var _getComputedStyle2 = _interopRequireDefault2(getComputedStyle$1.exports);
  var _removeStyle = _interopRequireDefault2(removeStyle.exports);
  var _properties = properties;
  var _isTransform = _interopRequireDefault2(isTransform.exports);
  function style2(node, property, value) {
    var css2 = "";
    var transforms = "";
    var props2 = property;
    if (typeof property === "string") {
      if (value === void 0) {
        return node.style[(0, _camelizeStyle.default)(property)] || (0, _getComputedStyle2.default)(node).getPropertyValue((0, _hyphenateStyle.default)(property));
      } else {
        (props2 = {})[property] = value;
      }
    }
    Object.keys(props2).forEach(function(key) {
      var value2 = props2[key];
      if (!value2 && value2 !== 0) {
        (0, _removeStyle.default)(node, (0, _hyphenateStyle.default)(key));
      } else if ((0, _isTransform.default)(key)) {
        transforms += key + "(" + value2 + ") ";
      } else {
        css2 += (0, _hyphenateStyle.default)(key) + ": " + value2 + ";";
      }
    });
    if (transforms) {
      css2 += _properties.transform + ": " + transforms + ";";
    }
    node.style.cssText += ";" + css2;
  }
  module2.exports = exports2["default"];
})(style, style.exports);
var $k7QOs$domhelpersstyle = /* @__PURE__ */ getDefaultExportFromCjs(style.exports);
var offset = { exports: {} };
var contains = { exports: {} };
(function(module2, exports2) {
  var _interopRequireDefault2 = interopRequireDefault.exports;
  exports2.__esModule = true;
  exports2.default = void 0;
  var _inDOM2 = _interopRequireDefault2(inDOM.exports);
  var _default2 = function() {
    return _inDOM2.default ? function(context, node) {
      if (context.contains) {
        return context.contains(node);
      } else if (context.compareDocumentPosition) {
        return context === node || !!(context.compareDocumentPosition(node) & 16);
      } else {
        return fallback(context, node);
      }
    } : fallback;
  }();
  exports2.default = _default2;
  function fallback(context, node) {
    if (node)
      do {
        if (node === context)
          return true;
      } while (node = node.parentNode);
    return false;
  }
  module2.exports = exports2["default"];
})(contains, contains.exports);
var isWindow = { exports: {} };
(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = getWindow;
  function getWindow(node) {
    return node === node.window ? node : node.nodeType === 9 ? node.defaultView || node.parentWindow : false;
  }
  module2.exports = exports2["default"];
})(isWindow, isWindow.exports);
var ownerDocument = { exports: {} };
(function(module2, exports2) {
  exports2.__esModule = true;
  exports2.default = ownerDocument2;
  function ownerDocument2(node) {
    return node && node.ownerDocument || document;
  }
  module2.exports = exports2["default"];
})(ownerDocument, ownerDocument.exports);
var $k7QOs$domhelpersownerDocument = /* @__PURE__ */ getDefaultExportFromCjs(ownerDocument.exports);
(function(module2, exports2) {
  var _interopRequireDefault2 = interopRequireDefault.exports;
  exports2.__esModule = true;
  exports2.default = offset2;
  var _contains = _interopRequireDefault2(contains.exports);
  var _isWindow = _interopRequireDefault2(isWindow.exports);
  var _ownerDocument = _interopRequireDefault2(ownerDocument.exports);
  function offset2(node) {
    var doc = (0, _ownerDocument.default)(node), win = (0, _isWindow.default)(doc), docElem = doc && doc.documentElement, box = {
      top: 0,
      left: 0,
      height: 0,
      width: 0
    };
    if (!doc)
      return;
    if (!(0, _contains.default)(docElem, node))
      return box;
    if (node.getBoundingClientRect !== void 0)
      box = node.getBoundingClientRect();
    box = {
      top: box.top + (win.pageYOffset || docElem.scrollTop) - (docElem.clientTop || 0),
      left: box.left + (win.pageXOffset || docElem.scrollLeft) - (docElem.clientLeft || 0),
      width: (box.width == null ? node.offsetWidth : box.width) || 0,
      height: (box.height == null ? node.offsetHeight : box.height) || 0
    };
    return box;
  }
  module2.exports = exports2["default"];
})(offset, offset.exports);
var $k7QOs$domhelpersqueryoffset = /* @__PURE__ */ getDefaultExportFromCjs(offset.exports);
var position = { exports: {} };
var _extends$1 = { exports: {} };
(function(module2) {
  function _extends2() {
    module2.exports = _extends2 = Object.assign || function(target) {
      for (var i2 = 1; i2 < arguments.length; i2++) {
        var source = arguments[i2];
        for (var key in source) {
          if (Object.prototype.hasOwnProperty.call(source, key)) {
            target[key] = source[key];
          }
        }
      }
      return target;
    }, module2.exports.__esModule = true, module2.exports["default"] = module2.exports;
    return _extends2.apply(this, arguments);
  }
  module2.exports = _extends2, module2.exports.__esModule = true, module2.exports["default"] = module2.exports;
})(_extends$1);
var offsetParent = { exports: {} };
(function(module2, exports2) {
  var _interopRequireDefault2 = interopRequireDefault.exports;
  exports2.__esModule = true;
  exports2.default = offsetParent2;
  var _ownerDocument = _interopRequireDefault2(ownerDocument.exports);
  var _style = _interopRequireDefault2(style.exports);
  function nodeName(node) {
    return node.nodeName && node.nodeName.toLowerCase();
  }
  function offsetParent2(node) {
    var doc = (0, _ownerDocument.default)(node), offsetParent3 = node && node.offsetParent;
    while (offsetParent3 && nodeName(node) !== "html" && (0, _style.default)(offsetParent3, "position") === "static") {
      offsetParent3 = offsetParent3.offsetParent;
    }
    return offsetParent3 || doc.documentElement;
  }
  module2.exports = exports2["default"];
})(offsetParent, offsetParent.exports);
var scrollTop = { exports: {} };
(function(module2, exports2) {
  var _interopRequireDefault2 = interopRequireDefault.exports;
  exports2.__esModule = true;
  exports2.default = scrollTop2;
  var _isWindow = _interopRequireDefault2(isWindow.exports);
  function scrollTop2(node, val) {
    var win = (0, _isWindow.default)(node);
    if (val === void 0)
      return win ? "pageYOffset" in win ? win.pageYOffset : win.document.documentElement.scrollTop : node.scrollTop;
    if (win)
      win.scrollTo("pageXOffset" in win ? win.pageXOffset : win.document.documentElement.scrollLeft, val);
    else
      node.scrollTop = val;
  }
  module2.exports = exports2["default"];
})(scrollTop, scrollTop.exports);
var $k7QOs$domhelpersqueryscrollTop = /* @__PURE__ */ getDefaultExportFromCjs(scrollTop.exports);
var scrollLeft = { exports: {} };
(function(module2, exports2) {
  var _interopRequireDefault2 = interopRequireDefault.exports;
  exports2.__esModule = true;
  exports2.default = scrollTop2;
  var _isWindow = _interopRequireDefault2(isWindow.exports);
  function scrollTop2(node, val) {
    var win = (0, _isWindow.default)(node);
    if (val === void 0)
      return win ? "pageXOffset" in win ? win.pageXOffset : win.document.documentElement.scrollLeft : node.scrollLeft;
    if (win)
      win.scrollTo(val, "pageYOffset" in win ? win.pageYOffset : win.document.documentElement.scrollTop);
    else
      node.scrollLeft = val;
  }
  module2.exports = exports2["default"];
})(scrollLeft, scrollLeft.exports);
var $k7QOs$domhelpersqueryscrollLeft = /* @__PURE__ */ getDefaultExportFromCjs(scrollLeft.exports);
(function(module2, exports2) {
  var _interopRequireDefault2 = interopRequireDefault.exports;
  exports2.__esModule = true;
  exports2.default = position2;
  var _extends2 = _interopRequireDefault2(_extends$1.exports);
  var _offset = _interopRequireDefault2(offset.exports);
  var _offsetParent = _interopRequireDefault2(offsetParent.exports);
  var _scrollTop = _interopRequireDefault2(scrollTop.exports);
  var _scrollLeft = _interopRequireDefault2(scrollLeft.exports);
  var _style = _interopRequireDefault2(style.exports);
  function nodeName(node) {
    return node.nodeName && node.nodeName.toLowerCase();
  }
  function position2(node, offsetParent2) {
    var parentOffset = {
      top: 0,
      left: 0
    }, offset2;
    if ((0, _style.default)(node, "position") === "fixed") {
      offset2 = node.getBoundingClientRect();
    } else {
      offsetParent2 = offsetParent2 || (0, _offsetParent.default)(node);
      offset2 = (0, _offset.default)(node);
      if (nodeName(offsetParent2) !== "html")
        parentOffset = (0, _offset.default)(offsetParent2);
      parentOffset.top += parseInt((0, _style.default)(offsetParent2, "borderTopWidth"), 10) - (0, _scrollTop.default)(offsetParent2) || 0;
      parentOffset.left += parseInt((0, _style.default)(offsetParent2, "borderLeftWidth"), 10) - (0, _scrollLeft.default)(offsetParent2) || 0;
    }
    return (0, _extends2.default)({}, offset2, {
      top: offset2.top - parentOffset.top - (parseInt((0, _style.default)(node, "marginTop"), 10) || 0),
      left: offset2.left - parentOffset.left - (parseInt((0, _style.default)(node, "marginLeft"), 10) || 0)
    });
  }
  module2.exports = exports2["default"];
})(position, position.exports);
var $k7QOs$domhelpersqueryposition = /* @__PURE__ */ getDefaultExportFromCjs(position.exports);
function $parcel$export$o(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
function $parcel$interopDefault$3(a2) {
  return a2 && a2.__esModule ? a2.default : a2;
}
var $2a41e45df1593e64$exports = {};
$parcel$export$o($2a41e45df1593e64$exports, "useOverlayPosition", () => $2a41e45df1593e64$export$d39e1813b3bdd0e1);
const $edcf132a9284368a$var$AXIS = {
  top: "top",
  bottom: "top",
  left: "left",
  right: "left"
};
const $edcf132a9284368a$var$FLIPPED_DIRECTION = {
  top: "bottom",
  bottom: "top",
  left: "right",
  right: "left"
};
const $edcf132a9284368a$var$CROSS_AXIS = {
  top: "left",
  left: "top"
};
const $edcf132a9284368a$var$AXIS_SIZE = {
  top: "height",
  left: "width"
};
const $edcf132a9284368a$var$PARSED_PLACEMENT_CACHE = {};
let $edcf132a9284368a$var$visualViewport = typeof window !== "undefined" && window.visualViewport;
function $edcf132a9284368a$var$getContainerDimensions(containerNode) {
  let width = 0, height = 0, top = 0, left = 0;
  let scroll = {};
  if (containerNode.tagName === "BODY") {
    var ref;
    width = (ref = $edcf132a9284368a$var$visualViewport === null || $edcf132a9284368a$var$visualViewport === void 0 ? void 0 : $edcf132a9284368a$var$visualViewport.width) !== null && ref !== void 0 ? ref : document.documentElement.clientWidth;
    var ref1;
    height = (ref1 = $edcf132a9284368a$var$visualViewport === null || $edcf132a9284368a$var$visualViewport === void 0 ? void 0 : $edcf132a9284368a$var$visualViewport.height) !== null && ref1 !== void 0 ? ref1 : document.documentElement.clientHeight;
    scroll.top = $k7QOs$domhelpersqueryscrollTop($k7QOs$domhelpersownerDocument(containerNode).documentElement) || $k7QOs$domhelpersqueryscrollTop(containerNode);
    scroll.left = $k7QOs$domhelpersqueryscrollLeft($k7QOs$domhelpersownerDocument(containerNode).documentElement) || $k7QOs$domhelpersqueryscrollLeft(containerNode);
  } else {
    ({ width, height, top, left } = $k7QOs$domhelpersqueryoffset(containerNode));
    scroll.top = $k7QOs$domhelpersqueryscrollTop(containerNode);
    scroll.left = $k7QOs$domhelpersqueryscrollLeft(containerNode);
  }
  return {
    width,
    height,
    scroll,
    top,
    left
  };
}
function $edcf132a9284368a$var$getScroll(node) {
  return {
    top: node.scrollTop,
    left: node.scrollLeft,
    width: node.scrollWidth,
    height: node.scrollHeight
  };
}
function $edcf132a9284368a$var$getDelta(axis, offset2, size, containerDimensions, padding) {
  let containerScroll = containerDimensions.scroll[axis];
  let containerHeight = containerDimensions[$edcf132a9284368a$var$AXIS_SIZE[axis]];
  let startEdgeOffset = offset2 - padding - containerScroll;
  let endEdgeOffset = offset2 + padding - containerScroll + size;
  if (startEdgeOffset < 0)
    return -startEdgeOffset;
  else if (endEdgeOffset > containerHeight)
    return Math.max(containerHeight - endEdgeOffset, -startEdgeOffset);
  else
    return 0;
}
function $edcf132a9284368a$var$getMargins(node) {
  let style2 = window.getComputedStyle(node);
  return {
    top: parseInt(style2.marginTop, 10) || 0,
    bottom: parseInt(style2.marginBottom, 10) || 0,
    left: parseInt(style2.marginLeft, 10) || 0,
    right: parseInt(style2.marginRight, 10) || 0
  };
}
function $edcf132a9284368a$var$parsePlacement(input) {
  if ($edcf132a9284368a$var$PARSED_PLACEMENT_CACHE[input])
    return $edcf132a9284368a$var$PARSED_PLACEMENT_CACHE[input];
  let [placement, crossPlacement] = input.split(" ");
  let axis = $edcf132a9284368a$var$AXIS[placement] || "right";
  let crossAxis = $edcf132a9284368a$var$CROSS_AXIS[axis];
  if (!$edcf132a9284368a$var$AXIS[crossPlacement])
    crossPlacement = "center";
  let size = $edcf132a9284368a$var$AXIS_SIZE[axis];
  let crossSize = $edcf132a9284368a$var$AXIS_SIZE[crossAxis];
  $edcf132a9284368a$var$PARSED_PLACEMENT_CACHE[input] = {
    placement,
    crossPlacement,
    axis,
    crossAxis,
    size,
    crossSize
  };
  return $edcf132a9284368a$var$PARSED_PLACEMENT_CACHE[input];
}
function $edcf132a9284368a$var$computePosition(childOffset, boundaryDimensions, overlaySize, placementInfo, offset2, crossOffset, containerOffsetWithBoundary, isContainerPositioned) {
  let { placement, crossPlacement, axis, crossAxis, size, crossSize } = placementInfo;
  let position2 = {};
  position2[crossAxis] = childOffset[crossAxis];
  if (crossPlacement === "center")
    position2[crossAxis] += (childOffset[crossSize] - overlaySize[crossSize]) / 2;
  else if (crossPlacement !== crossAxis)
    position2[crossAxis] += childOffset[crossSize] - overlaySize[crossSize];
  position2[crossAxis] += crossOffset;
  let minViablePosition = childOffset[crossAxis] + childOffset[crossSize] / 2 - overlaySize[crossSize];
  let maxViablePosition = childOffset[crossAxis] + childOffset[crossSize] / 2;
  position2[crossAxis] = Math.min(Math.max(minViablePosition, position2[crossAxis]), maxViablePosition);
  if (placement === axis) {
    const containerHeight = isContainerPositioned ? containerOffsetWithBoundary[size] : boundaryDimensions[size];
    position2[$edcf132a9284368a$var$FLIPPED_DIRECTION[axis]] = Math.floor(containerHeight - childOffset[axis] + offset2);
  } else
    position2[axis] = Math.floor(childOffset[axis] + childOffset[size] + offset2);
  return position2;
}
function $edcf132a9284368a$var$getMaxHeight(position2, boundaryDimensions, containerOffsetWithBoundary, childOffset, margins, padding) {
  return position2.top != null ? Math.max(0, boundaryDimensions.height + boundaryDimensions.top + boundaryDimensions.scroll.top - (containerOffsetWithBoundary.top + position2.top) - (margins.top + margins.bottom + padding)) : Math.max(0, childOffset.top + containerOffsetWithBoundary.top - (boundaryDimensions.top + boundaryDimensions.scroll.top) - (margins.top + margins.bottom + padding));
}
function $edcf132a9284368a$var$getAvailableSpace(boundaryDimensions, containerOffsetWithBoundary, childOffset, margins, padding, placementInfo) {
  let { placement, axis, size } = placementInfo;
  if (placement === axis)
    return Math.max(0, childOffset[axis] - boundaryDimensions[axis] - boundaryDimensions.scroll[axis] + containerOffsetWithBoundary[axis] - margins[axis] - margins[$edcf132a9284368a$var$FLIPPED_DIRECTION[axis]] - padding);
  return Math.max(0, boundaryDimensions[size] + boundaryDimensions[axis] + boundaryDimensions.scroll[axis] - containerOffsetWithBoundary[axis] - childOffset[axis] - childOffset[size] - margins[axis] - margins[$edcf132a9284368a$var$FLIPPED_DIRECTION[axis]] - padding);
}
function $edcf132a9284368a$export$6839422d1f33cee9(placementInput, childOffset, overlaySize, scrollSize, margins, padding, flip, boundaryDimensions, containerOffsetWithBoundary, offset2, crossOffset, isContainerPositioned, userSetMaxHeight) {
  let placementInfo = $edcf132a9284368a$var$parsePlacement(placementInput);
  let { size, crossAxis, crossSize, placement, crossPlacement } = placementInfo;
  let position2 = $edcf132a9284368a$var$computePosition(childOffset, boundaryDimensions, overlaySize, placementInfo, offset2, crossOffset, containerOffsetWithBoundary, isContainerPositioned);
  let normalizedOffset = offset2;
  let space = $edcf132a9284368a$var$getAvailableSpace(boundaryDimensions, containerOffsetWithBoundary, childOffset, margins, padding + offset2, placementInfo);
  if (flip && scrollSize[size] > space) {
    let flippedPlacementInfo = $edcf132a9284368a$var$parsePlacement(`${$edcf132a9284368a$var$FLIPPED_DIRECTION[placement]} ${crossPlacement}`);
    let flippedPosition = $edcf132a9284368a$var$computePosition(childOffset, boundaryDimensions, overlaySize, flippedPlacementInfo, offset2, crossOffset, containerOffsetWithBoundary, isContainerPositioned);
    let flippedSpace = $edcf132a9284368a$var$getAvailableSpace(boundaryDimensions, containerOffsetWithBoundary, childOffset, margins, padding + offset2, flippedPlacementInfo);
    if (flippedSpace > space) {
      placementInfo = flippedPlacementInfo;
      position2 = flippedPosition;
      normalizedOffset = offset2;
    }
  }
  let delta = $edcf132a9284368a$var$getDelta(crossAxis, position2[crossAxis], overlaySize[crossSize], boundaryDimensions, padding);
  position2[crossAxis] += delta;
  let maxHeight = $edcf132a9284368a$var$getMaxHeight(position2, boundaryDimensions, containerOffsetWithBoundary, childOffset, margins, padding);
  if (userSetMaxHeight && userSetMaxHeight < maxHeight)
    maxHeight = userSetMaxHeight;
  overlaySize.height = Math.min(overlaySize.height, maxHeight);
  position2 = $edcf132a9284368a$var$computePosition(childOffset, boundaryDimensions, overlaySize, placementInfo, normalizedOffset, crossOffset, containerOffsetWithBoundary, isContainerPositioned);
  delta = $edcf132a9284368a$var$getDelta(crossAxis, position2[crossAxis], overlaySize[crossSize], boundaryDimensions, padding);
  position2[crossAxis] += delta;
  let arrowPosition = {};
  arrowPosition[crossAxis] = childOffset[crossAxis] - position2[crossAxis] + childOffset[crossSize] / 2;
  return {
    position: position2,
    maxHeight,
    arrowOffsetLeft: arrowPosition.left,
    arrowOffsetTop: arrowPosition.top,
    placement: placementInfo.placement
  };
}
function $edcf132a9284368a$export$b3ceb0cbf1056d98(opts) {
  let { placement, targetNode, overlayNode, scrollNode, padding, shouldFlip, boundaryElement, offset: offset2, crossOffset, maxHeight } = opts;
  let container = overlayNode.offsetParent || document.body;
  let isBodyContainer = container.tagName === "BODY";
  const containerPositionStyle = window.getComputedStyle(container).position;
  let isContainerPositioned = !!containerPositionStyle && containerPositionStyle !== "static";
  let childOffset = isBodyContainer ? $k7QOs$domhelpersqueryoffset(targetNode) : $k7QOs$domhelpersqueryposition(targetNode, container);
  if (!isBodyContainer) {
    childOffset.top += parseInt($k7QOs$domhelpersstyle(targetNode, "marginTop"), 10) || 0;
    childOffset.left += parseInt($k7QOs$domhelpersstyle(targetNode, "marginLeft"), 10) || 0;
  }
  let overlaySize = $k7QOs$domhelpersqueryoffset(overlayNode);
  let margins = $edcf132a9284368a$var$getMargins(overlayNode);
  overlaySize.width += margins.left + margins.right;
  overlaySize.height += margins.top + margins.bottom;
  let scrollSize = $edcf132a9284368a$var$getScroll(scrollNode);
  let boundaryDimensions = $edcf132a9284368a$var$getContainerDimensions(boundaryElement);
  let containerOffsetWithBoundary = boundaryElement.tagName === "BODY" ? $k7QOs$domhelpersqueryoffset(container) : $k7QOs$domhelpersqueryposition(container, boundaryElement);
  return $edcf132a9284368a$export$6839422d1f33cee9(placement, childOffset, overlaySize, scrollSize, margins, padding, shouldFlip, boundaryDimensions, containerOffsetWithBoundary, offset2, crossOffset, isContainerPositioned, maxHeight);
}
const $dd149f63282afbbf$export$f6211563215e3b37 = /* @__PURE__ */ new WeakMap();
function $dd149f63282afbbf$export$18fc8428861184da(opts) {
  let { triggerRef, isOpen, onClose } = opts;
  useEffect(() => {
    if (!isOpen)
      return;
    let onScroll = (e2) => {
      let target = e2.target;
      if (!triggerRef.current || target instanceof Node && !target.contains(triggerRef.current))
        return;
      let onCloseHandler = onClose || $dd149f63282afbbf$export$f6211563215e3b37.get(triggerRef.current);
      if (onCloseHandler)
        onCloseHandler();
    };
    window.addEventListener("scroll", onScroll, true);
    return () => {
      window.removeEventListener("scroll", onScroll, true);
    };
  }, [
    isOpen,
    onClose,
    triggerRef
  ]);
}
let $2a41e45df1593e64$var$visualViewport = typeof window !== "undefined" && window.visualViewport;
function $2a41e45df1593e64$export$d39e1813b3bdd0e1(props2) {
  let { direction } = $18f2051aff69b9bf$export$43bb16f9c6d9e3f7();
  let { targetRef, overlayRef, scrollRef = overlayRef, placement = "bottom", containerPadding = 12, shouldFlip = true, boundaryElement = typeof document !== "undefined" ? document.body : null, offset: offset2 = 0, crossOffset = 0, shouldUpdatePosition = true, isOpen = true, onClose, maxHeight } = props2;
  let [position2, setPosition] = useState({
    position: {},
    arrowOffsetLeft: void 0,
    arrowOffsetTop: void 0,
    maxHeight: void 0,
    placement: void 0
  });
  let deps = [
    shouldUpdatePosition,
    placement,
    overlayRef.current,
    targetRef.current,
    scrollRef.current,
    containerPadding,
    shouldFlip,
    boundaryElement,
    offset2,
    crossOffset,
    isOpen,
    direction,
    maxHeight
  ];
  let updatePosition = useCallback(() => {
    if (shouldUpdatePosition === false || !isOpen || !overlayRef.current || !targetRef.current || !scrollRef.current || !boundaryElement)
      return;
    setPosition($edcf132a9284368a$export$b3ceb0cbf1056d98({
      placement: $2a41e45df1593e64$var$translateRTL(placement, direction),
      overlayNode: overlayRef.current,
      targetNode: targetRef.current,
      scrollNode: scrollRef.current,
      padding: containerPadding,
      shouldFlip,
      boundaryElement,
      offset: offset2,
      crossOffset,
      maxHeight
    }));
  }, deps);
  $f0a04ccd8dbdd83b$export$e5c5a5f917a5871c(updatePosition, deps);
  $2a41e45df1593e64$var$useResize(updatePosition);
  let isResizing = useRef(false);
  $f0a04ccd8dbdd83b$export$e5c5a5f917a5871c(() => {
    let timeout;
    let onResize = () => {
      isResizing.current = true;
      clearTimeout(timeout);
      timeout = setTimeout(() => {
        isResizing.current = false;
      }, 500);
      updatePosition();
    };
    $2a41e45df1593e64$var$visualViewport === null || $2a41e45df1593e64$var$visualViewport === void 0 ? void 0 : $2a41e45df1593e64$var$visualViewport.addEventListener("resize", onResize);
    return () => {
      $2a41e45df1593e64$var$visualViewport === null || $2a41e45df1593e64$var$visualViewport === void 0 ? void 0 : $2a41e45df1593e64$var$visualViewport.removeEventListener("resize", onResize);
    };
  }, [
    updatePosition
  ]);
  let close = useCallback(() => {
    if (!isResizing.current)
      onClose();
  }, [
    onClose,
    isResizing
  ]);
  $dd149f63282afbbf$export$18fc8428861184da({
    triggerRef: targetRef,
    isOpen,
    onClose: onClose ? close : void 0
  });
  return {
    overlayProps: {
      style: __spreadProps(__spreadValues({
        position: "absolute",
        zIndex: 1e5
      }, position2.position), {
        maxHeight: position2.maxHeight
      })
    },
    placement: position2.placement,
    arrowProps: {
      style: {
        left: position2.arrowOffsetLeft,
        top: position2.arrowOffsetTop
      }
    },
    updatePosition
  };
}
function $2a41e45df1593e64$var$useResize(onResize) {
  $f0a04ccd8dbdd83b$export$e5c5a5f917a5871c(() => {
    window.addEventListener("resize", onResize, false);
    return () => {
      window.removeEventListener("resize", onResize, false);
    };
  }, [
    onResize
  ]);
}
function $2a41e45df1593e64$var$translateRTL(position2, direction) {
  if (direction === "rtl")
    return position2.replace("start", "right").replace("end", "left");
  return position2.replace("start", "left").replace("end", "right");
}
var $a11501f3d1d39e6c$exports = {};
$parcel$export$o($a11501f3d1d39e6c$exports, "useOverlay", () => $a11501f3d1d39e6c$export$ea8f71083e90600f);
const $a11501f3d1d39e6c$var$visibleOverlays = [];
function $a11501f3d1d39e6c$export$ea8f71083e90600f(props2, ref) {
  let { onClose, shouldCloseOnBlur, isOpen, isDismissable = false, isKeyboardDismissDisabled = false, shouldCloseOnInteractOutside } = props2;
  useEffect(() => {
    if (isOpen)
      $a11501f3d1d39e6c$var$visibleOverlays.push(ref);
    return () => {
      let index2 = $a11501f3d1d39e6c$var$visibleOverlays.indexOf(ref);
      if (index2 >= 0)
        $a11501f3d1d39e6c$var$visibleOverlays.splice(index2, 1);
    };
  }, [
    isOpen,
    ref
  ]);
  let onHide = () => {
    if ($a11501f3d1d39e6c$var$visibleOverlays[$a11501f3d1d39e6c$var$visibleOverlays.length - 1] === ref && onClose)
      onClose();
  };
  let onInteractOutsideStart = (e2) => {
    if (!shouldCloseOnInteractOutside || shouldCloseOnInteractOutside(e2.target)) {
      if ($a11501f3d1d39e6c$var$visibleOverlays[$a11501f3d1d39e6c$var$visibleOverlays.length - 1] === ref) {
        e2.stopPropagation();
        e2.preventDefault();
      }
    }
  };
  let onInteractOutside = (e2) => {
    if (!shouldCloseOnInteractOutside || shouldCloseOnInteractOutside(e2.target)) {
      if ($a11501f3d1d39e6c$var$visibleOverlays[$a11501f3d1d39e6c$var$visibleOverlays.length - 1] === ref) {
        e2.stopPropagation();
        e2.preventDefault();
      }
      onHide();
    }
  };
  let onKeyDown = (e2) => {
    if (e2.key === "Escape" && !isKeyboardDismissDisabled) {
      e2.preventDefault();
      onHide();
    }
  };
  $e0b6e0b68ec7f50f$export$872b660ac5a1ff98({
    ref,
    onInteractOutside: isDismissable ? onInteractOutside : null,
    onInteractOutsideStart
  });
  let { focusWithinProps } = $9ab94262bd0047c7$export$420e68273165f4ec({
    isDisabled: !shouldCloseOnBlur,
    onBlurWithin: (e2) => {
      if (!shouldCloseOnInteractOutside || shouldCloseOnInteractOutside(e2.relatedTarget))
        onClose();
    }
  });
  let onPointerDownUnderlay = (e2) => {
    if (e2.target === e2.currentTarget)
      e2.preventDefault();
  };
  return {
    overlayProps: __spreadValues({
      onKeyDown
    }, focusWithinProps),
    underlayProps: {
      onPointerDown: onPointerDownUnderlay
    }
  };
}
var $628037886ba31236$exports = {};
$parcel$export$o($628037886ba31236$exports, "useOverlayTrigger", () => $628037886ba31236$export$f9d5c8beee7d008d);
function $628037886ba31236$export$f9d5c8beee7d008d(props2, state2, ref) {
  let { type } = props2;
  let { isOpen } = state2;
  useEffect(() => {
    if (ref && ref.current)
      $dd149f63282afbbf$export$f6211563215e3b37.set(ref.current, state2.close);
  });
  let ariaHasPopup = void 0;
  if (type === "menu")
    ariaHasPopup = true;
  else if (type === "listbox")
    ariaHasPopup = "listbox";
  let overlayId = $bdb11010cef70236$export$f680877a34711e37();
  return {
    triggerProps: {
      "aria-haspopup": ariaHasPopup,
      "aria-expanded": isOpen,
      "aria-controls": isOpen ? overlayId : null
    },
    overlayProps: {
      id: overlayId
    }
  };
}
var $49c51c25361d4cd2$exports = {};
$parcel$export$o($49c51c25361d4cd2$exports, "usePreventScroll", () => $49c51c25361d4cd2$export$ee0f7cc6afcd1c18);
const $49c51c25361d4cd2$var$visualViewport = typeof window !== "undefined" && window.visualViewport;
const $49c51c25361d4cd2$var$nonTextInputTypes = /* @__PURE__ */ new Set([
  "checkbox",
  "radio",
  "range",
  "color",
  "file",
  "image",
  "button",
  "submit",
  "reset"
]);
function $49c51c25361d4cd2$export$ee0f7cc6afcd1c18(options = {}) {
  let { isDisabled } = options;
  $f0a04ccd8dbdd83b$export$e5c5a5f917a5871c(() => {
    if (isDisabled)
      return;
    if ($c87311424ea30a05$export$fedb369cb70207f1())
      return $49c51c25361d4cd2$var$preventScrollMobileSafari();
    else
      return $49c51c25361d4cd2$var$preventScrollStandard();
  }, [
    isDisabled
  ]);
}
function $49c51c25361d4cd2$var$preventScrollStandard() {
  return $ff5963eb1fccf552$export$e08e3b67e392101e($49c51c25361d4cd2$var$setStyle(document.documentElement, "paddingRight", `${window.innerWidth - document.documentElement.clientWidth}px`), $49c51c25361d4cd2$var$setStyle(document.documentElement, "overflow", "hidden"));
}
function $49c51c25361d4cd2$var$preventScrollMobileSafari() {
  let scrollable;
  let lastY = 0;
  let onTouchStart = (e2) => {
    scrollable = $62d8ded9296f3872$export$cfa2225e87938781(e2.target);
    if (scrollable === document.documentElement && scrollable === document.body)
      return;
    lastY = e2.changedTouches[0].pageY;
  };
  let onTouchMove = (e2) => {
    if (scrollable === document.documentElement || scrollable === document.body) {
      e2.preventDefault();
      return;
    }
    let y2 = e2.changedTouches[0].pageY;
    let scrollTop2 = scrollable.scrollTop;
    let bottom = scrollable.scrollHeight - scrollable.clientHeight;
    if (scrollTop2 <= 0 && y2 > lastY || scrollTop2 >= bottom && y2 < lastY)
      e2.preventDefault();
    lastY = y2;
  };
  let onTouchEnd = (e2) => {
    let target = e2.target;
    if (target instanceof HTMLInputElement && !$49c51c25361d4cd2$var$nonTextInputTypes.has(target.type)) {
      e2.preventDefault();
      target.style.transform = "translateY(-2000px)";
      target.focus();
      requestAnimationFrame(() => {
        target.style.transform = "";
      });
    }
  };
  let onFocus = (e2) => {
    let target = e2.target;
    if (target instanceof HTMLInputElement && !$49c51c25361d4cd2$var$nonTextInputTypes.has(target.type)) {
      target.style.transform = "translateY(-2000px)";
      requestAnimationFrame(() => {
        target.style.transform = "";
        if ($49c51c25361d4cd2$var$visualViewport) {
          if ($49c51c25361d4cd2$var$visualViewport.height < window.innerHeight)
            requestAnimationFrame(() => {
              $49c51c25361d4cd2$var$scrollIntoView(target);
            });
          else
            $49c51c25361d4cd2$var$visualViewport.addEventListener("resize", () => $49c51c25361d4cd2$var$scrollIntoView(target), {
              once: true
            });
        }
      });
    }
  };
  let onWindowScroll = () => {
    window.scrollTo(0, 0);
  };
  let scrollX = window.pageXOffset;
  let scrollY = window.pageYOffset;
  let restoreStyles = $ff5963eb1fccf552$export$e08e3b67e392101e($49c51c25361d4cd2$var$setStyle(document.documentElement, "paddingRight", `${window.innerWidth - document.documentElement.clientWidth}px`), $49c51c25361d4cd2$var$setStyle(document.documentElement, "overflow", "hidden"), $49c51c25361d4cd2$var$setStyle(document.body, "marginTop", `-${scrollY}px`));
  window.scrollTo(0, 0);
  let removeEvents = $ff5963eb1fccf552$export$e08e3b67e392101e($49c51c25361d4cd2$var$addEvent(document, "touchstart", onTouchStart, {
    passive: false,
    capture: true
  }), $49c51c25361d4cd2$var$addEvent(document, "touchmove", onTouchMove, {
    passive: false,
    capture: true
  }), $49c51c25361d4cd2$var$addEvent(document, "touchend", onTouchEnd, {
    passive: false,
    capture: true
  }), $49c51c25361d4cd2$var$addEvent(document, "focus", onFocus, true), $49c51c25361d4cd2$var$addEvent(window, "scroll", onWindowScroll));
  return () => {
    restoreStyles();
    removeEvents();
    window.scrollTo(scrollX, scrollY);
  };
}
function $49c51c25361d4cd2$var$setStyle(element, style2, value) {
  let cur = element.style[style2];
  element.style[style2] = value;
  return () => {
    element.style[style2] = cur;
  };
}
function $49c51c25361d4cd2$var$addEvent(target, event, handler, options) {
  target.addEventListener(event, handler, options);
  return () => {
    target.removeEventListener(event, handler, options);
  };
}
function $49c51c25361d4cd2$var$scrollIntoView(target) {
  let scrollable = $62d8ded9296f3872$export$cfa2225e87938781(target);
  if (scrollable !== document.documentElement && scrollable !== document.body) {
    let scrollableTop = scrollable.getBoundingClientRect().top;
    let targetTop = target.getBoundingClientRect().top;
    if (targetTop > scrollableTop + target.clientHeight)
      scrollable.scrollTop += targetTop - scrollableTop;
  }
}
var $f57aed4a881a3485$exports = {};
$parcel$export$o($f57aed4a881a3485$exports, "ModalProvider", () => $f57aed4a881a3485$export$178405afcd8c5eb);
$parcel$export$o($f57aed4a881a3485$exports, "useModalProvider", () => $f57aed4a881a3485$export$d9aaed4c3ece1bc0);
$parcel$export$o($f57aed4a881a3485$exports, "OverlayProvider", () => $f57aed4a881a3485$export$bf688221f59024e5);
$parcel$export$o($f57aed4a881a3485$exports, "OverlayContainer", () => $f57aed4a881a3485$export$b47c3594eab58386);
$parcel$export$o($f57aed4a881a3485$exports, "useModal", () => $f57aed4a881a3485$export$33ffd74ebf07f060);
const $f57aed4a881a3485$var$Context = /* @__PURE__ */ React__default.createContext(null);
function $f57aed4a881a3485$export$178405afcd8c5eb(props2) {
  let { children } = props2;
  let parent = useContext($f57aed4a881a3485$var$Context);
  let [modalCount, setModalCount] = useState(0);
  let context = useMemo(() => ({
    parent,
    modalCount,
    addModal() {
      setModalCount((count) => count + 1);
      if (parent)
        parent.addModal();
    },
    removeModal() {
      setModalCount((count) => count - 1);
      if (parent)
        parent.removeModal();
    }
  }), [
    parent,
    modalCount
  ]);
  return /* @__PURE__ */ React__default.createElement($f57aed4a881a3485$var$Context.Provider, {
    value: context
  }, children);
}
function $f57aed4a881a3485$export$d9aaed4c3ece1bc0() {
  let context = useContext($f57aed4a881a3485$var$Context);
  return {
    modalProviderProps: {
      "aria-hidden": context && context.modalCount > 0 ? true : null
    }
  };
}
function $f57aed4a881a3485$var$OverlayContainerDOM(props2) {
  let { modalProviderProps } = $f57aed4a881a3485$export$d9aaed4c3ece1bc0();
  return /* @__PURE__ */ React__default.createElement("div", __spreadValues(__spreadValues({
    "data-overlay-container": true
  }, props2), modalProviderProps));
}
function $f57aed4a881a3485$export$bf688221f59024e5(props2) {
  return /* @__PURE__ */ React__default.createElement($f57aed4a881a3485$export$178405afcd8c5eb, null, /* @__PURE__ */ React__default.createElement($f57aed4a881a3485$var$OverlayContainerDOM, props2));
}
function $f57aed4a881a3485$export$b47c3594eab58386(props2) {
  let _a2 = props2, { portalContainer = document.body } = _a2, rest = __objRest(_a2, ["portalContainer"]);
  React__default.useEffect(() => {
    if (portalContainer.closest("[data-overlay-container]"))
      throw new Error("An OverlayContainer must not be inside another container. Please change the portalContainer prop.");
  }, [
    portalContainer
  ]);
  let contents = /* @__PURE__ */ React__default.createElement($f57aed4a881a3485$export$bf688221f59024e5, rest);
  return /* @__PURE__ */ $icz4I$reactdom.createPortal(contents, portalContainer);
}
function $f57aed4a881a3485$export$33ffd74ebf07f060(options) {
  let context = useContext($f57aed4a881a3485$var$Context);
  if (!context)
    throw new Error("Modal is not contained within a provider");
  useEffect(() => {
    if ((options === null || options === void 0 ? void 0 : options.isDisabled) || !context || !context.parent)
      return;
    context.parent.addModal();
    return () => {
      if (context && context.parent)
        context.parent.removeModal();
    };
  }, [
    context,
    context.parent,
    options === null || options === void 0 ? void 0 : options.isDisabled
  ]);
  return {
    modalProps: {
      "data-ismodal": !(options === null || options === void 0 ? void 0 : options.isDisabled)
    }
  };
}
var $86ea4cb521eb2e37$exports = {};
$parcel$export$o($86ea4cb521eb2e37$exports, "DismissButton", () => $86ea4cb521eb2e37$export$2317d149ed6f78c4);
var $61fe14465afefc5e$exports = {};
var $773d5888b972f1cf$exports = {};
$773d5888b972f1cf$exports = JSON.parse('{"dismiss":"\u062A\u062C\u0627\u0647\u0644"}');
var $d11f19852b941573$exports = {};
$d11f19852b941573$exports = JSON.parse('{"dismiss":"\u041E\u0442\u0445\u0432\u044A\u0440\u043B\u044F\u043D\u0435"}');
var $b983974c2ee1efb3$exports = {};
$b983974c2ee1efb3$exports = JSON.parse('{"dismiss":"Odstranit"}');
var $5809cc9d4e92de73$exports = {};
$5809cc9d4e92de73$exports = JSON.parse('{"dismiss":"Luk"}');
var $c68c2e4fc74398d1$exports = {};
$c68c2e4fc74398d1$exports = JSON.parse('{"dismiss":"Schlie\xDFen"}');
var $0898b4c153db2b77$exports = {};
$0898b4c153db2b77$exports = JSON.parse('{"dismiss":"\u0391\u03C0\u03CC\u03C1\u03C1\u03B9\u03C8\u03B7"}');
var $6d74810286a15183$exports = {};
$6d74810286a15183$exports = JSON.parse('{"dismiss":"Dismiss"}');
var $309d73dc65f78055$exports = {};
$309d73dc65f78055$exports = JSON.parse('{"dismiss":"Descartar"}');
var $44ad94f7205cf593$exports = {};
$44ad94f7205cf593$exports = JSON.parse('{"dismiss":"L\xF5peta"}');
var $7c28f5687f0779a9$exports = {};
$7c28f5687f0779a9$exports = JSON.parse('{"dismiss":"Hylk\xE4\xE4"}');
var $e6d75df4b68bd73a$exports = {};
$e6d75df4b68bd73a$exports = JSON.parse('{"dismiss":"Rejeter"}');
var $87505c9dab186d0f$exports = {};
$87505c9dab186d0f$exports = JSON.parse('{"dismiss":"\u05D4\u05EA\u05E2\u05DC\u05DD"}');
var $553439c3ffb3e492$exports = {};
$553439c3ffb3e492$exports = JSON.parse('{"dismiss":"Odbaci"}');
var $74cf411061b983a2$exports = {};
$74cf411061b983a2$exports = JSON.parse('{"dismiss":"Elutas\xEDt\xE1s"}');
var $e933f298574dc435$exports = {};
$e933f298574dc435$exports = JSON.parse('{"dismiss":"Ignora"}');
var $ac91fc9fe02f71f6$exports = {};
$ac91fc9fe02f71f6$exports = JSON.parse('{"dismiss":"\u9589\u3058\u308B"}');
var $52b96f86422025af$exports = {};
$52b96f86422025af$exports = JSON.parse('{"dismiss":"\uBB34\uC2DC"}');
var $c0d724c3e51dafa6$exports = {};
$c0d724c3e51dafa6$exports = JSON.parse('{"dismiss":"Atmesti"}');
var $c92899672a3fe72e$exports = {};
$c92899672a3fe72e$exports = JSON.parse('{"dismiss":"Ner\u0101d\u012Bt"}');
var $9f576b39d8e7a9d6$exports = {};
$9f576b39d8e7a9d6$exports = JSON.parse('{"dismiss":"Lukk"}');
var $9d025808aeec81a7$exports = {};
$9d025808aeec81a7$exports = JSON.parse('{"dismiss":"Negeren"}');
var $fce709921e2c0fa6$exports = {};
$fce709921e2c0fa6$exports = JSON.parse('{"dismiss":"Zignoruj"}');
var $2599cf0c4ab37f59$exports = {};
$2599cf0c4ab37f59$exports = JSON.parse('{"dismiss":"Descartar"}');
var $3c220ae7ef8a35fd$exports = {};
$3c220ae7ef8a35fd$exports = JSON.parse('{"dismiss":"Dispensar"}');
var $93562b5094072f54$exports = {};
$93562b5094072f54$exports = JSON.parse('{"dismiss":"Revocare"}');
var $cd9e2abd0d06c7b4$exports = {};
$cd9e2abd0d06c7b4$exports = JSON.parse('{"dismiss":"\u041F\u0440\u043E\u043F\u0443\u0441\u0442\u0438\u0442\u044C"}');
var $45375701f409adf1$exports = {};
$45375701f409adf1$exports = JSON.parse('{"dismiss":"Zru\u0161i\u0165"}');
var $27fab53a576de9dd$exports = {};
$27fab53a576de9dd$exports = JSON.parse('{"dismiss":"Opusti"}');
var $4438748d9952e7c7$exports = {};
$4438748d9952e7c7$exports = JSON.parse('{"dismiss":"Odbaci"}');
var $0936d7347ef4da4c$exports = {};
$0936d7347ef4da4c$exports = JSON.parse('{"dismiss":"Avvisa"}');
var $29700c92185d38f8$exports = {};
$29700c92185d38f8$exports = JSON.parse('{"dismiss":"Kapat"}');
var $662ccaf2be4c25b3$exports = {};
$662ccaf2be4c25b3$exports = JSON.parse('{"dismiss":"\u0421\u043A\u0430\u0441\u0443\u0432\u0430\u0442\u0438"}');
var $d80a27deda7cdb3c$exports = {};
$d80a27deda7cdb3c$exports = JSON.parse('{"dismiss":"\u53D6\u6D88"}');
var $2b2734393847c884$exports = {};
$2b2734393847c884$exports = JSON.parse('{"dismiss":"\u95DC\u9589"}');
$61fe14465afefc5e$exports = {
  "ar-AE": $773d5888b972f1cf$exports,
  "bg-BG": $d11f19852b941573$exports,
  "cs-CZ": $b983974c2ee1efb3$exports,
  "da-DK": $5809cc9d4e92de73$exports,
  "de-DE": $c68c2e4fc74398d1$exports,
  "el-GR": $0898b4c153db2b77$exports,
  "en-US": $6d74810286a15183$exports,
  "es-ES": $309d73dc65f78055$exports,
  "et-EE": $44ad94f7205cf593$exports,
  "fi-FI": $7c28f5687f0779a9$exports,
  "fr-FR": $e6d75df4b68bd73a$exports,
  "he-IL": $87505c9dab186d0f$exports,
  "hr-HR": $553439c3ffb3e492$exports,
  "hu-HU": $74cf411061b983a2$exports,
  "it-IT": $e933f298574dc435$exports,
  "ja-JP": $ac91fc9fe02f71f6$exports,
  "ko-KR": $52b96f86422025af$exports,
  "lt-LT": $c0d724c3e51dafa6$exports,
  "lv-LV": $c92899672a3fe72e$exports,
  "nb-NO": $9f576b39d8e7a9d6$exports,
  "nl-NL": $9d025808aeec81a7$exports,
  "pl-PL": $fce709921e2c0fa6$exports,
  "pt-BR": $2599cf0c4ab37f59$exports,
  "pt-PT": $3c220ae7ef8a35fd$exports,
  "ro-RO": $93562b5094072f54$exports,
  "ru-RU": $cd9e2abd0d06c7b4$exports,
  "sk-SK": $45375701f409adf1$exports,
  "sl-SI": $27fab53a576de9dd$exports,
  "sr-SP": $4438748d9952e7c7$exports,
  "sv-SE": $0936d7347ef4da4c$exports,
  "tr-TR": $29700c92185d38f8$exports,
  "uk-UA": $662ccaf2be4c25b3$exports,
  "zh-CN": $d80a27deda7cdb3c$exports,
  "zh-TW": $2b2734393847c884$exports
};
function $86ea4cb521eb2e37$export$2317d149ed6f78c4(props2) {
  let _a2 = props2, { onDismiss } = _a2, otherProps = __objRest(_a2, ["onDismiss"]);
  let formatMessage2 = $321bc95feeb923dd$export$ec23bf898b1eed85(/* @__PURE__ */ $parcel$interopDefault$3($61fe14465afefc5e$exports));
  let labels = $313b98861ee5dd6c$export$d6875122194c7b44(otherProps, formatMessage2("dismiss"));
  let onClick = () => {
    if (onDismiss)
      onDismiss();
  };
  return /* @__PURE__ */ React__default.createElement($5c3e21d68f1c4674$export$439d29a4e110a164, null, /* @__PURE__ */ React__default.createElement("button", __spreadProps(__spreadValues({}, labels), {
    tabIndex: -1,
    onClick
  })));
}
var $5e3802645cc19319$exports = {};
$parcel$export$o($5e3802645cc19319$exports, "ariaHideOutside", () => $5e3802645cc19319$export$1c3ebcada18427bf);
let $5e3802645cc19319$var$refCountMap = /* @__PURE__ */ new WeakMap();
function $5e3802645cc19319$export$1c3ebcada18427bf(targets, root = document.body) {
  let visibleNodes = new Set(targets);
  let hiddenNodes = /* @__PURE__ */ new Set();
  let walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT, {
    acceptNode(node) {
      if (node instanceof HTMLElement && node.dataset.liveAnnouncer === "true")
        visibleNodes.add(node);
      if (visibleNodes.has(node) || hiddenNodes.has(node.parentElement))
        return NodeFilter.FILTER_REJECT;
      if (node instanceof HTMLElement && node.getAttribute("role") === "row")
        return NodeFilter.FILTER_SKIP;
      if (targets.some((target) => node.contains(target)))
        return NodeFilter.FILTER_SKIP;
      return NodeFilter.FILTER_ACCEPT;
    }
  });
  let hide = (node) => {
    var ref;
    let refCount = (ref = $5e3802645cc19319$var$refCountMap.get(node)) !== null && ref !== void 0 ? ref : 0;
    if (node.getAttribute("aria-hidden") === "true" && refCount === 0)
      return;
    if (refCount === 0)
      node.setAttribute("aria-hidden", "true");
    hiddenNodes.add(node);
    $5e3802645cc19319$var$refCountMap.set(node, refCount + 1);
  };
  let node1 = walker.nextNode();
  while (node1 != null) {
    hide(node1);
    node1 = walker.nextNode();
  }
  let observer = new MutationObserver((changes) => {
    for (let change of changes) {
      if (change.type !== "childList" || change.addedNodes.length === 0)
        continue;
      if (![
        ...visibleNodes,
        ...hiddenNodes
      ].some((node) => node.contains(change.target)))
        for (let node2 of change.addedNodes) {
          if (node2 instanceof HTMLElement && node2.dataset.liveAnnouncer === "true")
            visibleNodes.add(node2);
          else if (node2 instanceof Element)
            hide(node2);
        }
    }
  });
  observer.observe(root, {
    childList: true,
    subtree: true
  });
  return () => {
    observer.disconnect();
    for (let node of hiddenNodes) {
      let count = $5e3802645cc19319$var$refCountMap.get(node);
      if (count === 1) {
        node.removeAttribute("aria-hidden");
        $5e3802645cc19319$var$refCountMap.delete(node);
      } else
        $5e3802645cc19319$var$refCountMap.set(node, count - 1);
    }
  };
}
function $parcel$export$n(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $52ac987c016884e9$exports = {};
$parcel$export$n($52ac987c016884e9$exports, "useSelectableCollection", () => $52ac987c016884e9$export$d6daf82dcd84e87c);
function $c636d3b6065ca9f6$export$d3e3bd3e26688c04(e2) {
  return $c87311424ea30a05$export$e1865c3bedcd822b() ? e2.altKey : e2.ctrlKey;
}
function $c636d3b6065ca9f6$export$16792effe837dba3(e2) {
  if ($c87311424ea30a05$export$9ac100e40613ea10())
    return e2.metaKey;
  return e2.ctrlKey;
}
var $a6f03d1cafa48b51$exports = {};
$parcel$export$n($a6f03d1cafa48b51$exports, "useTypeSelect", () => $a6f03d1cafa48b51$export$e32c88dfddc6e1d8);
function $a6f03d1cafa48b51$export$e32c88dfddc6e1d8(options) {
  let { keyboardDelegate, selectionManager, onTypeSelect } = options;
  let state2 = useRef({
    search: "",
    timeout: null
  }).current;
  let onKeyDown = (e2) => {
    let character = $a6f03d1cafa48b51$var$getStringForKey(e2.key);
    if (!character || e2.ctrlKey || e2.metaKey)
      return;
    if (character === " " && state2.search.trim().length > 0) {
      e2.preventDefault();
      if (!("continuePropagation" in e2))
        e2.stopPropagation();
    }
    state2.search += character;
    let key = keyboardDelegate.getKeyForSearch(state2.search, selectionManager.focusedKey);
    if (key == null)
      key = keyboardDelegate.getKeyForSearch(state2.search);
    if (key != null) {
      selectionManager.setFocusedKey(key);
      if (onTypeSelect)
        onTypeSelect(key);
    }
    clearTimeout(state2.timeout);
    state2.timeout = setTimeout(() => {
      state2.search = "";
    }, 500);
  };
  return {
    typeSelectProps: {
      onKeyDownCapture: keyboardDelegate.getKeyForSearch ? onKeyDown : null
    }
  };
}
function $a6f03d1cafa48b51$var$getStringForKey(key) {
  if (key.length === 1 || !/^[A-Z]/i.test(key))
    return key;
  return "";
}
function $52ac987c016884e9$export$d6daf82dcd84e87c(options) {
  let { selectionManager: manager, keyboardDelegate: delegate, ref, autoFocus = false, shouldFocusWrap = false, disallowEmptySelection = false, disallowSelectAll = false, selectOnFocus = manager.selectionBehavior === "replace", disallowTypeAhead = false, shouldUseVirtualFocus, allowsTabNavigation = false, isVirtualized, scrollRef = ref } = options;
  let { direction } = $18f2051aff69b9bf$export$43bb16f9c6d9e3f7();
  let onKeyDown = (e2) => {
    if (e2.altKey && e2.key === "Tab")
      e2.preventDefault();
    if (!ref.current.contains(e2.target))
      return;
    const navigateToKey = (key, childFocus) => {
      if (key != null) {
        manager.setFocusedKey(key, childFocus);
        if (e2.shiftKey && manager.selectionMode === "multiple")
          manager.extendSelection(key);
        else if (selectOnFocus && !$c636d3b6065ca9f6$export$d3e3bd3e26688c04(e2))
          manager.replaceSelection(key);
      }
    };
    switch (e2.key) {
      case "ArrowDown":
        if (delegate.getKeyBelow) {
          var ref4, ref1;
          e2.preventDefault();
          let nextKey = manager.focusedKey != null ? delegate.getKeyBelow(manager.focusedKey) : (ref4 = delegate.getFirstKey) === null || ref4 === void 0 ? void 0 : ref4.call(delegate);
          if (nextKey == null && shouldFocusWrap)
            nextKey = (ref1 = delegate.getFirstKey) === null || ref1 === void 0 ? void 0 : ref1.call(delegate, manager.focusedKey);
          navigateToKey(nextKey);
        }
        break;
      case "ArrowUp":
        if (delegate.getKeyAbove) {
          var ref2, ref3;
          e2.preventDefault();
          let nextKey = manager.focusedKey != null ? delegate.getKeyAbove(manager.focusedKey) : (ref2 = delegate.getLastKey) === null || ref2 === void 0 ? void 0 : ref2.call(delegate);
          if (nextKey == null && shouldFocusWrap)
            nextKey = (ref3 = delegate.getLastKey) === null || ref3 === void 0 ? void 0 : ref3.call(delegate, manager.focusedKey);
          navigateToKey(nextKey);
        }
        break;
      case "ArrowLeft":
        if (delegate.getKeyLeftOf) {
          e2.preventDefault();
          let nextKey = delegate.getKeyLeftOf(manager.focusedKey);
          navigateToKey(nextKey, direction === "rtl" ? "first" : "last");
        }
        break;
      case "ArrowRight":
        if (delegate.getKeyRightOf) {
          e2.preventDefault();
          let nextKey = delegate.getKeyRightOf(manager.focusedKey);
          navigateToKey(nextKey, direction === "rtl" ? "last" : "first");
        }
        break;
      case "Home":
        if (delegate.getFirstKey) {
          e2.preventDefault();
          let firstKey = delegate.getFirstKey(manager.focusedKey, $c636d3b6065ca9f6$export$16792effe837dba3(e2));
          manager.setFocusedKey(firstKey);
          if ($c636d3b6065ca9f6$export$16792effe837dba3(e2) && e2.shiftKey && manager.selectionMode === "multiple")
            manager.extendSelection(firstKey);
          else if (selectOnFocus)
            manager.replaceSelection(firstKey);
        }
        break;
      case "End":
        if (delegate.getLastKey) {
          e2.preventDefault();
          let lastKey = delegate.getLastKey(manager.focusedKey, $c636d3b6065ca9f6$export$16792effe837dba3(e2));
          manager.setFocusedKey(lastKey);
          if ($c636d3b6065ca9f6$export$16792effe837dba3(e2) && e2.shiftKey && manager.selectionMode === "multiple")
            manager.extendSelection(lastKey);
          else if (selectOnFocus)
            manager.replaceSelection(lastKey);
        }
        break;
      case "PageDown":
        if (delegate.getKeyPageBelow) {
          e2.preventDefault();
          let nextKey = delegate.getKeyPageBelow(manager.focusedKey);
          navigateToKey(nextKey);
        }
        break;
      case "PageUp":
        if (delegate.getKeyPageAbove) {
          e2.preventDefault();
          let nextKey = delegate.getKeyPageAbove(manager.focusedKey);
          navigateToKey(nextKey);
        }
        break;
      case "a":
        if ($c636d3b6065ca9f6$export$16792effe837dba3(e2) && manager.selectionMode === "multiple" && disallowSelectAll !== true) {
          e2.preventDefault();
          manager.selectAll();
        }
        break;
      case "Escape":
        e2.preventDefault();
        if (!disallowEmptySelection)
          manager.clearSelection();
        break;
      case "Tab":
        if (!allowsTabNavigation) {
          if (e2.shiftKey)
            ref.current.focus();
          else {
            let walker = $14e5c84cbc2e6e2e$export$2d6ec8fc375ceafa(ref.current, {
              tabbable: true
            });
            let next;
            let last;
            do {
              last = walker.lastChild();
              if (last)
                next = last;
            } while (last);
            if (next && !next.contains(document.activeElement))
              $7215afc6de606d6b$export$de79e2c695e052f3(next);
          }
          break;
        }
    }
  };
  let scrollPos = useRef({
    top: 0,
    left: 0
  });
  $e9faafb641e167db$export$90fc3a17d93f704c(scrollRef, "scroll", isVirtualized ? null : () => {
    scrollPos.current = {
      top: scrollRef.current.scrollTop,
      left: scrollRef.current.scrollLeft
    };
  });
  let onFocus = (e2) => {
    if (manager.isFocused) {
      if (!e2.currentTarget.contains(e2.target))
        manager.setFocused(false);
      return;
    }
    if (!e2.currentTarget.contains(e2.target))
      return;
    manager.setFocused(true);
    if (manager.focusedKey == null) {
      let navigateToFirstKey = (key) => {
        if (key != null) {
          manager.setFocusedKey(key);
          if (selectOnFocus)
            manager.replaceSelection(key);
        }
      };
      let relatedTarget = e2.relatedTarget;
      var _lastSelectedKey, _firstSelectedKey;
      if (relatedTarget && e2.currentTarget.compareDocumentPosition(relatedTarget) & Node.DOCUMENT_POSITION_FOLLOWING)
        navigateToFirstKey((_lastSelectedKey = manager.lastSelectedKey) !== null && _lastSelectedKey !== void 0 ? _lastSelectedKey : delegate.getLastKey());
      else
        navigateToFirstKey((_firstSelectedKey = manager.firstSelectedKey) !== null && _firstSelectedKey !== void 0 ? _firstSelectedKey : delegate.getFirstKey());
    } else if (!isVirtualized) {
      scrollRef.current.scrollTop = scrollPos.current.top;
      scrollRef.current.scrollLeft = scrollPos.current.left;
      let element = scrollRef.current.querySelector(`[data-key="${manager.focusedKey}"]`);
      if (element) {
        $7215afc6de606d6b$export$de79e2c695e052f3(element);
        $2f04cbc44ee30ce0$export$53a0910f038337bd(scrollRef.current, element);
      }
    }
  };
  let onBlur = (e2) => {
    if (!e2.currentTarget.contains(e2.relatedTarget))
      manager.setFocused(false);
  };
  const autoFocusRef = useRef(autoFocus);
  useEffect(() => {
    if (autoFocusRef.current) {
      let focusedKey = null;
      if (autoFocus === "first")
        focusedKey = delegate.getFirstKey();
      if (autoFocus === "last")
        focusedKey = delegate.getLastKey();
      let selectedKeys = manager.selectedKeys;
      if (selectedKeys.size)
        focusedKey = selectedKeys.values().next().value;
      manager.setFocused(true);
      manager.setFocusedKey(focusedKey);
      if (focusedKey == null && !shouldUseVirtualFocus)
        $1159c3b6ba210e4f$export$80f3e147d781571c(ref.current);
    }
    autoFocusRef.current = false;
  }, []);
  useEffect(() => {
    if (!isVirtualized && manager.focusedKey && (scrollRef === null || scrollRef === void 0 ? void 0 : scrollRef.current)) {
      let element = scrollRef.current.querySelector(`[data-key="${manager.focusedKey}"]`);
      if (element)
        $2f04cbc44ee30ce0$export$53a0910f038337bd(scrollRef.current, element);
    }
  }, [
    isVirtualized,
    scrollRef,
    manager.focusedKey
  ]);
  let handlers2 = {
    onKeyDown,
    onFocus,
    onBlur,
    onMouseDown(e2) {
      if (e2.currentTarget.contains(e2.target))
        e2.preventDefault();
    }
  };
  let { typeSelectProps } = $a6f03d1cafa48b51$export$e32c88dfddc6e1d8({
    keyboardDelegate: delegate,
    selectionManager: manager
  });
  if (!disallowTypeAhead)
    handlers2 = $3ef42575df84b30b$export$9d1611c77c2fe928(typeSelectProps, handlers2);
  let tabIndex;
  if (!shouldUseVirtualFocus)
    tabIndex = manager.focusedKey == null ? 0 : -1;
  return {
    collectionProps: __spreadProps(__spreadValues({}, handlers2), {
      tabIndex
    })
  };
}
var $5ec5a493f6042709$exports = {};
$parcel$export$n($5ec5a493f6042709$exports, "useSelectableItem", () => $5ec5a493f6042709$export$ecf600387e221c37);
function $5ec5a493f6042709$export$ecf600387e221c37(options) {
  let { selectionManager: manager, key, ref, shouldSelectOnPressUp, isVirtualized, shouldUseVirtualFocus, focus, isDisabled, onAction } = options;
  let onSelect = (e2) => {
    if (e2.pointerType === "keyboard" && $c636d3b6065ca9f6$export$d3e3bd3e26688c04(e2))
      manager.toggleSelection(key);
    else {
      if (manager.selectionMode === "none")
        return;
      if (manager.selectionMode === "single") {
        if (manager.isSelected(key) && !manager.disallowEmptySelection)
          manager.toggleSelection(key);
        else
          manager.replaceSelection(key);
      } else if (e2 && e2.shiftKey)
        manager.extendSelection(key);
      else if (manager.selectionBehavior === "toggle" || e2 && ($c636d3b6065ca9f6$export$16792effe837dba3(e2) || e2.pointerType === "touch" || e2.pointerType === "virtual"))
        manager.toggleSelection(key);
      else
        manager.replaceSelection(key);
    }
  };
  let isFocused = key === manager.focusedKey;
  useEffect(() => {
    if (isFocused && manager.isFocused && !shouldUseVirtualFocus && document.activeElement !== ref.current) {
      if (focus)
        focus();
      else
        $1159c3b6ba210e4f$export$80f3e147d781571c(ref.current);
    }
  }, [
    ref,
    isFocused,
    manager.focusedKey,
    manager.childFocusStrategy,
    manager.isFocused,
    shouldUseVirtualFocus
  ]);
  let itemProps = {};
  if (!shouldUseVirtualFocus)
    itemProps = {
      tabIndex: isFocused ? 0 : -1,
      onFocus(e2) {
        if (e2.target === ref.current)
          manager.setFocusedKey(key);
      }
    };
  let modality = useRef(null);
  let hasPrimaryAction = onAction && manager.selectionMode === "none";
  let hasSecondaryAction = onAction && manager.selectionMode !== "none" && manager.selectionBehavior === "replace";
  let allowsSelection = !isDisabled && manager.canSelectItem(key);
  let itemPressProps = {};
  if (shouldSelectOnPressUp) {
    itemPressProps.onPressStart = (e2) => {
      modality.current = e2.pointerType;
      if (e2.pointerType === "keyboard")
        onSelect(e2);
    };
    itemPressProps.onPressUp = (e2) => {
      if (e2.pointerType !== "keyboard")
        onSelect(e2);
    };
    itemPressProps.onPress = hasPrimaryAction ? () => onAction() : null;
  } else {
    itemPressProps.onPressStart = (e2) => {
      modality.current = e2.pointerType;
      if (e2.pointerType !== "touch" && e2.pointerType !== "virtual")
        onSelect(e2);
    };
    itemPressProps.onPress = (e2) => {
      if (e2.pointerType === "touch" || e2.pointerType === "virtual" || hasPrimaryAction) {
        if (hasPrimaryAction || hasSecondaryAction)
          onAction();
        else
          onSelect(e2);
      }
    };
  }
  if (!isVirtualized)
    itemProps["data-key"] = key;
  itemPressProps.preventFocusOnPress = shouldUseVirtualFocus;
  let { pressProps, isPressed } = $f6c31cce2adf654f$export$45712eceda6fad21(itemPressProps);
  let onDoubleClick = hasSecondaryAction ? (e2) => {
    if (modality.current === "mouse") {
      e2.stopPropagation();
      e2.preventDefault();
      onAction();
    }
  } : void 0;
  let { longPressProps } = $8a26561d2877236e$export$c24ed0104d07eab9({
    isDisabled: !hasSecondaryAction,
    onLongPress(e2) {
      if (e2.pointerType === "touch") {
        onSelect(e2);
        manager.setSelectionBehavior("toggle");
      }
    }
  });
  let onKeyUp = hasSecondaryAction ? (e2) => {
    if (e2.key === "Enter")
      onAction();
  } : void 0;
  return {
    itemProps: $3ef42575df84b30b$export$9d1611c77c2fe928(itemProps, allowsSelection || hasPrimaryAction ? pressProps : {}, hasSecondaryAction ? longPressProps : {}, {
      onKeyUp,
      onDoubleClick
    }),
    isPressed
  };
}
var $38e0ab555fbd8768$exports = {};
$parcel$export$n($38e0ab555fbd8768$exports, "useSelectableList", () => $38e0ab555fbd8768$export$b95089534ab7c1fd);
var $8dd8d9b0d53d6ca8$exports = {};
$parcel$export$n($8dd8d9b0d53d6ca8$exports, "ListKeyboardDelegate", () => $8dd8d9b0d53d6ca8$export$a05409b8bb224a5a);
class $8dd8d9b0d53d6ca8$export$a05409b8bb224a5a {
  getKeyBelow(key) {
    key = this.collection.getKeyAfter(key);
    while (key != null) {
      let item = this.collection.getItem(key);
      if (item.type === "item" && !this.disabledKeys.has(key))
        return key;
      key = this.collection.getKeyAfter(key);
    }
  }
  getKeyAbove(key) {
    key = this.collection.getKeyBefore(key);
    while (key != null) {
      let item = this.collection.getItem(key);
      if (item.type === "item" && !this.disabledKeys.has(key))
        return key;
      key = this.collection.getKeyBefore(key);
    }
  }
  getFirstKey() {
    let key = this.collection.getFirstKey();
    while (key != null) {
      let item = this.collection.getItem(key);
      if (item.type === "item" && !this.disabledKeys.has(key))
        return key;
      key = this.collection.getKeyAfter(key);
    }
  }
  getLastKey() {
    let key = this.collection.getLastKey();
    while (key != null) {
      let item = this.collection.getItem(key);
      if (item.type === "item" && !this.disabledKeys.has(key))
        return key;
      key = this.collection.getKeyBefore(key);
    }
  }
  getItem(key) {
    return this.ref.current.querySelector(`[data-key="${key}"]`);
  }
  getKeyPageAbove(key) {
    let menu = this.ref.current;
    let item = this.getItem(key);
    if (!item)
      return null;
    let pageY = Math.max(0, item.offsetTop + item.offsetHeight - menu.offsetHeight);
    while (item && item.offsetTop > pageY) {
      key = this.getKeyAbove(key);
      item = this.getItem(key);
    }
    return key;
  }
  getKeyPageBelow(key) {
    let menu = this.ref.current;
    let item = this.getItem(key);
    if (!item)
      return null;
    let pageY = Math.min(menu.scrollHeight, item.offsetTop - item.offsetHeight + menu.offsetHeight);
    while (item && item.offsetTop < pageY) {
      key = this.getKeyBelow(key);
      item = this.getItem(key);
    }
    return key;
  }
  getKeyForSearch(search, fromKey) {
    if (!this.collator)
      return null;
    let collection = this.collection;
    let key = fromKey || this.getFirstKey();
    while (key != null) {
      let item = collection.getItem(key);
      let substring = item.textValue.slice(0, search.length);
      if (item.textValue && this.collator.compare(substring, search) === 0)
        return key;
      key = this.getKeyBelow(key);
    }
    return null;
  }
  constructor(collection, disabledKeys, ref, collator) {
    this.collection = collection;
    this.disabledKeys = disabledKeys;
    this.ref = ref;
    this.collator = collator;
  }
}
function $38e0ab555fbd8768$export$b95089534ab7c1fd(props2) {
  let { selectionManager, collection, disabledKeys, ref, keyboardDelegate, autoFocus, shouldFocusWrap, isVirtualized, disallowEmptySelection, selectOnFocus = false, disallowTypeAhead, shouldUseVirtualFocus, allowsTabNavigation } = props2;
  let collator = $325a3faab7a68acd$export$a16aca283550c30d({
    usage: "search",
    sensitivity: "base"
  });
  let delegate = useMemo(() => keyboardDelegate || new $8dd8d9b0d53d6ca8$export$a05409b8bb224a5a(collection, disabledKeys, ref, collator), [
    keyboardDelegate,
    collection,
    disabledKeys,
    ref,
    collator
  ]);
  let { collectionProps } = $52ac987c016884e9$export$d6daf82dcd84e87c({
    ref,
    selectionManager,
    keyboardDelegate: delegate,
    autoFocus,
    shouldFocusWrap,
    disallowEmptySelection,
    selectOnFocus,
    disallowTypeAhead,
    shouldUseVirtualFocus,
    allowsTabNavigation,
    isVirtualized,
    scrollRef: ref
  });
  return {
    listProps: collectionProps
  };
}
function $parcel$interopDefault$2(a2) {
  return a2 && a2.__esModule ? a2.default : a2;
}
function $parcel$export$m(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $235cea8b956832d5$exports = {};
$parcel$export$m($235cea8b956832d5$exports, "useMenuTrigger", () => $235cea8b956832d5$export$dc9c12ed27dd1b49);
var $96dc1c2244700b52$exports = {};
var $1a8690630e322ec6$exports = {};
$1a8690630e322ec6$exports = JSON.parse('{"longPressMessage":"\u0627\u0636\u063A\u0637 \u0645\u0637\u0648\u0644\u0627\u064B \u0623\u0648 \u0627\u0636\u063A\u0637 \u0639\u0644\u0649 Alt + \u0627\u0644\u0633\u0647\u0645 \u0644\u0623\u0633\u0641\u0644 \u0644\u0641\u062A\u062D \u0627\u0644\u0642\u0627\u0626\u0645\u0629"}');
var $fc3ddb23f24e2eea$exports = {};
$fc3ddb23f24e2eea$exports = JSON.parse('{"longPressMessage":"\u041D\u0430\u0442\u0438\u0441\u043D\u0435\u0442\u0435 \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E \u0438\u043B\u0438 \u043D\u0430\u0442\u0438\u0441\u043D\u0435\u0442\u0435 Alt+ \u0441\u0442\u0440\u0435\u043B\u043A\u0430 \u043D\u0430\u0434\u043E\u043B\u0443, \u0437\u0430 \u0434\u0430 \u043E\u0442\u0432\u043E\u0440\u0438\u0442\u0435 \u043C\u0435\u043D\u044E\u0442\u043E"}');
var $eb1dc9b603d71109$exports = {};
$eb1dc9b603d71109$exports = JSON.parse('{"longPressMessage":"Dlouh\xFDm stiskem nebo stisknut\xEDm kl\xE1ves Alt + \u0161ipka dol\u016F otev\u0159ete nab\xEDdku"}');
var $2d95ec734354bc1d$exports = {};
$2d95ec734354bc1d$exports = JSON.parse('{"longPressMessage":"Langt tryk eller tryk p\xE5 Alt + pil ned for at \xE5bne menuen"}');
var $e5cd075746034abd$exports = {};
$e5cd075746034abd$exports = JSON.parse('{"longPressMessage":"Dr\xFCcken Sie lange oder dr\xFCcken Sie Alt + Nach-unten, um das Men\xFC zu \xF6ffnen"}');
var $74fe177ce68f16a7$exports = {};
$74fe177ce68f16a7$exports = JSON.parse('{"longPressMessage":"\u03A0\u03B9\u03AD\u03C3\u03C4\u03B5 \u03C0\u03B1\u03C1\u03B1\u03C4\u03B5\u03C4\u03B1\u03BC\u03AD\u03BD\u03B1 \u03AE \u03C0\u03B1\u03C4\u03AE\u03C3\u03C4\u03B5 Alt + \u03BA\u03AC\u03C4\u03C9 \u03B2\u03AD\u03BB\u03BF\u03C2 \u03B3\u03B9\u03B1 \u03BD\u03B1 \u03B1\u03BD\u03BF\u03AF\u03BE\u03B5\u03C4\u03B5 \u03C4\u03BF \u03BC\u03B5\u03BD\u03BF\u03CD"}');
var $a59d721fbb9df903$exports = {};
$a59d721fbb9df903$exports = JSON.parse('{"longPressMessage":"Long press or press Alt + ArrowDown to open menu"}');
var $617e1630a7dd16ea$exports = {};
$617e1630a7dd16ea$exports = JSON.parse('{"longPressMessage":"Mantenga pulsado o pulse Alt + flecha abajo para abrir el men\xFA"}');
var $3218d8c72495e96b$exports = {};
$3218d8c72495e96b$exports = JSON.parse('{"longPressMessage":"Men\xFC\xFC avamiseks vajutage pikalt v\xF5i vajutage klahve Alt + allanool"}');
var $f2f412c97ede0995$exports = {};
$f2f412c97ede0995$exports = JSON.parse('{"longPressMessage":"Avaa valikko painamalla pohjassa tai n\xE4pp\xE4inyhdistelm\xE4ll\xE4 Alt + Alanuoli"}');
var $7640150678ab200d$exports = {};
$7640150678ab200d$exports = JSON.parse('{"longPressMessage":"Appuyez de mani\xE8re prolong\xE9e ou appuyez sur Alt\xA0+\xA0Fl\xE8che vers le bas pour ouvrir le menu."}');
var $84c642b6d2ee0f06$exports = {};
$84c642b6d2ee0f06$exports = JSON.parse('{"longPressMessage":"\u05DC\u05D7\u05E5 \u05DC\u05D7\u05D9\u05E6\u05D4 \u05D0\u05E8\u05D5\u05DB\u05D4 \u05D0\u05D5 \u05D4\u05E7\u05E9 Alt + ArrowDown \u05DB\u05D3\u05D9 \u05DC\u05E4\u05EA\u05D5\u05D7 \u05D0\u05EA \u05D4\u05EA\u05E4\u05E8\u05D9\u05D8"}');
var $57727cf256b928dd$exports = {};
$57727cf256b928dd$exports = JSON.parse('{"longPressMessage":"Dugo pritisnite ili pritisnite Alt + strelicu prema dolje za otvaranje izbornika"}');
var $05114af5675ffd82$exports = {};
$05114af5675ffd82$exports = JSON.parse('{"longPressMessage":"Nyomja meg hosszan, vagy nyomja meg az Alt + lefele ny\xEDl gombot a men\xFC megnyit\xE1s\xE1hoz"}');
var $38a13f141610baa6$exports = {};
$38a13f141610baa6$exports = JSON.parse('{"longPressMessage":"Premere a lungo o premere Alt + Freccia gi\xF9 per aprire il menu"}');
var $02ea00ed085de6ca$exports = {};
$02ea00ed085de6ca$exports = JSON.parse('{"longPressMessage":"\u9577\u62BC\u3057\u307E\u305F\u306F Alt+\u4E0B\u77E2\u5370\u30AD\u30FC\u3067\u30E1\u30CB\u30E5\u30FC\u3092\u958B\u304F"}');
var $220ff1248b85a717$exports = {};
$220ff1248b85a717$exports = JSON.parse('{"longPressMessage":"\uAE38\uAC8C \uB204\uB974\uAC70\uB098 Alt + \uC544\uB798\uCABD \uD654\uC0B4\uD45C\uB97C \uB20C\uB7EC \uBA54\uB274 \uC5F4\uAE30"}');
var $bf5ad8f2c050e288$exports = {};
$bf5ad8f2c050e288$exports = JSON.parse('{"longPressMessage":"Nor\u0117dami atidaryti meniu, nuspaud\u0119 palaikykite arba paspauskite \u201EAlt + ArrowDown\u201C."}');
var $f3bc8e284003309a$exports = {};
$f3bc8e284003309a$exports = JSON.parse('{"longPressMessage":"Lai atv\u0113rtu izv\u0113lni, turiet nospiestu vai nospiediet tausti\u0146u kombin\u0101ciju Alt + lejupv\u0113rst\u0101 bulti\u0146a"}');
var $7cb4a85cce2978c1$exports = {};
$7cb4a85cce2978c1$exports = JSON.parse('{"longPressMessage":"Langt trykk eller trykk Alt + PilNed for \xE5 \xE5pne menyen"}');
var $4bbc2c2d2f167f68$exports = {};
$4bbc2c2d2f167f68$exports = JSON.parse('{"longPressMessage":"Druk lang op Alt + pijl-omlaag of druk op Alt om het menu te openen"}');
var $ed008113cc0b674e$exports = {};
$ed008113cc0b674e$exports = JSON.parse('{"longPressMessage":"Naci\u015Bnij i przytrzymaj lub naci\u015Bnij klawisze Alt + Strza\u0142ka w d\xF3\u0142, aby otworzy\u0107 menu"}');
var $62bfb2a2daab045d$exports = {};
$62bfb2a2daab045d$exports = JSON.parse('{"longPressMessage":"Pressione e segure ou pressione Alt + Seta para baixo para abrir o menu"}');
var $856d8cc1d19b4c06$exports = {};
$856d8cc1d19b4c06$exports = JSON.parse('{"longPressMessage":"Prima continuamente ou prima Alt + Seta Para Baixo para abrir o menu"}');
var $a46dcfaf580fda03$exports = {};
$a46dcfaf580fda03$exports = JSON.parse('{"longPressMessage":"Ap\u0103sa\u021Bi lung sau ap\u0103sa\u021Bi pe Alt + s\u0103geat\u0103 \xEEn jos pentru a deschide meniul"}');
var $d919ca79cce015eb$exports = {};
$d919ca79cce015eb$exports = JSON.parse('{"longPressMessage":"\u041D\u0430\u0436\u043C\u0438\u0442\u0435 \u0438 \u0443\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u0439\u0442\u0435 \u0438\u043B\u0438 \u043D\u0430\u0436\u043C\u0438\u0442\u0435 Alt + \u0421\u0442\u0440\u0435\u043B\u043A\u0430 \u0432\u043D\u0438\u0437, \u0447\u0442\u043E\u0431\u044B \u043E\u0442\u043A\u0440\u044B\u0442\u044C \u043C\u0435\u043D\u044E"}');
var $dcee2f03ab5d79f4$exports = {};
$dcee2f03ab5d79f4$exports = JSON.parse('{"longPressMessage":"Ponuku otvor\xEDte dlh\xFDm stla\u010Den\xEDm alebo stla\u010Den\xEDm kl\xE1vesu Alt + kl\xE1vesu so \u0161\xEDpkou nadol"}');
var $ec308c4d4a31d7ef$exports = {};
$ec308c4d4a31d7ef$exports = JSON.parse('{"longPressMessage":"Za odprtje menija pritisnite in dr\u017Eite gumb ali pritisnite Alt+pu\u0161\u010Dica navzdol"}');
var $639001ec689e223b$exports = {};
$639001ec689e223b$exports = JSON.parse('{"longPressMessage":"Dugo pritisnite ili pritisnite Alt + strelicu prema dole da otvorite meni"}');
var $37090bf5b661009a$exports = {};
$37090bf5b661009a$exports = JSON.parse('{"longPressMessage":"H\xE5ll nedtryckt eller tryck p\xE5 Alt + pil ned\xE5t f\xF6r att \xF6ppna menyn"}');
var $4ca70371ce142708$exports = {};
$4ca70371ce142708$exports = JSON.parse('{"longPressMessage":"Men\xFCy\xFC a\xE7mak i\xE7in uzun bas\u0131n veya Alt + A\u015Fa\u011F\u0131 Ok tu\u015Funa bas\u0131n"}');
var $772cc5075c4120ad$exports = {};
$772cc5075c4120ad$exports = JSON.parse('{"longPressMessage":"\u0414\u043E\u0432\u0433\u043E \u0430\u0431\u043E \u0437\u0432\u0438\u0447\u0430\u0439\u043D\u043E \u043D\u0430\u0442\u0438\u0441\u043D\u0456\u0442\u044C \u043A\u043E\u043C\u0431\u0456\u043D\u0430\u0446\u0456\u044E \u043A\u043B\u0430\u0432\u0456\u0448 Alt \u0456 \u0441\u0442\u0440\u0456\u043B\u043A\u0430 \u0432\u043D\u0438\u0437, \u0449\u043E\u0431 \u0432\u0456\u0434\u043A\u0440\u0438\u0442\u0438 \u043C\u0435\u043D\u044E"}');
var $a280148193f17e0f$exports = {};
$a280148193f17e0f$exports = JSON.parse('{"longPressMessage":"\u957F\u6309\u6216\u6309 Alt + \u5411\u4E0B\u65B9\u5411\u952E\u4EE5\u6253\u5F00\u83DC\u5355"}');
var $08dca4706d9e39f3$exports = {};
$08dca4706d9e39f3$exports = JSON.parse('{"longPressMessage":"\u9577\u6309\u6216\u6309 Alt+\u5411\u4E0B\u9375\u4EE5\u958B\u555F\u529F\u80FD\u8868"}');
$96dc1c2244700b52$exports = {
  "ar-AE": $1a8690630e322ec6$exports,
  "bg-BG": $fc3ddb23f24e2eea$exports,
  "cs-CZ": $eb1dc9b603d71109$exports,
  "da-DK": $2d95ec734354bc1d$exports,
  "de-DE": $e5cd075746034abd$exports,
  "el-GR": $74fe177ce68f16a7$exports,
  "en-US": $a59d721fbb9df903$exports,
  "es-ES": $617e1630a7dd16ea$exports,
  "et-EE": $3218d8c72495e96b$exports,
  "fi-FI": $f2f412c97ede0995$exports,
  "fr-FR": $7640150678ab200d$exports,
  "he-IL": $84c642b6d2ee0f06$exports,
  "hr-HR": $57727cf256b928dd$exports,
  "hu-HU": $05114af5675ffd82$exports,
  "it-IT": $38a13f141610baa6$exports,
  "ja-JP": $02ea00ed085de6ca$exports,
  "ko-KR": $220ff1248b85a717$exports,
  "lt-LT": $bf5ad8f2c050e288$exports,
  "lv-LV": $f3bc8e284003309a$exports,
  "nb-NO": $7cb4a85cce2978c1$exports,
  "nl-NL": $4bbc2c2d2f167f68$exports,
  "pl-PL": $ed008113cc0b674e$exports,
  "pt-BR": $62bfb2a2daab045d$exports,
  "pt-PT": $856d8cc1d19b4c06$exports,
  "ro-RO": $a46dcfaf580fda03$exports,
  "ru-RU": $d919ca79cce015eb$exports,
  "sk-SK": $dcee2f03ab5d79f4$exports,
  "sl-SI": $ec308c4d4a31d7ef$exports,
  "sr-SP": $639001ec689e223b$exports,
  "sv-SE": $37090bf5b661009a$exports,
  "tr-TR": $4ca70371ce142708$exports,
  "uk-UA": $772cc5075c4120ad$exports,
  "zh-CN": $a280148193f17e0f$exports,
  "zh-TW": $08dca4706d9e39f3$exports
};
function $235cea8b956832d5$export$dc9c12ed27dd1b49(props2, state2, ref) {
  let { type = "menu", isDisabled, trigger = "press" } = props2;
  let menuTriggerId = $bdb11010cef70236$export$f680877a34711e37();
  let { triggerProps, overlayProps } = $628037886ba31236$export$f9d5c8beee7d008d({
    type
  }, state2, ref);
  let onKeyDown = (e2) => {
    if (isDisabled)
      return;
    if (trigger === "longPress" && !e2.altKey)
      return;
    if (ref && ref.current)
      switch (e2.key) {
        case "Enter":
        case " ":
          if (trigger === "longPress")
            return;
        case "ArrowDown":
          if (!("continuePropagation" in e2))
            e2.stopPropagation();
          e2.preventDefault();
          state2.toggle("first");
          break;
        case "ArrowUp":
          if (!("continuePropagation" in e2))
            e2.stopPropagation();
          e2.preventDefault();
          state2.toggle("last");
          break;
      }
  };
  let formatMessage2 = $321bc95feeb923dd$export$ec23bf898b1eed85(/* @__PURE__ */ $parcel$interopDefault$2($96dc1c2244700b52$exports));
  let { longPressProps } = $8a26561d2877236e$export$c24ed0104d07eab9({
    accessibilityDescription: formatMessage2("longPressMessage"),
    onLongPressStart() {
      state2.close();
    },
    onLongPress() {
      state2.open("first");
    }
  });
  let pressProps = {
    onPressStart(e2) {
      if (e2.pointerType !== "touch" && e2.pointerType !== "keyboard" && !isDisabled)
        state2.toggle(e2.pointerType === "virtual" ? "first" : null);
    },
    onPress(e2) {
      if (e2.pointerType === "touch" && !isDisabled)
        state2.toggle();
    }
  };
  triggerProps = $3ef42575df84b30b$export$9d1611c77c2fe928(triggerProps, trigger === "press" ? pressProps : longPressProps);
  return {
    menuTriggerProps: __spreadProps(__spreadValues({}, triggerProps), {
      id: menuTriggerId,
      onKeyDown
    }),
    menuProps: __spreadProps(__spreadValues({}, overlayProps), {
      "aria-labelledby": menuTriggerId
    })
  };
}
var $9e81e1e13d86f3bd$exports = {};
$parcel$export$m($9e81e1e13d86f3bd$exports, "useMenu", () => $9e81e1e13d86f3bd$export$38eaa17faae8f579);
function $9e81e1e13d86f3bd$export$38eaa17faae8f579(props2, state2, ref) {
  let _a2 = props2, { shouldFocusWrap = true } = _a2, otherProps = __objRest(_a2, ["shouldFocusWrap"]);
  if (!props2["aria-label"] && !props2["aria-labelledby"])
    console.warn("An aria-label or aria-labelledby prop is required for accessibility.");
  let domProps = $65484d02dcb7eb3e$export$457c3d6518dd4c6f(props2, {
    labelable: true
  });
  let { listProps } = $38e0ab555fbd8768$export$b95089534ab7c1fd(__spreadProps(__spreadValues({}, otherProps), {
    ref,
    selectionManager: state2.selectionManager,
    collection: state2.collection,
    disabledKeys: state2.disabledKeys,
    shouldFocusWrap
  }));
  return {
    menuProps: $3ef42575df84b30b$export$9d1611c77c2fe928(domProps, __spreadValues({
      role: "menu"
    }, listProps))
  };
}
var $c5d816999d2ff723$exports = {};
$parcel$export$m($c5d816999d2ff723$exports, "useMenuItem", () => $c5d816999d2ff723$export$9d32628fc2aea7da);
function $c5d816999d2ff723$export$9d32628fc2aea7da(props2, state2, ref) {
  let { isSelected, isDisabled, key, onClose, closeOnSelect, isVirtualized, onAction } = props2;
  let role = "menuitem";
  if (state2.selectionManager.selectionMode === "single")
    role = "menuitemradio";
  else if (state2.selectionManager.selectionMode === "multiple")
    role = "menuitemcheckbox";
  let labelId = $bdb11010cef70236$export$b4cc09c592e8fdb8();
  let descriptionId = $bdb11010cef70236$export$b4cc09c592e8fdb8();
  let keyboardId = $bdb11010cef70236$export$b4cc09c592e8fdb8();
  let ariaProps = {
    "aria-disabled": isDisabled,
    role,
    "aria-label": props2["aria-label"],
    "aria-labelledby": labelId,
    "aria-describedby": [
      descriptionId,
      keyboardId
    ].filter(Boolean).join(" ") || void 0
  };
  if (state2.selectionManager.selectionMode !== "none")
    ariaProps["aria-checked"] = isSelected;
  if (isVirtualized) {
    ariaProps["aria-posinset"] = state2.collection.getItem(key).index;
    ariaProps["aria-setsize"] = $c6b7d36982dcfffc$export$77d5aafae4e095b2(state2.collection);
  }
  let onKeyDown = (e2) => {
    if (e2.repeat)
      return;
    switch (e2.key) {
      case " ":
        if (!isDisabled && state2.selectionManager.selectionMode === "none" && closeOnSelect !== false && onClose)
          onClose();
        break;
      case "Enter":
        if (!isDisabled && closeOnSelect !== false && onClose)
          onClose();
        break;
    }
  };
  let onPressStart = (e2) => {
    if (e2.pointerType === "keyboard" && onAction)
      onAction(key);
  };
  let onPressUp = (e2) => {
    if (e2.pointerType !== "keyboard") {
      if (onAction)
        onAction(key);
      if (onClose && (closeOnSelect !== null && closeOnSelect !== void 0 ? closeOnSelect : state2.selectionManager.selectionMode !== "multiple"))
        onClose();
    }
  };
  let { itemProps } = $5ec5a493f6042709$export$ecf600387e221c37({
    selectionManager: state2.selectionManager,
    key,
    ref,
    shouldSelectOnPressUp: true
  });
  let { pressProps } = $f6c31cce2adf654f$export$45712eceda6fad21({
    onPressStart,
    onPressUp,
    isDisabled
  });
  let { hoverProps } = $6179b936705e76d3$export$ae780daf29e6d456({
    isDisabled,
    onHoverStart() {
      if (!$507fabe10e71c6fb$export$b9b3dfddab17db27()) {
        state2.selectionManager.setFocused(true);
        state2.selectionManager.setFocusedKey(key);
      }
    }
  });
  return {
    menuItemProps: __spreadValues(__spreadValues({}, ariaProps), $3ef42575df84b30b$export$9d1611c77c2fe928(itemProps, pressProps, hoverProps, {
      onKeyDown
    })),
    labelProps: {
      id: labelId
    },
    descriptionProps: {
      id: descriptionId
    },
    keyboardShortcutProps: {
      id: keyboardId
    }
  };
}
var $2e6444d9033828ce$exports = {};
$parcel$export$m($2e6444d9033828ce$exports, "useMenuSection", () => $2e6444d9033828ce$export$73f7a44322579622);
function $2e6444d9033828ce$export$73f7a44322579622(props2) {
  let { heading, "aria-label": ariaLabel } = props2;
  let headingId = $bdb11010cef70236$export$f680877a34711e37();
  return {
    itemProps: {
      role: "presentation"
    },
    headingProps: heading ? {
      id: headingId,
      "aria-hidden": true
    } : {},
    groupProps: {
      role: "group",
      "aria-label": ariaLabel,
      "aria-labelledby": heading ? headingId : void 0
    }
  };
}
const MOBILE_SCREEN_WIDTH = 700;
function useIsMobileDevice() {
  const isSSR2 = $9d939cbc98267846$export$535bd6ca7f90a273();
  if (isSSR2 || typeof window === "undefined") {
    return false;
  }
  return window.screen.width <= MOBILE_SCREEN_WIDTH;
}
const popoverStyle = "bg-paper shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none rounded overflow-hidden";
const PopoverAnimation = {
  initial: {
    opacity: 0,
    y: 5
  },
  animate: {
    opacity: 1,
    y: 0
  },
  exit: {
    opacity: 0,
    y: 5
  },
  transition: {
    type: "tween",
    duration: 0.125
  }
};
function Overlay(props2) {
  var _b;
  const _a2 = props2, {
    children,
    className,
    type
  } = _a2, otherProps = __objRest(_a2, [
    "children",
    "className",
    "type"
  ]);
  const contextValue = useContext(OverlayPositionContext);
  let zIndex;
  if (type === "modal") {
    zIndex = "z-modal";
  } else if (type === "popover") {
    zIndex = "z-popover";
  } else {
    zIndex = "z-tray";
  }
  return /* @__PURE__ */ jsx($f57aed4a881a3485$export$b47c3594eab58386, __spreadProps(__spreadValues({
    className: clsx("isolate absolute top-0 left-0", type !== "popover" && "w-full h-full", zIndex, className),
    portalContainer: (_b = contextValue == null ? void 0 : contextValue.portalContainer) == null ? void 0 : _b.current
  }, otherProps), {
    children
  }));
}
const Popover = React__default.forwardRef((props2, ref) => {
  const _a2 = props2, {
    children,
    onClose,
    isOpen,
    shouldCloseOnBlur,
    hideArrow,
    isKeyboardDismissDisabled,
    isNonModal,
    isDismissable = true,
    preventScroll = true
  } = _a2, otherProps = __objRest(_a2, [
    "children",
    "onClose",
    "isOpen",
    "shouldCloseOnBlur",
    "hideArrow",
    "isKeyboardDismissDisabled",
    "isNonModal",
    "isDismissable",
    "preventScroll"
  ]);
  $49c51c25361d4cd2$export$ee0f7cc6afcd1c18({
    isDisabled: !preventScroll
  });
  return /* @__PURE__ */ jsx(Overlay, {
    type: "popover",
    children: /* @__PURE__ */ jsx(PopoverWrapper, __spreadProps(__spreadValues({}, otherProps), {
      ref,
      shouldCloseOnBlur,
      isKeyboardDismissDisabled,
      hideArrow,
      isNonModal,
      isDismissable,
      isOpen,
      onClose,
      children
    }))
  });
});
const PopoverWrapper = React__default.forwardRef((props2, ref) => {
  const _a2 = props2, {
    children,
    isOpen,
    onClose,
    hideArrow,
    shouldCloseOnBlur,
    isKeyboardDismissDisabled,
    isNonModal,
    isDismissable
  } = _a2, otherProps = __objRest(_a2, [
    "children",
    "isOpen",
    "onClose",
    "hideArrow",
    "shouldCloseOnBlur",
    "isKeyboardDismissDisabled",
    "isNonModal",
    "isDismissable"
  ]);
  const objRef = $df56164dff5785e2$export$4338b53315abf666(ref);
  const {
    overlayProps
  } = $a11501f3d1d39e6c$export$ea8f71083e90600f(__spreadProps(__spreadValues({}, props2), {
    isDismissable: isDismissable && isOpen
  }), objRef);
  const {
    modalProps
  } = $f57aed4a881a3485$export$33ffd74ebf07f060({
    isDisabled: isNonModal
  });
  return /* @__PURE__ */ jsxs(m$2.div, __spreadProps(__spreadValues(__spreadValues({
    ref: objRef
  }, PopoverAnimation), $3ef42575df84b30b$export$9d1611c77c2fe928(otherProps, overlayProps, modalProps)), {
    className: popoverStyle,
    role: "presentation",
    children: [children, hideArrow ? null : /* @__PURE__ */ jsx(Arrow, {
      popoverPlacement: "bottom"
    })]
  }));
});
function Arrow({
  popoverPlacement
}) {
  const className = clsx("absolute fill-background", popoverPlacement === "top" && "-translate-x-1/2 left-1/2", popoverPlacement === "bottom" && "-translate-x-1/2 left-1/2 rotate-180", popoverPlacement === "left" && "-translate-y-1/2 top-1/2 rotate-90", popoverPlacement === "right" && "-translate-y-1/2 top-1/2 -rotate-90");
  return /* @__PURE__ */ jsx("svg", {
    className,
    width: "16",
    height: "8",
    viewBox: "0 0 30 10",
    preserveAspectRatio: "none",
    children: /* @__PURE__ */ jsx("polygon", {
      points: "0,0 30,0 15,10"
    })
  });
}
const MenuContext = React__default.createContext(null);
function useMenuContext() {
  return useContext(MenuContext);
}
function Underlay({
  disableInitialTransition,
  position: position2
}) {
  return /* @__PURE__ */ jsx(m$2.div, {
    className: `w-full h-full bg-black/30 ${position2 || "absolute"} top-0 left-0 z-10`,
    "aria-hidden": true,
    initial: {
      opacity: disableInitialTransition ? 1 : 0
    },
    animate: {
      opacity: 1
    },
    exit: {
      opacity: 0
    },
    transition: {
      duration: 0.3
    }
  });
}
function Tray(props2) {
  const _a2 = props2, {
    children,
    isOpen,
    onClose,
    isFixedHeight,
    isNonModal
  } = _a2, otherProps = __objRest(_a2, [
    "children",
    "isOpen",
    "onClose",
    "isFixedHeight",
    "isNonModal"
  ]);
  const domRef = useRef(null);
  const {
    overlayProps,
    underlayProps
  } = $a11501f3d1d39e6c$export$ea8f71083e90600f(__spreadProps(__spreadValues({}, props2), {
    isDismissable: true
  }), domRef);
  return /* @__PURE__ */ jsxs(Overlay, __spreadProps(__spreadValues({
    type: "tray"
  }, otherProps), {
    children: [/* @__PURE__ */ jsx(Underlay, __spreadValues({}, underlayProps)), /* @__PURE__ */ jsx(TrayWrapper, {
      onClose,
      ref: domRef,
      overlayProps,
      isFixedHeight,
      isNonModal,
      children
    })]
  }));
}
const TrayWrapper = forwardRef((props2, ref) => {
  const _a2 = props2, {
    children,
    isOpen,
    isFixedHeight,
    isNonModal,
    overlayProps
  } = _a2, otherProps = __objRest(_a2, [
    "children",
    "isOpen",
    "isFixedHeight",
    "isNonModal",
    "overlayProps"
  ]);
  $49c51c25361d4cd2$export$ee0f7cc6afcd1c18();
  const {
    modalProps
  } = $f57aed4a881a3485$export$33ffd74ebf07f060({
    isDisabled: isNonModal
  });
  const viewport = $5df64b3807dc15ee$export$d699905dd57c73ca();
  const [height, setHeight] = useState(viewport.height);
  const timeoutRef = useRef();
  useEffect(() => {
    clearTimeout(timeoutRef.current);
    if (viewport.height < height && viewport.height < window.innerHeight) {
      timeoutRef.current = setTimeout(() => {
        setHeight(viewport.height);
      }, 500);
    } else {
      setHeight(viewport.height);
    }
  }, [height, viewport.height]);
  const style2 = {
    maxHeight: `${viewport.height - 64}px`
  };
  const domProps = $3ef42575df84b30b$export$9d1611c77c2fe928(otherProps, overlayProps, {
    style: style2
  });
  return /* @__PURE__ */ jsx(m$2.div, {
    initial: {
      opacity: 0,
      y: "100%"
    },
    animate: {
      opacity: 1,
      y: 0
    },
    exit: {
      opacity: 0,
      y: "100%"
    },
    transition: {
      type: "tween",
      duration: 0.2
    },
    className: "absolute bottom-0 left-0 w-full z-20",
    children: /* @__PURE__ */ jsx("div", __spreadProps(__spreadValues(__spreadValues({}, domProps), modalProps), {
      className: "max-w-375 w-full pb-safe-area mx-auto bg-paper rounded shadow-lg",
      ref,
      children
    }))
  });
});
function t(t2) {
  return t2.split("-")[0];
}
function e(t2) {
  return t2.split("-")[1];
}
function n$1(e2) {
  return ["top", "bottom"].includes(t(e2)) ? "x" : "y";
}
function r$1(t2) {
  return t2 === "y" ? "height" : "width";
}
function i$2(i2, o2, l2) {
  let { reference: a2, floating: s2 } = i2;
  const c2 = a2.x + a2.width / 2 - s2.width / 2, f2 = a2.y + a2.height / 2 - s2.height / 2, u2 = n$1(o2), m2 = r$1(u2), g2 = a2[m2] / 2 - s2[m2] / 2, d2 = u2 === "x";
  let p2;
  switch (t(o2)) {
    case "top":
      p2 = { x: c2, y: a2.y - s2.height };
      break;
    case "bottom":
      p2 = { x: c2, y: a2.y + a2.height };
      break;
    case "right":
      p2 = { x: a2.x + a2.width, y: f2 };
      break;
    case "left":
      p2 = { x: a2.x - s2.width, y: f2 };
      break;
    default:
      p2 = { x: a2.x, y: a2.y };
  }
  switch (e(o2)) {
    case "start":
      p2[u2] -= g2 * (l2 && d2 ? -1 : 1);
      break;
    case "end":
      p2[u2] += g2 * (l2 && d2 ? -1 : 1);
  }
  return p2;
}
const o$1 = async (t2, e2, n2) => {
  const { placement: r2 = "bottom", strategy: o2 = "absolute", middleware: l2 = [], platform: a2 } = n2, s2 = await (a2.isRTL == null ? void 0 : a2.isRTL(e2));
  let c2 = await a2.getElementRects({ reference: t2, floating: e2, strategy: o2 }), { x: f2, y: u2 } = i$2(c2, r2, s2), m2 = r2, g2 = {};
  for (let n3 = 0; n3 < l2.length; n3++) {
    const { name: d2, fn: p2 } = l2[n3], { x: h2, y: y2, data: x2, reset: w2 } = await p2({ x: f2, y: u2, initialPlacement: r2, placement: m2, strategy: o2, middlewareData: g2, rects: c2, platform: a2, elements: { reference: t2, floating: e2 } });
    f2 = h2 != null ? h2 : f2, u2 = y2 != null ? y2 : u2, g2 = __spreadProps(__spreadValues({}, g2), { [d2]: __spreadValues(__spreadValues({}, g2[d2]), x2) }), w2 && (typeof w2 == "object" && (w2.placement && (m2 = w2.placement), w2.rects && (c2 = w2.rects === true ? await a2.getElementRects({ reference: t2, floating: e2, strategy: o2 }) : w2.rects), { x: f2, y: u2 } = i$2(c2, m2, s2)), n3 = -1);
  }
  return { x: f2, y: u2, placement: m2, strategy: o2, middlewareData: g2 };
};
function l$1(t2) {
  return typeof t2 != "number" ? function(t3) {
    return __spreadValues({ top: 0, right: 0, bottom: 0, left: 0 }, t3);
  }(t2) : { top: t2, right: t2, bottom: t2, left: t2 };
}
function a$1(t2) {
  return __spreadProps(__spreadValues({}, t2), { top: t2.y, left: t2.x, right: t2.x + t2.width, bottom: t2.y + t2.height });
}
async function s$2(t2, e2) {
  var n2;
  e2 === void 0 && (e2 = {});
  const { x: r2, y: i2, platform: o2, rects: s2, elements: c2, strategy: f2 } = t2, { boundary: u2 = "clippingAncestors", rootBoundary: m2 = "viewport", elementContext: g2 = "floating", altBoundary: d2 = false, padding: p2 = 0 } = e2, h2 = l$1(p2), y2 = c2[d2 ? g2 === "floating" ? "reference" : "floating" : g2], x2 = a$1(await o2.getClippingRect({ element: (n2 = await (o2.isElement == null ? void 0 : o2.isElement(y2))) == null || n2 ? y2 : y2.contextElement || await (o2.getDocumentElement == null ? void 0 : o2.getDocumentElement(c2.floating)), boundary: u2, rootBoundary: m2 })), w2 = a$1(o2.convertOffsetParentRelativeRectToViewportRelativeRect ? await o2.convertOffsetParentRelativeRectToViewportRelativeRect({ rect: g2 === "floating" ? __spreadProps(__spreadValues({}, s2.floating), { x: r2, y: i2 }) : s2.reference, offsetParent: await (o2.getOffsetParent == null ? void 0 : o2.getOffsetParent(c2.floating)), strategy: f2 }) : s2[g2]);
  return { top: x2.top - w2.top + h2.top, bottom: w2.bottom - x2.bottom + h2.bottom, left: x2.left - w2.left + h2.left, right: w2.right - x2.right + h2.right };
}
const c$2 = Math.min, f$2 = Math.max;
function u$2(t2, e2, n2) {
  return f$2(t2, c$2(e2, n2));
}
const g$2 = { left: "right", right: "left", bottom: "top", top: "bottom" };
function d$2(t2) {
  return t2.replace(/left|right|bottom|top/g, (t3) => g$2[t3]);
}
function p$2(t2, i2, o2) {
  o2 === void 0 && (o2 = false);
  const l2 = e(t2), a2 = n$1(t2), s2 = r$1(a2);
  let c2 = a2 === "x" ? l2 === (o2 ? "end" : "start") ? "right" : "left" : l2 === "start" ? "bottom" : "top";
  return i2.reference[s2] > i2.floating[s2] && (c2 = d$2(c2)), { main: c2, cross: d$2(c2) };
}
const h$2 = { start: "end", end: "start" };
function y$1(t2) {
  return t2.replace(/start|end/g, (t3) => h$2[t3]);
}
const x$2 = ["top", "right", "bottom", "left"];
x$2.reduce((t2, e2) => t2.concat(e2, e2 + "-start", e2 + "-end"), []);
const b$2 = function(e2) {
  return e2 === void 0 && (e2 = {}), { name: "flip", options: e2, async fn(n2) {
    var r2;
    const { placement: i2, middlewareData: o2, rects: l2, initialPlacement: a2, platform: c2, elements: f2 } = n2, _a2 = e2, { mainAxis: u2 = true, crossAxis: m2 = true, fallbackPlacements: g2, fallbackStrategy: h2 = "bestFit", flipAlignment: x2 = true } = _a2, w2 = __objRest(_a2, ["mainAxis", "crossAxis", "fallbackPlacements", "fallbackStrategy", "flipAlignment"]), v2 = t(i2), b2 = g2 || (v2 === a2 || !x2 ? [d$2(a2)] : function(t2) {
      const e3 = d$2(t2);
      return [y$1(t2), e3, y$1(e3)];
    }(a2)), R2 = [a2, ...b2], A2 = await s$2(n2, w2), P2 = [];
    let T2 = ((r2 = o2.flip) == null ? void 0 : r2.overflows) || [];
    if (u2 && P2.push(A2[v2]), m2) {
      const { main: t2, cross: e3 } = p$2(i2, l2, await (c2.isRTL == null ? void 0 : c2.isRTL(f2.floating)));
      P2.push(A2[t2], A2[e3]);
    }
    if (T2 = [...T2, { placement: i2, overflows: P2 }], !P2.every((t2) => t2 <= 0)) {
      var O2, D2;
      const t2 = ((O2 = (D2 = o2.flip) == null ? void 0 : D2.index) != null ? O2 : 0) + 1, e3 = R2[t2];
      if (e3)
        return { data: { index: t2, overflows: T2 }, reset: { placement: e3 } };
      let n3 = "bottom";
      switch (h2) {
        case "bestFit": {
          var L2;
          const t3 = (L2 = T2.slice().sort((t4, e4) => t4.overflows.filter((t5) => t5 > 0).reduce((t5, e5) => t5 + e5, 0) - e4.overflows.filter((t5) => t5 > 0).reduce((t5, e5) => t5 + e5, 0))[0]) == null ? void 0 : L2.placement;
          t3 && (n3 = t3);
          break;
        }
        case "initialPlacement":
          n3 = a2;
      }
      if (i2 !== n3)
        return { reset: { placement: n3 } };
    }
    return {};
  } };
};
const T$2 = function(r2) {
  return r2 === void 0 && (r2 = 0), { name: "offset", options: r2, async fn(i2) {
    const { x: o2, y: l2, placement: a2, rects: s2, platform: c2, elements: f2 } = i2, u2 = function(r3, i3, o3, l3) {
      l3 === void 0 && (l3 = false);
      const a3 = t(r3), s3 = e(r3), c3 = n$1(r3) === "x", f3 = ["left", "top"].includes(a3) ? -1 : 1, u3 = l3 && c3 ? -1 : 1, m2 = typeof o3 == "function" ? o3(__spreadProps(__spreadValues({}, i3), { placement: r3 })) : o3, g2 = typeof m2 == "number";
      let { mainAxis: d2, crossAxis: p2, alignmentAxis: h2 } = g2 ? { mainAxis: m2, crossAxis: 0, alignmentAxis: null } : __spreadValues({ mainAxis: 0, crossAxis: 0, alignmentAxis: null }, m2);
      return s3 && typeof h2 == "number" && (p2 = s3 === "end" ? -1 * h2 : h2), c3 ? { x: p2 * u3, y: d2 * f3 } : { x: d2 * f3, y: p2 * u3 };
    }(a2, s2, r2, await (c2.isRTL == null ? void 0 : c2.isRTL(f2.floating)));
    return { x: o2 + u2.x, y: l2 + u2.y, data: u2 };
  } };
};
function O(t2) {
  return t2 === "x" ? "y" : "x";
}
const D$1 = function(e2) {
  return e2 === void 0 && (e2 = {}), { name: "shift", options: e2, async fn(r2) {
    const { x: i2, y: o2, placement: l2 } = r2, _a2 = e2, { mainAxis: a2 = true, crossAxis: c2 = false, limiter: f2 = { fn: (t2) => {
      let { x: e3, y: n2 } = t2;
      return { x: e3, y: n2 };
    } } } = _a2, m2 = __objRest(_a2, ["mainAxis", "crossAxis", "limiter"]), g2 = { x: i2, y: o2 }, d2 = await s$2(r2, m2), p2 = n$1(t(l2)), h2 = O(p2);
    let y2 = g2[p2], x2 = g2[h2];
    if (a2) {
      const t2 = p2 === "y" ? "bottom" : "right";
      y2 = u$2(y2 + d2[p2 === "y" ? "top" : "left"], y2, y2 - d2[t2]);
    }
    if (c2) {
      const t2 = h2 === "y" ? "bottom" : "right";
      x2 = u$2(x2 + d2[h2 === "y" ? "top" : "left"], x2, x2 - d2[t2]);
    }
    const w2 = f2.fn(__spreadProps(__spreadValues({}, r2), { [p2]: y2, [h2]: x2 }));
    return __spreadProps(__spreadValues({}, w2), { data: { x: w2.x - i2, y: w2.y - o2 } });
  } };
};
function n(t2) {
  return (t2 == null ? void 0 : t2.toString()) === "[object Window]";
}
function o(t2) {
  if (t2 == null)
    return window;
  if (!n(t2)) {
    const e2 = t2.ownerDocument;
    return e2 && e2.defaultView || window;
  }
  return t2;
}
function i$1(t2) {
  return o(t2).getComputedStyle(t2);
}
function r(t2) {
  return n(t2) ? "" : t2 ? (t2.nodeName || "").toLowerCase() : "";
}
function l(t2) {
  return t2 instanceof o(t2).HTMLElement;
}
function c$1(t2) {
  return t2 instanceof o(t2).Element;
}
function f$1(t2) {
  return t2 instanceof o(t2).ShadowRoot || t2 instanceof ShadowRoot;
}
function s$1(t2) {
  const { overflow: e2, overflowX: n2, overflowY: o2 } = i$1(t2);
  return /auto|scroll|overlay|hidden/.test(e2 + o2 + n2);
}
function u$1(t2) {
  return ["table", "td", "th"].includes(r(t2));
}
function h$1(t2) {
  const e2 = navigator.userAgent.toLowerCase().includes("firefox"), n2 = i$1(t2);
  return n2.transform !== "none" || n2.perspective !== "none" || n2.contain === "paint" || ["transform", "perspective"].includes(n2.willChange) || e2 && n2.willChange === "filter" || e2 && !!n2.filter && n2.filter !== "none";
}
const d$1 = Math.min, a = Math.max, g$1 = Math.round;
function p$1(t2, e2) {
  e2 === void 0 && (e2 = false);
  const n2 = t2.getBoundingClientRect();
  let o2 = 1, i2 = 1;
  return e2 && l(t2) && (o2 = t2.offsetWidth > 0 && g$1(n2.width) / t2.offsetWidth || 1, i2 = t2.offsetHeight > 0 && g$1(n2.height) / t2.offsetHeight || 1), { width: n2.width / o2, height: n2.height / i2, top: n2.top / i2, right: n2.right / o2, bottom: n2.bottom / i2, left: n2.left / o2, x: n2.left / o2, y: n2.top / i2 };
}
function m$1(t2) {
  return (e2 = t2, (e2 instanceof o(e2).Node ? t2.ownerDocument : t2.document) || window.document).documentElement;
  var e2;
}
function w$1(t2) {
  return n(t2) ? { scrollLeft: t2.pageXOffset, scrollTop: t2.pageYOffset } : { scrollLeft: t2.scrollLeft, scrollTop: t2.scrollTop };
}
function y(t2) {
  return p$1(m$1(t2)).left + w$1(t2).scrollLeft;
}
function v$1(t2, e2, n2) {
  const o2 = l(e2), i2 = m$1(e2), c2 = p$1(t2, o2 && function(t3) {
    const e3 = p$1(t3);
    return g$1(e3.width) !== t3.offsetWidth || g$1(e3.height) !== t3.offsetHeight;
  }(e2));
  let f2 = { scrollLeft: 0, scrollTop: 0 };
  const u2 = { x: 0, y: 0 };
  if (o2 || !o2 && n2 !== "fixed")
    if ((r(e2) !== "body" || s$1(i2)) && (f2 = w$1(e2)), l(e2)) {
      const t3 = p$1(e2, true);
      u2.x = t3.x + e2.clientLeft, u2.y = t3.y + e2.clientTop;
    } else
      i2 && (u2.x = y(i2));
  return { x: c2.left + f2.scrollLeft - u2.x, y: c2.top + f2.scrollTop - u2.y, width: c2.width, height: c2.height };
}
function x$1(t2) {
  return r(t2) === "html" ? t2 : t2.assignedSlot || t2.parentNode || (f$1(t2) ? t2.host : null) || m$1(t2);
}
function b$1(t2) {
  return l(t2) && getComputedStyle(t2).position !== "fixed" ? t2.offsetParent : null;
}
function L$1(t2) {
  const e2 = o(t2);
  let n2 = b$1(t2);
  for (; n2 && u$1(n2) && getComputedStyle(n2).position === "static"; )
    n2 = b$1(n2);
  return n2 && (r(n2) === "html" || r(n2) === "body" && getComputedStyle(n2).position === "static" && !h$1(n2)) ? e2 : n2 || function(t3) {
    let e3 = x$1(t3);
    for (f$1(e3) && (e3 = e3.host); l(e3) && !["html", "body"].includes(r(e3)); ) {
      if (h$1(e3))
        return e3;
      e3 = e3.parentNode;
    }
    return null;
  }(t2) || e2;
}
function R$1(t2) {
  if (l(t2))
    return { width: t2.offsetWidth, height: t2.offsetHeight };
  const e2 = p$1(t2);
  return { width: e2.width, height: e2.height };
}
function T$1(t2) {
  const e2 = x$1(t2);
  return ["html", "body", "#document"].includes(r(e2)) ? t2.ownerDocument.body : l(e2) && s$1(e2) ? e2 : T$1(e2);
}
function W(t2, e2) {
  var n2;
  e2 === void 0 && (e2 = []);
  const i2 = T$1(t2), r2 = i2 === ((n2 = t2.ownerDocument) == null ? void 0 : n2.body), l2 = o(i2), c2 = r2 ? [l2].concat(l2.visualViewport || [], s$1(i2) ? i2 : []) : i2, f2 = e2.concat(c2);
  return r2 ? f2 : f2.concat(W(x$1(c2)));
}
function C(e2, n2) {
  return n2 === "viewport" ? a$1(function(t2) {
    const e3 = o(t2), n3 = m$1(t2), i2 = e3.visualViewport;
    let r2 = n3.clientWidth, l2 = n3.clientHeight, c2 = 0, f2 = 0;
    return i2 && (r2 = i2.width, l2 = i2.height, Math.abs(e3.innerWidth / i2.scale - i2.width) < 0.01 && (c2 = i2.offsetLeft, f2 = i2.offsetTop)), { width: r2, height: l2, x: c2, y: f2 };
  }(e2)) : c$1(n2) ? function(t2) {
    const e3 = p$1(t2), n3 = e3.top + t2.clientTop, o2 = e3.left + t2.clientLeft;
    return { top: n3, left: o2, x: o2, y: n3, right: o2 + t2.clientWidth, bottom: n3 + t2.clientHeight, width: t2.clientWidth, height: t2.clientHeight };
  }(n2) : a$1(function(t2) {
    var e3;
    const n3 = m$1(t2), o2 = w$1(t2), r2 = (e3 = t2.ownerDocument) == null ? void 0 : e3.body, l2 = a(n3.scrollWidth, n3.clientWidth, r2 ? r2.scrollWidth : 0, r2 ? r2.clientWidth : 0), c2 = a(n3.scrollHeight, n3.clientHeight, r2 ? r2.scrollHeight : 0, r2 ? r2.clientHeight : 0);
    let f2 = -o2.scrollLeft + y(t2);
    const s2 = -o2.scrollTop;
    return i$1(r2 || n3).direction === "rtl" && (f2 += a(n3.clientWidth, r2 ? r2.clientWidth : 0) - l2), { width: l2, height: c2, x: f2, y: s2 };
  }(m$1(e2)));
}
function E(t2) {
  const e2 = W(t2), n2 = ["absolute", "fixed"].includes(i$1(t2).position) && l(t2) ? L$1(t2) : t2;
  return c$1(n2) ? e2.filter((t3) => c$1(t3) && function(t4, e3) {
    const n3 = e3.getRootNode == null ? void 0 : e3.getRootNode();
    if (t4.contains(e3))
      return true;
    if (n3 && f$1(n3)) {
      let n4 = e3;
      do {
        if (n4 && t4 === n4)
          return true;
        n4 = n4.parentNode || n4.host;
      } while (n4);
    }
    return false;
  }(t3, n2) && r(t3) !== "body") : [];
}
const H = { getClippingRect: function(t2) {
  let { element: e2, boundary: n2, rootBoundary: o2 } = t2;
  const i2 = [...n2 === "clippingAncestors" ? E(e2) : [].concat(n2), o2], r2 = i2[0], l2 = i2.reduce((t3, n3) => {
    const o3 = C(e2, n3);
    return t3.top = a(o3.top, t3.top), t3.right = d$1(o3.right, t3.right), t3.bottom = d$1(o3.bottom, t3.bottom), t3.left = a(o3.left, t3.left), t3;
  }, C(e2, r2));
  return { width: l2.right - l2.left, height: l2.bottom - l2.top, x: l2.left, y: l2.top };
}, convertOffsetParentRelativeRectToViewportRelativeRect: function(t2) {
  let { rect: e2, offsetParent: n2, strategy: o2 } = t2;
  const i2 = l(n2), c2 = m$1(n2);
  if (n2 === c2)
    return e2;
  let f2 = { scrollLeft: 0, scrollTop: 0 };
  const u2 = { x: 0, y: 0 };
  if ((i2 || !i2 && o2 !== "fixed") && ((r(n2) !== "body" || s$1(c2)) && (f2 = w$1(n2)), l(n2))) {
    const t3 = p$1(n2, true);
    u2.x = t3.x + n2.clientLeft, u2.y = t3.y + n2.clientTop;
  }
  return __spreadProps(__spreadValues({}, e2), { x: e2.x - f2.scrollLeft + u2.x, y: e2.y - f2.scrollTop + u2.y });
}, isElement: c$1, getDimensions: R$1, getOffsetParent: L$1, getDocumentElement: m$1, getElementRects: (t2) => {
  let { reference: e2, floating: n2, strategy: o2 } = t2;
  return { reference: v$1(e2, L$1(n2), o2), floating: __spreadProps(__spreadValues({}, R$1(n2)), { x: 0, y: 0 }) };
}, getClientRects: (t2) => Array.from(t2.getClientRects()), isRTL: (t2) => i$1(t2).direction === "rtl" };
const D = (t2, n2, o2) => o$1(t2, n2, __spreadValues({ platform: H }, o2));
var index = typeof document !== "undefined" ? useLayoutEffect : useEffect;
function deepEqual(a2, b2) {
  if (a2 === b2) {
    return true;
  }
  if (typeof a2 !== typeof b2) {
    return false;
  }
  if (typeof a2 === "function" && a2.toString() === b2.toString()) {
    return true;
  }
  let length, i2, keys;
  if (a2 && b2 && typeof a2 == "object") {
    if (Array.isArray(a2)) {
      length = a2.length;
      if (length != b2.length)
        return false;
      for (i2 = length; i2-- !== 0; ) {
        if (!deepEqual(a2[i2], b2[i2])) {
          return false;
        }
      }
      return true;
    }
    keys = Object.keys(a2);
    length = keys.length;
    if (length !== Object.keys(b2).length) {
      return false;
    }
    for (i2 = length; i2-- !== 0; ) {
      if (!Object.prototype.hasOwnProperty.call(b2, keys[i2])) {
        return false;
      }
    }
    for (i2 = length; i2-- !== 0; ) {
      const key = keys[i2];
      if (key === "_owner" && a2.$$typeof) {
        continue;
      }
      if (!deepEqual(a2[key], b2[key])) {
        return false;
      }
    }
    return true;
  }
  return a2 !== a2 && b2 !== b2;
}
function useFloating(_temp) {
  let {
    middleware,
    placement = "bottom",
    strategy = "absolute"
  } = _temp === void 0 ? {} : _temp;
  const reference = useRef(null);
  const floating = useRef(null);
  const [data, setData] = useState({
    x: null,
    y: null,
    strategy,
    placement,
    middlewareData: {}
  });
  const [latestMiddleware, setLatestMiddleware] = useState(middleware);
  if (!deepEqual(latestMiddleware == null ? void 0 : latestMiddleware.map((_ref) => {
    let {
      options
    } = _ref;
    return options;
  }), middleware == null ? void 0 : middleware.map((_ref2) => {
    let {
      options
    } = _ref2;
    return options;
  }))) {
    setLatestMiddleware(middleware);
  }
  const isMountedRef = useRef(true);
  index(() => {
    isMountedRef.current = true;
    return () => {
      isMountedRef.current = false;
    };
  }, []);
  const update = useCallback(() => {
    if (!reference.current || !floating.current) {
      return;
    }
    D(reference.current, floating.current, {
      middleware: latestMiddleware,
      placement,
      strategy
    }).then((data2) => {
      if (isMountedRef.current) {
        setData(data2);
      }
    });
  }, [latestMiddleware, placement, strategy]);
  index(update, [update]);
  const setReference = useCallback((node) => {
    reference.current = node;
    update();
  }, [update]);
  const setFloating = useCallback((node) => {
    floating.current = node;
    update();
  }, [update]);
  const refs = useMemo(() => ({
    reference,
    floating
  }), []);
  return useMemo(() => __spreadProps(__spreadValues({}, data), {
    update,
    refs,
    reference: setReference,
    floating: setFloating
  }), [data, update, refs, setReference, setFloating]);
}
function useOverlayPosition({
  shouldFlip = true,
  offset: offset2 = 5,
  containerPadding = 16
}) {
  const {
    x: x2,
    y: y2,
    reference,
    floating,
    strategy,
    refs
  } = useFloating({
    placement: "bottom",
    middleware: [T$2(offset2), b$2({
      padding: containerPadding,
      crossAxis: shouldFlip,
      mainAxis: shouldFlip
    }), D$1({
      padding: containerPadding
    })]
  });
  return {
    triggerRef: reference,
    triggerObjRef: refs.reference,
    overlayRef: floating,
    overlayObjRef: refs.floating,
    objRefs: refs,
    positionStyle: {
      position: strategy,
      top: y2 != null ? y2 : "",
      left: x2 != null ? x2 : ""
    }
  };
}
function MenuTrigger(props2) {
  const {
    children,
    closeOnSelect,
    shouldFlip = true
  } = props2;
  const [menuTrigger, menu] = React__default.Children.toArray(children);
  const state2 = $89a94a12744b972a$export$79fefeb1c2091ac3(props2);
  const {
    triggerRef,
    overlayRef,
    positionStyle,
    triggerObjRef
  } = useOverlayPosition({
    shouldFlip
  });
  const {
    menuTriggerProps,
    menuProps
  } = $235cea8b956832d5$export$dc9c12ed27dd1b49({}, state2, triggerObjRef);
  const isMobile = useIsMobileDevice();
  const menuContext = __spreadProps(__spreadValues({}, menuProps), {
    onClose: state2.close,
    closeOnSelect,
    autoFocus: state2.focusStrategy || true
  });
  const contents = /* @__PURE__ */ jsxs($14e5c84cbc2e6e2e$export$20e40289641fbbb6, {
    restoreFocus: true,
    contain: isMobile,
    children: [/* @__PURE__ */ jsx($86ea4cb521eb2e37$export$2317d149ed6f78c4, {
      onDismiss: state2.close
    }), menu, /* @__PURE__ */ jsx($86ea4cb521eb2e37$export$2317d149ed6f78c4, {
      onDismiss: state2.close
    })]
  });
  let overlay;
  if (isMobile) {
    overlay = /* @__PURE__ */ jsx(Tray, {
      isOpen: state2.isOpen,
      onClose: state2.close,
      children: contents
    });
  } else {
    overlay = /* @__PURE__ */ jsx(Popover, {
      isOpen: state2.isOpen,
      style: positionStyle,
      ref: overlayRef,
      hideArrow: true,
      onClose: state2.close,
      shouldCloseOnBlur: true,
      children: contents
    });
  }
  return /* @__PURE__ */ jsxs(Fragment, {
    children: [menuTrigger && React__default.cloneElement(menuTrigger, __spreadProps(__spreadValues({}, menuTriggerProps), {
      ref: triggerRef,
      isPressed: state2.isOpen
    })), /* @__PURE__ */ jsx(AnimatePresence, {
      children: state2.isOpen && /* @__PURE__ */ jsx(MenuContext.Provider, {
        value: menuContext,
        children: overlay
      })
    })]
  });
}
function $parcel$export$l(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $ec35bdc00c823be9$exports = {};
$parcel$export$l($ec35bdc00c823be9$exports, "useMultipleSelectionState", () => $ec35bdc00c823be9$export$253fe78d46329472);
class $84eb7a4250035b1f$export$52baac22726c72bf extends Set {
  constructor(keys, anchorKey, currentKey) {
    super(keys);
    if (keys instanceof $84eb7a4250035b1f$export$52baac22726c72bf) {
      this.anchorKey = anchorKey || keys.anchorKey;
      this.currentKey = currentKey || keys.currentKey;
    } else {
      this.anchorKey = anchorKey;
      this.currentKey = currentKey;
    }
  }
}
function $ec35bdc00c823be9$var$equalSets(setA, setB) {
  if (setA.size !== setB.size)
    return false;
  for (let item of setA) {
    if (!setB.has(item))
      return false;
  }
  return true;
}
function $ec35bdc00c823be9$export$253fe78d46329472(props2) {
  let { selectionMode = "none", disallowEmptySelection, allowDuplicateSelectionEvents } = props2;
  let isFocusedRef = useRef(false);
  let [, setFocused] = useState(false);
  let focusedKeyRef = useRef(null);
  let childFocusStrategyRef = useRef(null);
  let [, setFocusedKey] = useState(null);
  let selectedKeysProp = useMemo(() => $ec35bdc00c823be9$var$convertSelection(props2.selectedKeys), [
    props2.selectedKeys
  ]);
  let defaultSelectedKeys = useMemo(() => $ec35bdc00c823be9$var$convertSelection(props2.defaultSelectedKeys, new $84eb7a4250035b1f$export$52baac22726c72bf()), [
    props2.defaultSelectedKeys
  ]);
  let [selectedKeys, setSelectedKeys] = $bfee1151ccb0650f$export$40bfa8c7b0832715(selectedKeysProp, defaultSelectedKeys, props2.onSelectionChange);
  let disabledKeysProp = useMemo(() => props2.disabledKeys ? new Set(props2.disabledKeys) : /* @__PURE__ */ new Set(), [
    props2.disabledKeys
  ]);
  let [selectionBehavior, setSelectionBehavior] = useState(props2.selectionBehavior || "toggle");
  if (props2.selectionBehavior === "replace" && selectionBehavior === "toggle" && typeof selectedKeys === "object" && selectedKeys.size === 0)
    setSelectionBehavior("replace");
  return {
    selectionMode,
    disallowEmptySelection,
    selectionBehavior,
    setSelectionBehavior,
    get isFocused() {
      return isFocusedRef.current;
    },
    setFocused(f2) {
      isFocusedRef.current = f2;
      setFocused(f2);
    },
    get focusedKey() {
      return focusedKeyRef.current;
    },
    get childFocusStrategy() {
      return childFocusStrategyRef.current;
    },
    setFocusedKey(k2, childFocusStrategy = "first") {
      focusedKeyRef.current = k2;
      childFocusStrategyRef.current = childFocusStrategy;
      setFocusedKey(k2);
    },
    selectedKeys,
    setSelectedKeys(keys) {
      if (allowDuplicateSelectionEvents || !$ec35bdc00c823be9$var$equalSets(keys, selectedKeys))
        setSelectedKeys(keys);
    },
    disabledKeys: disabledKeysProp
  };
}
function $ec35bdc00c823be9$var$convertSelection(selection, defaultValue) {
  if (!selection)
    return defaultValue;
  return selection === "all" ? "all" : new $84eb7a4250035b1f$export$52baac22726c72bf(selection);
}
var $1c74ece56c82b9c4$exports = {};
$parcel$export$l($1c74ece56c82b9c4$exports, "SelectionManager", () => $1c74ece56c82b9c4$export$6c8a5aaad13c9852);
class $1c74ece56c82b9c4$export$6c8a5aaad13c9852 {
  get selectionMode() {
    return this.state.selectionMode;
  }
  get disallowEmptySelection() {
    return this.state.disallowEmptySelection;
  }
  get selectionBehavior() {
    return this.state.selectionBehavior;
  }
  setSelectionBehavior(selectionBehavior) {
    this.state.setSelectionBehavior(selectionBehavior);
  }
  get isFocused() {
    return this.state.isFocused;
  }
  setFocused(isFocused) {
    this.state.setFocused(isFocused);
  }
  get focusedKey() {
    return this.state.focusedKey;
  }
  get childFocusStrategy() {
    return this.state.childFocusStrategy;
  }
  setFocusedKey(key, childFocusStrategy) {
    this.state.setFocusedKey(key, childFocusStrategy);
  }
  get selectedKeys() {
    return this.state.selectedKeys === "all" ? new Set(this.getSelectAllKeys()) : this.state.selectedKeys;
  }
  get rawSelection() {
    return this.state.selectedKeys;
  }
  isSelected(key) {
    if (this.state.selectionMode === "none")
      return false;
    key = this.getKey(key);
    return this.state.selectedKeys === "all" ? !this.state.disabledKeys.has(key) : this.state.selectedKeys.has(key);
  }
  get isEmpty() {
    return this.state.selectedKeys !== "all" && this.state.selectedKeys.size === 0;
  }
  get isSelectAll() {
    if (this.isEmpty)
      return false;
    if (this.state.selectedKeys === "all")
      return true;
    if (this._isSelectAll != null)
      return this._isSelectAll;
    let allKeys = this.getSelectAllKeys();
    let selectedKeys = this.state.selectedKeys;
    this._isSelectAll = allKeys.every((k2) => selectedKeys.has(k2));
    return this._isSelectAll;
  }
  get firstSelectedKey() {
    let first = null;
    for (let key of this.state.selectedKeys) {
      let item = this.collection.getItem(key);
      if (!first || (item === null || item === void 0 ? void 0 : item.index) < first.index)
        first = item;
    }
    return first === null || first === void 0 ? void 0 : first.key;
  }
  get lastSelectedKey() {
    let last = null;
    for (let key of this.state.selectedKeys) {
      let item = this.collection.getItem(key);
      if (!last || (item === null || item === void 0 ? void 0 : item.index) > last.index)
        last = item;
    }
    return last === null || last === void 0 ? void 0 : last.key;
  }
  extendSelection(toKey) {
    if (this.selectionMode === "none")
      return;
    if (this.selectionMode === "single") {
      this.replaceSelection(toKey);
      return;
    }
    toKey = this.getKey(toKey);
    let selection;
    if (this.state.selectedKeys === "all")
      selection = new $84eb7a4250035b1f$export$52baac22726c72bf([
        toKey
      ], toKey, toKey);
    else {
      let selectedKeys = this.state.selectedKeys;
      let anchorKey = selectedKeys.anchorKey || toKey;
      selection = new $84eb7a4250035b1f$export$52baac22726c72bf(selectedKeys, anchorKey, toKey);
      for (let key of this.getKeyRange(anchorKey, selectedKeys.currentKey || toKey))
        selection.delete(key);
      for (let key1 of this.getKeyRange(toKey, anchorKey))
        if (!this.state.disabledKeys.has(key1))
          selection.add(key1);
    }
    this.state.setSelectedKeys(selection);
  }
  getKeyRange(from, to) {
    let fromItem = this.collection.getItem(from);
    let toItem = this.collection.getItem(to);
    if (fromItem && toItem) {
      if (fromItem.index <= toItem.index)
        return this.getKeyRangeInternal(from, to);
      return this.getKeyRangeInternal(to, from);
    }
    return [];
  }
  getKeyRangeInternal(from, to) {
    let keys = [];
    let key = from;
    while (key) {
      let item = this.collection.getItem(key);
      if (item && item.type === "item" || item.type === "cell" && this.allowsCellSelection)
        keys.push(key);
      if (key === to)
        return keys;
      key = this.collection.getKeyAfter(key);
    }
    return [];
  }
  getKey(key) {
    let item = this.collection.getItem(key);
    if (!item)
      return key;
    if (item.type === "cell" && this.allowsCellSelection)
      return key;
    while (item.type !== "item" && item.parentKey != null)
      item = this.collection.getItem(item.parentKey);
    if (!item || item.type !== "item")
      return null;
    return item.key;
  }
  toggleSelection(key) {
    if (this.selectionMode === "none")
      return;
    if (this.selectionMode === "single" && !this.isSelected(key)) {
      this.replaceSelection(key);
      return;
    }
    key = this.getKey(key);
    if (key == null)
      return;
    let keys = new $84eb7a4250035b1f$export$52baac22726c72bf(this.state.selectedKeys === "all" ? this.getSelectAllKeys() : this.state.selectedKeys);
    if (keys.has(key))
      keys.delete(key);
    else {
      keys.add(key);
      keys.anchorKey = key;
      keys.currentKey = key;
    }
    if (this.disallowEmptySelection && keys.size === 0)
      return;
    this.state.setSelectedKeys(keys);
  }
  replaceSelection(key) {
    if (this.selectionMode === "none")
      return;
    key = this.getKey(key);
    if (key == null)
      return;
    this.state.setSelectedKeys(new $84eb7a4250035b1f$export$52baac22726c72bf([
      key
    ], key, key));
  }
  setSelectedKeys(keys) {
    if (this.selectionMode === "none")
      return;
    let selection = new $84eb7a4250035b1f$export$52baac22726c72bf();
    for (let key of keys) {
      key = this.getKey(key);
      if (key != null) {
        selection.add(key);
        if (this.selectionMode === "single")
          break;
      }
    }
    this.state.setSelectedKeys(selection);
  }
  getSelectAllKeys() {
    let keys = [];
    let addKeys = (key) => {
      while (key) {
        if (!this.state.disabledKeys.has(key)) {
          let item = this.collection.getItem(key);
          if (item.type === "item")
            keys.push(key);
          if (item.hasChildNodes && (this.allowsCellSelection || item.type !== "item"))
            addKeys([
              ...item.childNodes
            ][0].key);
        }
        key = this.collection.getKeyAfter(key);
      }
    };
    addKeys(this.collection.getFirstKey());
    return keys;
  }
  selectAll() {
    if (this.selectionMode === "multiple")
      this.state.setSelectedKeys("all");
  }
  clearSelection() {
    if (!this.disallowEmptySelection && (this.state.selectedKeys === "all" || this.state.selectedKeys.size > 0))
      this.state.setSelectedKeys(new $84eb7a4250035b1f$export$52baac22726c72bf());
  }
  toggleSelectAll() {
    if (this.isSelectAll)
      this.clearSelection();
    else
      this.selectAll();
  }
  select(key, e2) {
    if (this.selectionMode === "none")
      return;
    if (this.selectionMode === "single") {
      if (this.isSelected(key) && !this.disallowEmptySelection)
        this.toggleSelection(key);
      else
        this.replaceSelection(key);
    } else if (this.selectionBehavior === "toggle" || e2 && (e2.pointerType === "touch" || e2.pointerType === "virtual"))
      this.toggleSelection(key);
    else
      this.replaceSelection(key);
  }
  isSelectionEqual(selection) {
    if (selection === this.state.selectedKeys)
      return true;
    let selectedKeys = this.selectedKeys;
    if (selection.size !== selectedKeys.size)
      return false;
    for (let key of selection) {
      if (!selectedKeys.has(key))
        return false;
    }
    for (let key2 of selectedKeys) {
      if (!selection.has(key2))
        return false;
    }
    return true;
  }
  canSelectItem(key) {
    if (this.state.selectionMode === "none" || this.state.disabledKeys.has(key))
      return false;
    let item = this.collection.getItem(key);
    if (!item || item.type === "cell" && !this.allowsCellSelection)
      return false;
    return true;
  }
  constructor(collection, state2, options) {
    this.collection = collection;
    this.state = state2;
    var ref;
    this.allowsCellSelection = (ref = options === null || options === void 0 ? void 0 : options.allowsCellSelection) !== null && ref !== void 0 ? ref : false;
    this._isSelectAll = null;
  }
}
function $parcel$export$k(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $36d99f0640511db5$exports = {};
$parcel$export$k($36d99f0640511db5$exports, "useTreeState", () => $36d99f0640511db5$export$728d6ba534403756);
var tmp$1 = Symbol.iterator;
class $c8161626733397a0$export$863faf230ee2118a {
  *[tmp$1]() {
    yield* this.iterable;
  }
  get size() {
    return this.keyMap.size;
  }
  getKeys() {
    return this.keyMap.keys();
  }
  getKeyBefore(key) {
    let node = this.keyMap.get(key);
    return node ? node.prevKey : null;
  }
  getKeyAfter(key) {
    let node = this.keyMap.get(key);
    return node ? node.nextKey : null;
  }
  getFirstKey() {
    return this.firstKey;
  }
  getLastKey() {
    return this.lastKey;
  }
  getItem(key) {
    return this.keyMap.get(key);
  }
  at(idx) {
    const keys = [
      ...this.getKeys()
    ];
    return this.getItem(keys[idx]);
  }
  constructor(nodes, { expandedKeys } = {}) {
    this.keyMap = /* @__PURE__ */ new Map();
    this.iterable = nodes;
    expandedKeys = expandedKeys || /* @__PURE__ */ new Set();
    let visit = (node) => {
      this.keyMap.set(node.key, node);
      if (node.childNodes && (node.type === "section" || expandedKeys.has(node.key)))
        for (let child of node.childNodes)
          visit(child);
    };
    for (let node2 of nodes)
      visit(node2);
    let last;
    let index2 = 0;
    for (let [key, node1] of this.keyMap) {
      if (last) {
        last.nextKey = key;
        node1.prevKey = last.key;
      } else {
        this.firstKey = key;
        node1.prevKey = void 0;
      }
      if (node1.type === "item")
        node1.index = index2++;
      last = node1;
      last.nextKey = void 0;
    }
    this.lastKey = last === null || last === void 0 ? void 0 : last.key;
  }
}
function $36d99f0640511db5$export$728d6ba534403756(props2) {
  let [expandedKeys, setExpandedKeys] = $bfee1151ccb0650f$export$40bfa8c7b0832715(props2.expandedKeys ? new Set(props2.expandedKeys) : void 0, props2.defaultExpandedKeys ? new Set(props2.defaultExpandedKeys) : /* @__PURE__ */ new Set(), props2.onExpandedChange);
  let selectionState = $ec35bdc00c823be9$export$253fe78d46329472(props2);
  let disabledKeys = useMemo(() => props2.disabledKeys ? new Set(props2.disabledKeys) : /* @__PURE__ */ new Set(), [
    props2.disabledKeys
  ]);
  let tree = $54e9526d7573190f$export$6cd28814d92fa9c9(props2, (nodes) => new $c8161626733397a0$export$863faf230ee2118a(nodes, {
    expandedKeys
  }), null, [
    expandedKeys
  ]);
  useEffect(() => {
    if (selectionState.focusedKey != null && !tree.getItem(selectionState.focusedKey))
      selectionState.setFocusedKey(null);
  }, [
    tree,
    selectionState.focusedKey
  ]);
  let onToggle = (key) => {
    setExpandedKeys($36d99f0640511db5$var$toggleKey(expandedKeys, key));
  };
  return {
    collection: tree,
    expandedKeys,
    disabledKeys,
    toggleKey: onToggle,
    selectionManager: new $1c74ece56c82b9c4$export$6c8a5aaad13c9852(tree, selectionState)
  };
}
function $36d99f0640511db5$var$toggleKey(set, key) {
  let res = new Set(set);
  if (res.has(key))
    res.delete(key);
  else
    res.add(key);
  return res;
}
function listboxWrapperStyle(className) {
  return clsx("p-4 overflow-y-auto text-base sm:text-sm outline-none max-h-inherit", className);
}
function listboxItemStyle({
  isFocused,
  isSelected,
  isDisabled,
  isHovered
}) {
  let action = "";
  if (isDisabled) {
    action = "text-disabled pointer-events-none";
  } else if (isSelected) {
    if (isHovered || isFocused) {
      action = "bg-primary/focus";
    } else {
      action = "bg-primary/selected";
    }
  } else if (isFocused) {
    action = "bg-focus";
  } else if (isHovered) {
    action = "bg-hover";
  }
  return clsx("px-16 py-8 text-sm truncate select-none outline-none rounded cursor-pointer flex items-center gap-16", action);
}
const listboxItemIconStyle = "icon-md text-muted";
function MenuItem(props2) {
  const {
    item,
    state: state2,
    onAction
  } = props2;
  const {
    onClose,
    closeOnSelect
  } = useMenuContext();
  let startIcon;
  let endIcon;
  let label;
  const {
    rendered,
    key
  } = item;
  if (Array.isArray(rendered)) {
    [startIcon = null, label, endIcon = null] = rendered;
  } else {
    label = rendered;
  }
  const isSelected = state2.selectionManager.isSelected(key);
  const isDisabled = state2.disabledKeys.has(key);
  const ref = useRef(null);
  const {
    menuItemProps,
    labelProps,
    descriptionProps,
    keyboardShortcutProps
  } = $c5d816999d2ff723$export$9d32628fc2aea7da({
    isSelected,
    isDisabled,
    "aria-label": item["aria-label"],
    key,
    onClose,
    closeOnSelect,
    onAction
  }, state2, ref);
  const {
    hoverProps,
    isHovered
  } = $6179b936705e76d3$export$ae780daf29e6d456({
    isDisabled
  });
  const {
    focusProps,
    isFocusVisible
  } = $e63d024ca16f2165$export$4e328f61c538687f();
  const className = listboxItemStyle({
    isFocused: isFocusVisible,
    isSelected,
    isDisabled,
    isHovered
  });
  return /* @__PURE__ */ jsxs("li", __spreadProps(__spreadValues({
    className
  }, $3ef42575df84b30b$export$9d1611c77c2fe928(menuItemProps, hoverProps, focusProps)), {
    ref,
    children: [startIcon && React__default.cloneElement(startIcon, {
      className: listboxItemIconStyle
    }), /* @__PURE__ */ jsx("div", __spreadProps(__spreadValues({}, labelProps), {
      children: label
    })), endIcon]
  }));
}
function Menu(props2) {
  const className = listboxWrapperStyle();
  const contextProps = useContext(MenuContext);
  const menuRef = useRef(null);
  const mergedProps = __spreadValues({}, $3ef42575df84b30b$export$9d1611c77c2fe928(contextProps, props2));
  const state2 = $36d99f0640511db5$export$728d6ba534403756(mergedProps);
  const {
    menuProps
  } = $9e81e1e13d86f3bd$export$38eaa17faae8f579(mergedProps, state2, menuRef);
  return /* @__PURE__ */ jsx("ul", __spreadProps(__spreadValues({
    ref: menuRef,
    className
  }, menuProps), {
    children: [...state2.collection].map((item) => {
      let menuItem = /* @__PURE__ */ jsx(MenuItem, {
        item,
        state: state2,
        onAction: mergedProps.onAction
      }, item.key);
      if (item.wrapper) {
        menuItem = item.wrapper(menuItem);
      }
      return menuItem;
    })
  }));
}
function DropdownButton({
  item,
  button
}) {
  const menuItems = item.menuItems;
  return /* @__PURE__ */ jsxs(MenuTrigger, {
    children: [button, /* @__PURE__ */ jsx(Menu, {
      onAction: (label) => {
        const menuItem = menuItems.find((i2) => i2.label === label);
        menuItem == null ? void 0 : menuItem.action();
      },
      items: menuItems,
      children: (menuItem) => /* @__PURE__ */ jsx($89e587cd0f107a73$export$6d08773d2e66f8f2, {
        children: menuItem.label
      }, menuItem.label)
    })]
  });
}
const IconButton = forwardRef((_i, ref) => {
  var _j = _i, {
    children,
    size,
    variant = "text",
    radius = "rounded-full",
    className,
    padding,
    equalWidth = true
  } = _j, other = __objRest(_j, [
    "children",
    "size",
    "variant",
    "radius",
    "className",
    "padding",
    "equalWidth"
  ]);
  const mergedClassName = clsx(getButtonSizeStyle(size, {
    padding,
    equalWidth
  }), className);
  const iconClass = clsx(children.props.className, getIconSizeStyle(size));
  return /* @__PURE__ */ jsx(ButtonBase, __spreadProps(__spreadValues({}, other), {
    ref,
    radius,
    variant,
    className: mergedClassName,
    children: React__default.cloneElement(children, {
      className: iconClass
    })
  }));
});
function _MixedIcon({
  icon,
  className
}) {
  let iconEl;
  if (React__default.isValidElement(icon)) {
    iconEl = React__default.cloneElement(icon, {
      className: "svg-iconEl"
    });
  } else if (typeof icon === "string") {
    iconEl = /* @__PURE__ */ jsx("img", {
      className: "w-font h-font",
      src: icon,
      alt: ""
    });
  } else if (Array.isArray(icon)) {
    iconEl = React__default.createElement(createSvgIconFromTree(icon));
  } else {
    iconEl = React__default.createElement(icon);
  }
  return /* @__PURE__ */ jsx("span", {
    className: clsx(className, "leading-none"),
    children: iconEl
  });
}
const MixedIcon = React__default.memo(_MixedIcon);
function ToolbarButton({
  item
}) {
  const button = item.label ? /* @__PURE__ */ jsx(ButtonWithLabel, {
    item
  }) : /* @__PURE__ */ jsx(IconOnlyButton, {
    item
  });
  if (item.menuItems) {
    return /* @__PURE__ */ jsx(DropdownButton, {
      item,
      button
    });
  }
  return React__default.cloneElement(button, {
    onPress: () => {
      var _a2;
      (_a2 = item.action) == null ? void 0 : _a2.call(item, state().editor);
    }
  });
}
const IconOnlyButton = forwardRef((_k, ref) => {
  var _l = _k, {
    item
  } = _l, other = __objRest(_l, [
    "item"
  ]);
  return /* @__PURE__ */ jsx(IconButton, __spreadProps(__spreadValues({
    ref,
    radius: "rounded-full",
    size: "sm"
  }, other), {
    children: /* @__PURE__ */ jsx(MixedIcon, {
      icon: item.icon
    })
  }));
});
const ButtonWithLabel = forwardRef((_m, ref) => {
  var _n = _m, {
    item
  } = _n, other = __objRest(_n, [
    "item"
  ]);
  return /* @__PURE__ */ jsx(Button, __spreadProps(__spreadValues({
    ref,
    radius: "rounded-full",
    size: "xs",
    color: "primary",
    startIcon: /* @__PURE__ */ jsx(MixedIcon, {
      icon: item.icon
    })
  }, other), {
    children: /* @__PURE__ */ jsx(Label, {
      item
    })
  }));
});
function Label({
  item
}) {
  if (!item.label)
    return null;
  if (typeof item.label === "string") {
    return /* @__PURE__ */ jsx(Fragment, {
      children: item.label
    });
  }
  return /* @__PURE__ */ jsx(FormattedMessage$1, __spreadValues({}, item.label));
}
function ButtonGroup({
  children,
  color: color2,
  variant,
  radius,
  size,
  className,
  value,
  onChange,
  multiple
}) {
  const isActive = (childValue) => {
    if (value === void 0)
      return false;
    if (multiple) {
      return value.includes(childValue);
    }
    return childValue === value;
  };
  const toggleMultipleValue = (childValue) => {
    const newValue = [...value];
    const childIndex = value.indexOf(childValue);
    if (childIndex > -1) {
      newValue.splice(childIndex, 1);
    } else {
      newValue.push(childValue);
    }
    return newValue;
  };
  const buttons = React__default.Children.map(children, (button, i2) => {
    if (React__default.isValidElement(button)) {
      const active = isActive(button.props.value);
      const adjustedColor = active ? "primary" : color2;
      return React__default.cloneElement(button, __spreadProps(__spreadValues({
        color: active ? "primary" : color2,
        variant,
        size,
        radius: null
      }, button.props), {
        onPress: (e2) => {
          if (button.props.onPress) {
            button.props.onPress(e2);
          }
          if (!onChange)
            return;
          if (multiple) {
            onChange == null ? void 0 : onChange(toggleMultipleValue(button.props.value));
          } else {
            onChange == null ? void 0 : onChange(button.props.value);
          }
        },
        className: clsx(button.props.className, active ? "z-20" : "z-10", getStyle(i2, children, radius, adjustedColor))
      }));
    }
  });
  return /* @__PURE__ */ jsx("div", {
    className: clsx(radius, "inline-flex isolate", className),
    children: buttons
  });
}
function getStyle(i2, children, radius, color2) {
  if (i2 === 0) {
    return clsx(radius, "rounded-tr-none rounded-br-none", !color2 && "border-r-transparent disabled:border-r-transparent");
  }
  if (i2 === children.length - 1) {
    return clsx(radius, "rounded-tl-none rounded-bl-none -ml-1");
  }
  return clsx("rounded-none -ml-1", !color2 && "border-r-transparent disabled:border-r-transparent");
}
const UndoIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M12.5 8c-2.65 0-5.05.99-6.9 2.6L2 7v9h9l-3.62-3.62c1.39-1.16 3.16-1.88 5.12-1.88 3.54 0 6.55 2.31 7.6 5.5l2.37-.78C21.08 11.03 17.15 8 12.5 8z"
}), "UndoOutlined");
const RedoIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M18.4 10.6C16.55 8.99 14.15 8 11.5 8c-4.65 0-8.58 3.03-9.96 7.22L3.9 16c1.05-3.19 4.05-5.5 7.6-5.5 1.95 0 3.73.72 5.12 1.88L13 16h9V7l-3.6 3.6z"
}), "RedoOutlined");
function UndoRedoBtns() {
  const canUndo = useStore$1((s2) => s2.history.canUndo);
  const canRedo = useStore$1((s2) => s2.history.canRedo);
  return /* @__PURE__ */ jsxs(ButtonGroup, {
    variant: "outline",
    children: [/* @__PURE__ */ jsx(IconButton, {
      equalWidth: false,
      size: "xs",
      padding: "pl-12 pr-10",
      radius: "rounded-full",
      isDisabled: !canUndo,
      onPress: () => {
        tools().history.undo();
      },
      children: /* @__PURE__ */ jsx(UndoIcon, {})
    }), /* @__PURE__ */ jsx(IconButton, {
      equalWidth: false,
      padding: "pl-10 pr-12",
      size: "xs",
      radius: "rounded-full",
      isDisabled: !canRedo,
      onPress: () => {
        tools().history.redo();
      },
      children: /* @__PURE__ */ jsx(RedoIcon, {})
    })]
  });
}
const RemoveIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M19 13H5v-2h14v2z"
}), "RemoveOutlined");
const AddIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"
}), "AddOutlined");
function ZoomWidget() {
  var _a2, _b, _c;
  const zoom = useStore$1((s2) => s2.zoom) || 1;
  const allowUserZoom = (_a2 = useStore$1((s2) => {
    var _a3, _b2;
    return (_b2 = (_a3 = s2.config.tools) == null ? void 0 : _a3.zoom) == null ? void 0 : _b2.allowUserZoom;
  })) != null ? _a2 : true;
  if (!allowUserZoom) {
    return null;
  }
  return /* @__PURE__ */ jsxs("div", {
    className: "flex items-center select-none",
    children: [/* @__PURE__ */ jsx(IconButton, {
      size: "sm",
      isDisabled: !((_b = tools().zoom) == null ? void 0 : _b.canZoomOut()),
      onPress: () => {
        tools().zoom.zoomOut(tools().zoom.step);
      },
      children: /* @__PURE__ */ jsx(RemoveIcon, {})
    }), /* @__PURE__ */ jsxs("div", {
      className: "w-[4ch] text-sm text-center",
      children: [Math.round(zoom * 100), "%"]
    }), /* @__PURE__ */ jsx(IconButton, {
      size: "sm",
      isDisabled: !((_c = tools().zoom) == null ? void 0 : _c.canZoomIn()),
      onPress: () => {
        tools().zoom.zoomIn(tools().zoom.step);
      },
      children: /* @__PURE__ */ jsx(AddIcon, {})
    })]
  });
}
function ToolbarItem({
  item
}) {
  switch (item.type) {
    case "undoWidget":
      return /* @__PURE__ */ jsx(UndoRedoBtns, {});
    case "zoomWidget":
      return /* @__PURE__ */ jsx(ZoomWidget, {});
    case "button":
      return /* @__PURE__ */ jsx(ToolbarButton, {
        item
      });
    case "image":
      return /* @__PURE__ */ jsx("img", {
        className: "h-30 object-cover",
        src: assetUrl(item.src),
        alt: ""
      });
    default:
      return null;
  }
}
const CloseIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z"
}), "CloseOutlined");
function useEditorMode() {
  var _a2;
  let isModal = useStore$1((s2) => {
    var _a3;
    return ((_a3 = s2.config.ui) == null ? void 0 : _a3.mode) === EditorMode.OVERLAY;
  });
  const {
    width
  } = useStore$1((s2) => s2.stageSize);
  const isMobile = width <= 700;
  if (isMobile && ((_a2 = state().config.ui) == null ? void 0 : _a2.forceOverlayModeOnMobile)) {
    isModal = true;
  }
  return {
    isModal,
    isMobile
  };
}
function MainToolbar() {
  var _a2;
  const {
    isModal,
    isMobile
  } = useEditorMode();
  const allowEditorClose = (_a2 = useStore$1((s2) => {
    var _a3;
    return (_a3 = s2.config.ui) == null ? void 0 : _a3.allowEditorClose;
  })) != null ? _a2 : true;
  const items = useStore$1((s2) => {
    var _a3, _b;
    return (_b = (_a3 = s2.config.ui) == null ? void 0 : _a3.menubar) == null ? void 0 : _b.items;
  }) || [];
  const leftItems = [];
  const centerItems = [];
  const rightItems = [];
  items.filter((item) => !isMobile && !item.mobileOnly || isMobile && !item.desktopOnly).forEach((item) => {
    if (item.align === "left") {
      leftItems.push(item);
    } else if (item.align === "right") {
      rightItems.push(item);
    } else {
      centerItems.push(item);
    }
  });
  const closeButton = isModal && isMobile && allowEditorClose && /* @__PURE__ */ jsx(IconButton, {
    size: "sm",
    className: "ml-10",
    onPress: () => {
      state().editor.close();
    },
    children: /* @__PURE__ */ jsx(CloseIcon, {})
  });
  return /* @__PURE__ */ jsxs(m$2.div, __spreadProps(__spreadValues({
    className: toolbarStyle
  }, toolbarAnimation), {
    children: [/* @__PURE__ */ jsx("div", {
      className: "mr-auto",
      children: leftItems.map((item, i2) => /* @__PURE__ */ jsx(ToolbarItem, {
        item
      }, i2))
    }), /* @__PURE__ */ jsx("div", {
      className: "flex items-center gap-10",
      children: centerItems.map((item, i2) => /* @__PURE__ */ jsx(ToolbarItem, {
        item
      }, i2))
    }), /* @__PURE__ */ jsx("div", {
      className: "ml-auto flex items-center gap-8",
      children: rightItems.map((item, i2) => /* @__PURE__ */ jsx(ToolbarItem, {
        item
      }, i2))
    }), closeButton]
  }));
}
class ResizeAction {
  constructor() {
    __publicField(this, "callbackName", "onResize");
    __publicField(this, "resizeDir", null);
  }
  matches(e2) {
    const target = e2.target;
    if (target.dataset.position) {
      this.resizeDir = target.dataset.position;
      return true;
    }
    return false;
  }
  execute(e2, rect) {
    if (rect) {
      return this.resizeUsingRect(e2, rect);
    }
    return this.resizeUsingEvent(e2);
  }
  onPointerUp() {
    this.resizeDir = null;
  }
  resizeUsingEvent(e2) {
    const prevRect = __spreadValues({}, e2.currentRect);
    const newRect = __spreadValues({}, e2.currentRect);
    const ratio = e2.aspectRatio;
    if (this.resizeDir === "top-right") {
      newRect.width = Math.floor(newRect.width + e2.deltaX);
      if (ratio) {
        newRect.height = Math.floor(newRect.width / ratio);
      } else {
        newRect.height = Math.floor(newRect.height - e2.deltaY);
      }
      newRect.top = Math.floor(newRect.top + (prevRect.height - newRect.height));
    } else if (this.resizeDir === "bottom-right") {
      newRect.width = Math.floor(newRect.width + e2.deltaX);
      if (ratio) {
        newRect.height = Math.floor(newRect.width / ratio);
      } else {
        newRect.height = Math.floor(newRect.height + e2.deltaY);
      }
    } else if (this.resizeDir === "top-left") {
      newRect.width = Math.floor(newRect.width - e2.deltaX);
      if (ratio) {
        newRect.height = Math.floor(newRect.width / ratio);
      } else {
        newRect.height = Math.floor(newRect.height - e2.deltaY);
      }
      newRect.left = Math.floor(newRect.left + (prevRect.width - newRect.width));
      newRect.top = Math.floor(newRect.top + (prevRect.height - newRect.height));
    } else if (this.resizeDir === "bottom-left") {
      newRect.width = Math.floor(newRect.width - e2.deltaX);
      if (ratio) {
        newRect.height = Math.floor(newRect.width / ratio);
      } else {
        newRect.height = Math.floor(newRect.height + e2.deltaY);
      }
      newRect.left = Math.floor(newRect.left + (prevRect.width - newRect.width));
    }
    return newRect;
  }
  resizeUsingRect(e2, newRect) {
    const currentRect = __spreadValues(__spreadValues({}, e2.currentRect), newRect);
    if (e2.aspectRatio) {
      const size = calcNewSizeFromAspectRatio(e2.aspectRatio, currentRect.width, currentRect.height);
      currentRect.width = size.width;
      currentRect.height = size.height;
    }
    return currentRect;
  }
}
function $parcel$export$j(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $9f327308a7d514e5$exports = {};
$parcel$export$j($9f327308a7d514e5$exports, "useNumberFieldState", () => $9f327308a7d514e5$export$7f629e9dc1ecf37c);
function $9f327308a7d514e5$export$7f629e9dc1ecf37c(props2) {
  let { minValue, maxValue, step, formatOptions, value: value1, defaultValue, onChange, locale, isDisabled, isReadOnly } = props2;
  let [numberValue, setNumberValue] = $bfee1151ccb0650f$export$40bfa8c7b0832715(value1, isNaN(defaultValue) ? NaN : defaultValue, onChange);
  let [inputValue, setInputValue] = useState(() => isNaN(numberValue) ? "" : new $81812865b3bb9d70$export$cc77c4ff7e8673c5(locale, formatOptions).format(numberValue));
  let numberParser = useMemo(() => new $ad41ad2a9f71fc3e$export$cd11ab140839f11d(locale, formatOptions), [
    locale,
    formatOptions
  ]);
  let numberingSystem = useMemo(() => numberParser.getNumberingSystem(inputValue), [
    numberParser,
    inputValue
  ]);
  let formatter = useMemo(() => new $81812865b3bb9d70$export$cc77c4ff7e8673c5(locale, __spreadProps(__spreadValues({}, formatOptions), {
    numberingSystem
  })), [
    locale,
    formatOptions,
    numberingSystem
  ]);
  let intlOptions = useMemo(() => formatter.resolvedOptions(), [
    formatter
  ]);
  let format = useCallback((value) => isNaN(value) ? "" : formatter.format(value), [
    formatter
  ]);
  let clampStep = !isNaN(step) ? step : 1;
  if (intlOptions.style === "percent" && isNaN(step))
    clampStep = 0.01;
  useEffect(() => {
    setInputValue(format(numberValue));
  }, [
    numberValue,
    locale,
    formatOptions
  ]);
  let parsedValue = useMemo(() => numberParser.parse(inputValue), [
    numberParser,
    inputValue
  ]);
  let parsed = useRef(0);
  parsed.current = parsedValue;
  let commit = () => {
    if (!inputValue.length) {
      setNumberValue(NaN);
      setInputValue(value1 === void 0 ? "" : format(numberValue));
      return;
    }
    if (isNaN(parsed.current)) {
      setInputValue(format(numberValue));
      return;
    }
    let clampedValue;
    if (isNaN(step))
      clampedValue = $48d9f1d165180307$export$7d15b64cf5a3a4c4(parsed.current, minValue, maxValue);
    else
      clampedValue = $48d9f1d165180307$export$cb6e0bb50bc19463(parsed.current, minValue, maxValue, step);
    clampedValue = numberParser.parse(format(clampedValue));
    setNumberValue(clampedValue);
    setInputValue(format(value1 === void 0 ? clampedValue : numberValue));
  };
  let safeNextStep = (operation, minMax) => {
    let prev = parsed.current;
    if (isNaN(prev)) {
      let newValue = isNaN(minMax) ? 0 : minMax;
      return $48d9f1d165180307$export$cb6e0bb50bc19463(newValue, minValue, maxValue, clampStep);
    } else {
      let newValue = $48d9f1d165180307$export$cb6e0bb50bc19463(prev, minValue, maxValue, clampStep);
      if (operation === "+" && newValue > prev || operation === "-" && newValue < prev)
        return newValue;
      return $48d9f1d165180307$export$cb6e0bb50bc19463($9f327308a7d514e5$var$handleDecimalOperation(operation, prev, clampStep), minValue, maxValue, clampStep);
    }
  };
  let increment = () => {
    let newValue = safeNextStep("+", minValue);
    if (newValue === numberValue)
      setInputValue(format(newValue));
    setNumberValue(newValue);
  };
  let decrement = () => {
    let newValue = safeNextStep("-", maxValue);
    if (newValue === numberValue)
      setInputValue(format(newValue));
    setNumberValue(newValue);
  };
  let incrementToMax = () => {
    if (maxValue != null)
      setNumberValue($48d9f1d165180307$export$cb6e0bb50bc19463(maxValue, minValue, maxValue, clampStep));
  };
  let decrementToMin = () => {
    if (minValue != null)
      setNumberValue(minValue);
  };
  let canIncrement = useMemo(() => !isDisabled && !isReadOnly && (isNaN(parsedValue) || isNaN(maxValue) || $48d9f1d165180307$export$cb6e0bb50bc19463(parsedValue, minValue, maxValue, clampStep) > parsedValue || $9f327308a7d514e5$var$handleDecimalOperation("+", parsedValue, clampStep) <= maxValue), [
    isDisabled,
    isReadOnly,
    minValue,
    maxValue,
    clampStep,
    parsedValue
  ]);
  let canDecrement = useMemo(() => !isDisabled && !isReadOnly && (isNaN(parsedValue) || isNaN(minValue) || $48d9f1d165180307$export$cb6e0bb50bc19463(parsedValue, minValue, maxValue, clampStep) < parsedValue || $9f327308a7d514e5$var$handleDecimalOperation("-", parsedValue, clampStep) >= minValue), [
    isDisabled,
    isReadOnly,
    minValue,
    maxValue,
    clampStep,
    parsedValue
  ]);
  let validate = (value) => numberParser.isValidPartialNumber(value, minValue, maxValue);
  return {
    validate,
    increment,
    incrementToMax,
    decrement,
    decrementToMin,
    canIncrement,
    canDecrement,
    minValue,
    maxValue,
    numberValue: parsedValue,
    setInputValue,
    inputValue,
    commit
  };
}
function $9f327308a7d514e5$var$handleDecimalOperation(operator, value1, value2) {
  let result = operator === "+" ? value1 + value2 : value1 - value2;
  if (value1 % 1 !== 0 || value2 % 1 !== 0) {
    const value1Decimal = value1.toString().split(".");
    const value2Decimal = value2.toString().split(".");
    const value1DecimalLength = value1Decimal[1] && value1Decimal[1].length || 0;
    const value2DecimalLength = value2Decimal[1] && value2Decimal[1].length || 0;
    const multiplier = Math.pow(10, Math.max(value1DecimalLength, value2DecimalLength));
    value1 = Math.round(value1 * multiplier);
    value2 = Math.round(value2 * multiplier);
    result = operator === "+" ? value1 + value2 : value1 - value2;
    result /= multiplier;
  }
  return result;
}
function $parcel$export$i(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $8f1f06f2efd295ee$exports = {};
$parcel$export$i($8f1f06f2efd295ee$exports, "useField", () => $8f1f06f2efd295ee$export$294aa081a6c6f55d);
var $6f8f5e0de5a77844$exports = {};
$parcel$export$i($6f8f5e0de5a77844$exports, "useLabel", () => $6f8f5e0de5a77844$export$8467354a121f1b9f);
function $6f8f5e0de5a77844$export$8467354a121f1b9f(props2) {
  let { id: id2, label, "aria-labelledby": ariaLabelledby, "aria-label": ariaLabel, labelElementType = "label" } = props2;
  id2 = $bdb11010cef70236$export$f680877a34711e37(id2);
  let labelId = $bdb11010cef70236$export$f680877a34711e37();
  let labelProps = {};
  if (label) {
    ariaLabelledby = ariaLabelledby ? `${ariaLabelledby} ${labelId}` : labelId;
    labelProps = {
      id: labelId,
      htmlFor: labelElementType === "label" ? id2 : void 0
    };
  } else if (!ariaLabelledby && !ariaLabel)
    console.warn("If you do not provide a visible label, you must specify an aria-label or aria-labelledby attribute for accessibility");
  let fieldProps = $313b98861ee5dd6c$export$d6875122194c7b44({
    id: id2,
    "aria-label": ariaLabel,
    "aria-labelledby": ariaLabelledby
  });
  return {
    labelProps,
    fieldProps
  };
}
function $8f1f06f2efd295ee$export$294aa081a6c6f55d(props2) {
  let { description, errorMessage, validationState } = props2;
  let { labelProps, fieldProps } = $6f8f5e0de5a77844$export$8467354a121f1b9f(props2);
  let descriptionId = $bdb11010cef70236$export$b4cc09c592e8fdb8([
    Boolean(description),
    Boolean(errorMessage),
    validationState
  ]);
  let errorMessageId = $bdb11010cef70236$export$b4cc09c592e8fdb8([
    Boolean(description),
    Boolean(errorMessage),
    validationState
  ]);
  fieldProps = $3ef42575df84b30b$export$9d1611c77c2fe928(fieldProps, {
    "aria-describedby": [
      descriptionId,
      errorMessageId,
      props2["aria-describedby"]
    ].filter(Boolean).join(" ") || void 0
  });
  return {
    labelProps,
    fieldProps,
    descriptionProps: {
      id: descriptionId
    },
    errorMessageProps: {
      id: errorMessageId
    }
  };
}
function $parcel$export$h(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $13fe50aacf882d03$exports = {};
$parcel$export$h($13fe50aacf882d03$exports, "useTextField", () => $13fe50aacf882d03$export$712718f7aec83d5);
function $13fe50aacf882d03$export$712718f7aec83d5(props2, ref) {
  let { inputElementType = "input", isDisabled = false, isRequired = false, isReadOnly = false, validationState, type = "text", onChange = () => {
  } } = props2;
  let { focusableProps } = $391c6482f25a1991$export$4c014de7c8940b4c(props2, ref);
  let { labelProps, fieldProps, descriptionProps, errorMessageProps } = $8f1f06f2efd295ee$export$294aa081a6c6f55d(props2);
  let domProps = $65484d02dcb7eb3e$export$457c3d6518dd4c6f(props2, {
    labelable: true
  });
  const inputOnlyProps = {
    type,
    pattern: props2.pattern
  };
  return {
    labelProps,
    inputProps: $3ef42575df84b30b$export$9d1611c77c2fe928(domProps, inputElementType === "input" && inputOnlyProps, __spreadValues(__spreadValues({
      disabled: isDisabled,
      readOnly: isReadOnly,
      "aria-required": isRequired || void 0,
      "aria-invalid": validationState === "invalid" || void 0,
      "aria-errormessage": props2["aria-errormessage"],
      "aria-activedescendant": props2["aria-activedescendant"],
      "aria-autocomplete": props2["aria-autocomplete"],
      "aria-haspopup": props2["aria-haspopup"],
      value: props2.value,
      defaultValue: props2.value ? void 0 : props2.defaultValue,
      onChange: (e2) => onChange(e2.target.value),
      autoComplete: props2.autoComplete,
      maxLength: props2.maxLength,
      minLength: props2.minLength,
      name: props2.name,
      placeholder: props2.placeholder,
      inputMode: props2.inputMode,
      onCopy: props2.onCopy,
      onCut: props2.onCut,
      onPaste: props2.onPaste,
      onCompositionEnd: props2.onCompositionEnd,
      onCompositionStart: props2.onCompositionStart,
      onCompositionUpdate: props2.onCompositionUpdate,
      onSelect: props2.onSelect,
      onBeforeInput: props2.onBeforeInput,
      onInput: props2.onInput
    }, focusableProps), fieldProps)),
    descriptionProps,
    errorMessageProps
  };
}
var $58c0262056d833d5$exports = {};
$parcel$export$h($58c0262056d833d5$exports, "useFormattedTextField", () => $58c0262056d833d5$export$4f384c9210e583c3);
function $58c0262056d833d5$var$supportsNativeBeforeInputEvent() {
  return typeof window !== "undefined" && window.InputEvent && typeof InputEvent.prototype.getTargetRanges === "function";
}
function $58c0262056d833d5$export$4f384c9210e583c3(props2, state1, inputRef) {
  let stateRef = useRef(state1);
  stateRef.current = state1;
  useEffect(() => {
    if (!$58c0262056d833d5$var$supportsNativeBeforeInputEvent())
      return;
    let input = inputRef.current;
    let onBeforeInput = (e2) => {
      let state2 = stateRef.current;
      let nextValue;
      switch (e2.inputType) {
        case "historyUndo":
        case "historyRedo":
          return;
        case "deleteContent":
        case "deleteByCut":
        case "deleteByDrag":
          nextValue = input.value.slice(0, input.selectionStart) + input.value.slice(input.selectionEnd);
          break;
        case "deleteContentForward":
          nextValue = input.selectionEnd === input.selectionStart ? input.value.slice(0, input.selectionStart) + input.value.slice(input.selectionEnd + 1) : input.value.slice(0, input.selectionStart) + input.value.slice(input.selectionEnd);
          break;
        case "deleteContentBackward":
          nextValue = input.selectionEnd === input.selectionStart ? input.value.slice(0, input.selectionStart - 1) + input.value.slice(input.selectionStart) : input.value.slice(0, input.selectionStart) + input.value.slice(input.selectionEnd);
          break;
        case "deleteSoftLineBackward":
        case "deleteHardLineBackward":
          nextValue = input.value.slice(input.selectionStart);
          break;
        default:
          if (e2.data != null)
            nextValue = input.value.slice(0, input.selectionStart) + e2.data + input.value.slice(input.selectionEnd);
          break;
      }
      if (nextValue == null || !state2.validate(nextValue))
        e2.preventDefault();
    };
    input.addEventListener("beforeinput", onBeforeInput, false);
    return () => {
      input.removeEventListener("beforeinput", onBeforeInput, false);
    };
  }, [
    inputRef,
    stateRef
  ]);
  let onBeforeInput1 = !$58c0262056d833d5$var$supportsNativeBeforeInputEvent() ? (e2) => {
    let nextValue = e2.target.value.slice(0, e2.target.selectionStart) + e2.data + e2.target.value.slice(e2.target.selectionEnd);
    if (!state1.validate(nextValue))
      e2.preventDefault();
  } : null;
  let { labelProps, inputProps: textFieldProps, descriptionProps, errorMessageProps } = $13fe50aacf882d03$export$712718f7aec83d5(props2, inputRef);
  let compositionStartState = useRef(null);
  return {
    inputProps: $3ef42575df84b30b$export$9d1611c77c2fe928(textFieldProps, {
      onBeforeInput: onBeforeInput1,
      onCompositionStart() {
        let { value, selectionStart, selectionEnd } = inputRef.current;
        compositionStartState.current = {
          value,
          selectionStart,
          selectionEnd
        };
      },
      onCompositionEnd() {
        if (!state1.validate(inputRef.current.value)) {
          let { value, selectionStart, selectionEnd } = compositionStartState.current;
          inputRef.current.value = value;
          inputRef.current.setSelectionRange(selectionStart, selectionEnd);
          state1.setInputValue(value);
        }
      }
    }),
    labelProps,
    descriptionProps,
    errorMessageProps
  };
}
function $parcel$export$g(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $9694eec57086f168$exports = {};
$parcel$export$g($9694eec57086f168$exports, "announce", () => $9694eec57086f168$export$a9b970dcc4ae71a9);
$parcel$export$g($9694eec57086f168$exports, "clearAnnouncer", () => $9694eec57086f168$export$d10ae4f68404609a);
$parcel$export$g($9694eec57086f168$exports, "destroyAnnouncer", () => $9694eec57086f168$export$d8686216b8b81b2f);
const $9694eec57086f168$var$LIVEREGION_TIMEOUT_DELAY = 7e3;
let $9694eec57086f168$var$liveRegionAnnouncer = /* @__PURE__ */ React__default.createRef();
let $9694eec57086f168$var$node = null;
let $9694eec57086f168$var$messageId = 0;
function $9694eec57086f168$export$a9b970dcc4ae71a9(message, assertiveness = "assertive", timeout = $9694eec57086f168$var$LIVEREGION_TIMEOUT_DELAY) {
  $9694eec57086f168$var$ensureInstance((announcer) => announcer.announce(message, assertiveness, timeout));
}
function $9694eec57086f168$export$d10ae4f68404609a(assertiveness) {
  $9694eec57086f168$var$ensureInstance((announcer) => announcer.clear(assertiveness));
}
function $9694eec57086f168$export$d8686216b8b81b2f() {
  if ($9694eec57086f168$var$liveRegionAnnouncer.current) {
    $icz4I$reactdom.unmountComponentAtNode($9694eec57086f168$var$node);
    document.body.removeChild($9694eec57086f168$var$node);
    $9694eec57086f168$var$node = null;
  }
}
function $9694eec57086f168$var$ensureInstance(callback) {
  if (!$9694eec57086f168$var$liveRegionAnnouncer.current) {
    $9694eec57086f168$var$node = document.createElement("div");
    $9694eec57086f168$var$node.dataset.liveAnnouncer = "true";
    document.body.prepend($9694eec57086f168$var$node);
    $icz4I$reactdom.render(/* @__PURE__ */ React__default.createElement($9694eec57086f168$var$LiveRegionAnnouncer, {
      ref: $9694eec57086f168$var$liveRegionAnnouncer
    }), $9694eec57086f168$var$node, () => callback($9694eec57086f168$var$liveRegionAnnouncer.current));
  } else
    callback($9694eec57086f168$var$liveRegionAnnouncer.current);
}
const $9694eec57086f168$var$LiveRegionAnnouncer = /* @__PURE__ */ React__default.forwardRef((_2, ref) => {
  let [assertiveMessages, setAssertiveMessages] = useState([]);
  let [politeMessages, setPoliteMessages] = useState([]);
  let clear = (assertiveness) => {
    if (!assertiveness || assertiveness === "assertive")
      setAssertiveMessages([]);
    if (!assertiveness || assertiveness === "polite")
      setPoliteMessages([]);
  };
  let $9694eec57086f168$export$a9b970dcc4ae71a92 = (message1, assertiveness = "assertive", timeout = $9694eec57086f168$var$LIVEREGION_TIMEOUT_DELAY) => {
    let id2 = $9694eec57086f168$var$messageId++;
    if (assertiveness === "assertive")
      setAssertiveMessages((messages2) => [
        ...messages2,
        {
          id: id2,
          text: message1
        }
      ]);
    else
      setPoliteMessages((messages2) => [
        ...messages2,
        {
          id: id2,
          text: message1
        }
      ]);
    if (message1 !== "")
      setTimeout(() => {
        if (assertiveness === "assertive")
          setAssertiveMessages((messages2) => messages2.filter((message) => message.id !== id2));
        else
          setPoliteMessages((messages2) => messages2.filter((message) => message.id !== id2));
      }, timeout);
  };
  useImperativeHandle(ref, () => ({
    announce: $9694eec57086f168$export$a9b970dcc4ae71a92,
    clear
  }));
  return /* @__PURE__ */ React__default.createElement(Fragment$1, null, /* @__PURE__ */ React__default.createElement($9694eec57086f168$var$MessageBlock, {
    "aria-live": "assertive"
  }, assertiveMessages.map((message) => /* @__PURE__ */ React__default.createElement("div", {
    key: message.id
  }, message.text))), /* @__PURE__ */ React__default.createElement($9694eec57086f168$var$MessageBlock, {
    "aria-live": "polite"
  }, politeMessages.map((message) => /* @__PURE__ */ React__default.createElement("div", {
    key: message.id
  }, message.text))));
});
function $9694eec57086f168$var$MessageBlock({ children, "aria-live": ariaLive }) {
  return /* @__PURE__ */ React__default.createElement($5c3e21d68f1c4674$export$439d29a4e110a164, {
    role: "log",
    "aria-live": ariaLive,
    "aria-relevant": "additions"
  }, children);
}
function $parcel$interopDefault$1(a2) {
  return a2 && a2.__esModule ? a2.default : a2;
}
function $parcel$export$f(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $7fc2c1269c209e7a$exports = {};
$parcel$export$f($7fc2c1269c209e7a$exports, "useSpinButton", () => $7fc2c1269c209e7a$export$e908e06f4b8e3402);
var $340b38cae631a990$exports = {};
var $b9502ca1ed2a658b$exports = {};
$b9502ca1ed2a658b$exports = JSON.parse('{"Empty":"\u0641\u0627\u0631\u063A"}');
var $f5536daa79264fee$exports = {};
$f5536daa79264fee$exports = JSON.parse('{"Empty":"\u0418\u0437\u043F\u0440\u0430\u0437\u043D\u0438"}');
var $cf7f4a4198f8a132$exports = {};
$cf7f4a4198f8a132$exports = JSON.parse('{"Empty":"Pr\xE1zdn\xE9"}');
var $a125126b72296152$exports = {};
$a125126b72296152$exports = JSON.parse('{"Empty":"Tom"}');
var $14e8c357b1f6a729$exports = {};
$14e8c357b1f6a729$exports = JSON.parse('{"Empty":"Leer"}');
var $80806430c53bf3df$exports = {};
$80806430c53bf3df$exports = JSON.parse('{"Empty":"\u0386\u03B4\u03B5\u03B9\u03BF"}');
var $9da37b54727bdc96$exports = {};
$9da37b54727bdc96$exports = JSON.parse('{"Empty":"Empty"}');
var $4858ca7e134011e0$exports = {};
$4858ca7e134011e0$exports = JSON.parse('{"Empty":"Vac\xEDo"}');
var $84ca1479916e1b99$exports = {};
$84ca1479916e1b99$exports = JSON.parse('{"Empty":"T\xFChjenda"}');
var $93f5a002624d1f4c$exports = {};
$93f5a002624d1f4c$exports = JSON.parse('{"Empty":"Tyhj\xE4"}');
var $aed3a2b812f0d51c$exports = {};
$aed3a2b812f0d51c$exports = JSON.parse('{"Empty":"Vide"}');
var $dee73af7873d6102$exports = {};
$dee73af7873d6102$exports = JSON.parse('{"Empty":"\u05E8\u05D9\u05E7"}');
var $7eb77a2dda24ed8e$exports = {};
$7eb77a2dda24ed8e$exports = JSON.parse('{"Empty":"Prazno"}');
var $3226a172ca65c1f5$exports = {};
$3226a172ca65c1f5$exports = JSON.parse('{"Empty":"\xDCres"}');
var $2b2ffbc3f0ade025$exports = {};
$2b2ffbc3f0ade025$exports = JSON.parse('{"Empty":"Vuoto"}');
var $e9c8e101022d809a$exports = {};
$e9c8e101022d809a$exports = JSON.parse('{"Empty":"\u7A7A"}');
var $63f4629129a8bd6a$exports = {};
$63f4629129a8bd6a$exports = JSON.parse('{"Empty":"\uBE44\uC5B4 \uC788\uC74C"}');
var $047e27ea7822a64e$exports = {};
$047e27ea7822a64e$exports = JSON.parse('{"Empty":"Tu\u0161\u010Dias"}');
var $4f52beb8d7a97f37$exports = {};
$4f52beb8d7a97f37$exports = JSON.parse('{"Empty":"Tuk\u0161s"}');
var $e239fc54935fc6fe$exports = {};
$e239fc54935fc6fe$exports = JSON.parse('{"Empty":"Tom"}');
var $ff50d75ac63d2fe2$exports = {};
$ff50d75ac63d2fe2$exports = JSON.parse('{"Empty":"Leeg"}');
var $cb34519c43c80fbd$exports = {};
$cb34519c43c80fbd$exports = JSON.parse('{"Empty":"Pusty"}');
var $6335d0590d9b3b46$exports = {};
$6335d0590d9b3b46$exports = JSON.parse('{"Empty":"Vazio"}');
var $b352cf5a7254cc64$exports = {};
$b352cf5a7254cc64$exports = JSON.parse('{"Empty":"Vazio"}');
var $0421d1820ca63df4$exports = {};
$0421d1820ca63df4$exports = JSON.parse('{"Empty":"Gol"}');
var $cd59ecc168767389$exports = {};
$cd59ecc168767389$exports = JSON.parse('{"Empty":"\u041D\u0435 \u0437\u0430\u043F\u043E\u043B\u043D\u0435\u043D\u043E"}');
var $73864cfe6f4130a9$exports = {};
$73864cfe6f4130a9$exports = JSON.parse('{"Empty":"Pr\xE1zdne"}');
var $85a540e317a6ade4$exports = {};
$85a540e317a6ade4$exports = JSON.parse('{"Empty":"Prazen"}');
var $42d477601e71a1b4$exports = {};
$42d477601e71a1b4$exports = JSON.parse('{"Empty":"Prazno"}');
var $a8d88b556f2ce245$exports = {};
$a8d88b556f2ce245$exports = JSON.parse('{"Empty":"Tomt"}');
var $ab8e9d7da7315d53$exports = {};
$ab8e9d7da7315d53$exports = JSON.parse('{"Empty":"Bo\u015F"}');
var $73c9a5841c568e45$exports = {};
$73c9a5841c568e45$exports = JSON.parse('{"Empty":"\u041F\u0443\u0441\u0442\u043E"}');
var $35b700e586161794$exports = {};
$35b700e586161794$exports = JSON.parse('{"Empty":"\u7A7A"}');
var $53ac17eac2b15927$exports = {};
$53ac17eac2b15927$exports = JSON.parse('{"Empty":"\u7A7A\u767D"}');
$340b38cae631a990$exports = {
  "ar-AE": $b9502ca1ed2a658b$exports,
  "bg-BG": $f5536daa79264fee$exports,
  "cs-CZ": $cf7f4a4198f8a132$exports,
  "da-DK": $a125126b72296152$exports,
  "de-DE": $14e8c357b1f6a729$exports,
  "el-GR": $80806430c53bf3df$exports,
  "en-US": $9da37b54727bdc96$exports,
  "es-ES": $4858ca7e134011e0$exports,
  "et-EE": $84ca1479916e1b99$exports,
  "fi-FI": $93f5a002624d1f4c$exports,
  "fr-FR": $aed3a2b812f0d51c$exports,
  "he-IL": $dee73af7873d6102$exports,
  "hr-HR": $7eb77a2dda24ed8e$exports,
  "hu-HU": $3226a172ca65c1f5$exports,
  "it-IT": $2b2ffbc3f0ade025$exports,
  "ja-JP": $e9c8e101022d809a$exports,
  "ko-KR": $63f4629129a8bd6a$exports,
  "lt-LT": $047e27ea7822a64e$exports,
  "lv-LV": $4f52beb8d7a97f37$exports,
  "nb-NO": $e239fc54935fc6fe$exports,
  "nl-NL": $ff50d75ac63d2fe2$exports,
  "pl-PL": $cb34519c43c80fbd$exports,
  "pt-BR": $6335d0590d9b3b46$exports,
  "pt-PT": $b352cf5a7254cc64$exports,
  "ro-RO": $0421d1820ca63df4$exports,
  "ru-RU": $cd59ecc168767389$exports,
  "sk-SK": $73864cfe6f4130a9$exports,
  "sl-SI": $85a540e317a6ade4$exports,
  "sr-SP": $42d477601e71a1b4$exports,
  "sv-SE": $a8d88b556f2ce245$exports,
  "tr-TR": $ab8e9d7da7315d53$exports,
  "uk-UA": $73c9a5841c568e45$exports,
  "zh-CN": $35b700e586161794$exports,
  "zh-TW": $53ac17eac2b15927$exports
};
function $7fc2c1269c209e7a$export$e908e06f4b8e3402(props2) {
  const _async = useRef();
  let { value, textValue, minValue, maxValue, isDisabled, isReadOnly, isRequired, onIncrement, onIncrementPage, onDecrement, onDecrementPage, onDecrementToMin, onIncrementToMax } = props2;
  const formatMessage2 = $321bc95feeb923dd$export$ec23bf898b1eed85(/* @__PURE__ */ $parcel$interopDefault$1($340b38cae631a990$exports));
  const propsRef = useRef(props2);
  propsRef.current = props2;
  const clearAsync = () => clearTimeout(_async.current);
  useEffect(() => {
    return () => clearAsync();
  }, []);
  let onKeyDown = (e2) => {
    if (e2.ctrlKey || e2.metaKey || e2.shiftKey || e2.altKey || isReadOnly)
      return;
    switch (e2.key) {
      case "PageUp":
        if (onIncrementPage) {
          e2.preventDefault();
          onIncrementPage();
          break;
        }
      case "ArrowUp":
      case "Up":
        if (onIncrement) {
          e2.preventDefault();
          onIncrement();
        }
        break;
      case "PageDown":
        if (onDecrementPage) {
          e2.preventDefault();
          onDecrementPage();
          break;
        }
      case "ArrowDown":
      case "Down":
        if (onDecrement) {
          e2.preventDefault();
          onDecrement();
        }
        break;
      case "Home":
        if (onDecrementToMin) {
          e2.preventDefault();
          onDecrementToMin();
        }
        break;
      case "End":
        if (onIncrementToMax) {
          e2.preventDefault();
          onIncrementToMax();
        }
        break;
    }
  };
  let isFocused = useRef(false);
  let onFocus = () => {
    isFocused.current = true;
  };
  let onBlur = () => {
    isFocused.current = false;
  };
  textValue = textValue === "" ? formatMessage2("Empty") : (textValue || `${value}`).replace("-", "\u2212");
  useEffect(() => {
    if (isFocused.current)
      $9694eec57086f168$export$a9b970dcc4ae71a9(textValue, "assertive");
  }, [
    textValue
  ]);
  const onIncrementPressStart = useCallback((initialStepDelay) => {
    clearAsync();
    propsRef.current.onIncrement();
    _async.current = window.setTimeout(() => {
      if (isNaN(maxValue) || isNaN(value) || value < maxValue)
        onIncrementPressStart(60);
    }, initialStepDelay);
  }, [
    onIncrement,
    maxValue,
    value
  ]);
  const onDecrementPressStart = useCallback((initialStepDelay) => {
    clearAsync();
    propsRef.current.onDecrement();
    _async.current = window.setTimeout(() => {
      if (isNaN(minValue) || isNaN(value) || value > minValue)
        onDecrementPressStart(60);
    }, initialStepDelay);
  }, [
    onDecrement,
    minValue,
    value
  ]);
  let cancelContextMenu = (e2) => {
    e2.preventDefault();
  };
  let { addGlobalListener, removeAllGlobalListeners } = $03deb23ff14920c4$export$4eaf04e54aa8eed6();
  return {
    spinButtonProps: {
      role: "spinbutton",
      "aria-valuenow": !isNaN(value) ? value : null,
      "aria-valuetext": textValue,
      "aria-valuemin": minValue,
      "aria-valuemax": maxValue,
      "aria-disabled": isDisabled || null,
      "aria-readonly": isReadOnly || null,
      "aria-required": isRequired || null,
      onKeyDown,
      onFocus,
      onBlur
    },
    incrementButtonProps: {
      onPressStart: () => {
        onIncrementPressStart(400);
        addGlobalListener(window, "contextmenu", cancelContextMenu);
      },
      onPressEnd: () => {
        clearAsync();
        removeAllGlobalListeners();
      },
      onFocus,
      onBlur
    },
    decrementButtonProps: {
      onPressStart: () => {
        onDecrementPressStart(400);
        addGlobalListener(window, "contextmenu", cancelContextMenu);
      },
      onPressEnd: () => {
        clearAsync();
        removeAllGlobalListeners();
      },
      onFocus,
      onBlur
    }
  };
}
function $parcel$interopDefault(a2) {
  return a2 && a2.__esModule ? a2.default : a2;
}
function $parcel$export$e(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $cf0c3bd5e1672ec9$exports = {};
$parcel$export$e($cf0c3bd5e1672ec9$exports, "useNumberField", () => $cf0c3bd5e1672ec9$export$23f548e970bdf099);
var $2dbd11b99107b9a3$exports = {};
var $6549386043ae9318$exports = {};
$6549386043ae9318$exports = JSON.parse('{"decrease":"\u062E\u0641\u0636 {fieldLabel}","increase":"\u0632\u064A\u0627\u062F\u0629 {fieldLabel}","numberField":"\u062D\u0642\u0644 \u0631\u0642\u0645\u064A"}');
var $e76bce23c5e8423e$exports = {};
$e76bce23c5e8423e$exports = JSON.parse('{"decrease":"\u041D\u0430\u043C\u0430\u043B\u044F\u0432\u0430\u043D\u0435 {fieldLabel}","increase":"\u0423\u0441\u0438\u043B\u0432\u0430\u043D\u0435 {fieldLabel}","numberField":"\u041D\u043E\u043C\u0435\u0440 \u043D\u0430 \u043F\u043E\u043B\u0435\u0442\u043E"}');
var $6129a2a27a7967ba$exports = {};
$6129a2a27a7967ba$exports = JSON.parse('{"decrease":"Sn\xED\u017Eit {fieldLabel}","increase":"Zv\xFD\u0161it {fieldLabel}","numberField":"\u010C\xEDseln\xE9 pole"}');
var $52dac2657f2e7b91$exports = {};
$52dac2657f2e7b91$exports = JSON.parse('{"decrease":"Reducer {fieldLabel}","increase":"\xD8g {fieldLabel}","numberField":"Talfelt"}');
var $2d5c0936198b9a1d$exports = {};
$2d5c0936198b9a1d$exports = JSON.parse('{"decrease":"{fieldLabel} verringern","increase":"{fieldLabel} erh\xF6hen","numberField":"Nummernfeld"}');
var $037bbc3daaf1c938$exports = {};
$037bbc3daaf1c938$exports = JSON.parse('{"decrease":"\u039C\u03B5\u03AF\u03C9\u03C3\u03B7 {fieldLabel}","increase":"\u0391\u03CD\u03BE\u03B7\u03C3\u03B7 {fieldLabel}","numberField":"\u03A0\u03B5\u03B4\u03AF\u03BF \u03B1\u03C1\u03B9\u03B8\u03BC\u03BF\u03CD"}');
var $6f0e76066d1c5161$exports = {};
$6f0e76066d1c5161$exports = JSON.parse('{"decrease":"Decrease {fieldLabel}","increase":"Increase {fieldLabel}","numberField":"Number field"}');
var $ae410a5d2bee905f$exports = {};
$ae410a5d2bee905f$exports = JSON.parse('{"decrease":"Reducir {fieldLabel}","increase":"Aumentar {fieldLabel}","numberField":"Campo de n\xFAmero"}');
var $ba7e088ac7327440$exports = {};
$ba7e088ac7327440$exports = JSON.parse('{"decrease":"V\xE4henda {fieldLabel}","increase":"Suurenda {fieldLabel}","numberField":"Numbri v\xE4li"}');
var $16b3c05b733de903$exports = {};
$16b3c05b733de903$exports = JSON.parse('{"decrease":"V\xE4henn\xE4 {fieldLabel}","increase":"Lis\xE4\xE4 {fieldLabel}","numberField":"Numerokentt\xE4"}');
var $e8b2524c965f690e$exports = {};
$e8b2524c965f690e$exports = JSON.parse('{"decrease":"Diminuer {fieldLabel}","increase":"Augmenter {fieldLabel}","numberField":"Champ de nombre"}');
var $a6493a4a0eba3e94$exports = {};
$a6493a4a0eba3e94$exports = JSON.parse('{"decrease":"\u05D4\u05E7\u05D8\u05DF {fieldLabel}","increase":"\u05D4\u05D2\u05D3\u05DC {fieldLabel}","numberField":"\u05E9\u05D3\u05D4 \u05DE\u05E1\u05E4\u05E8"}');
var $fc83409ad17dbb8e$exports = {};
$fc83409ad17dbb8e$exports = JSON.parse('{"decrease":"Smanji {fieldLabel}","increase":"Pove\u0107aj {fieldLabel}","numberField":"Polje broja"}');
var $7fbda66289952e59$exports = {};
$7fbda66289952e59$exports = JSON.parse('{"decrease":"{fieldLabel} cs\xF6kkent\xE9se","increase":"{fieldLabel} n\xF6vel\xE9se","numberField":"Sz\xE1mmez\u0151"}');
var $0ca9c2faa64e1737$exports = {};
$0ca9c2faa64e1737$exports = JSON.parse('{"decrease":"Riduci {fieldLabel}","increase":"Aumenta {fieldLabel}","numberField":"Campo numero"}');
var $40b39fb57e4e01eb$exports = {};
$40b39fb57e4e01eb$exports = JSON.parse('{"decrease":"{fieldLabel}\u3092\u7E2E\u5C0F","increase":"{fieldLabel}\u3092\u62E1\u5927","numberField":"\u6570\u5024\u30D5\u30A3\u30FC\u30EB\u30C9"}');
var $eb43f79428829329$exports = {};
$eb43f79428829329$exports = JSON.parse('{"decrease":"{fieldLabel} \uAC10\uC18C","increase":"{fieldLabel} \uC99D\uAC00","numberField":"\uBC88\uD638 \uD544\uB4DC"}');
var $8716579631e81e6b$exports = {};
$8716579631e81e6b$exports = JSON.parse('{"decrease":"Suma\u017Einti {fieldLabel}","increase":"Padidinti {fieldLabel}","numberField":"Numerio laukas"}');
var $fb4343b9e8e55d54$exports = {};
$fb4343b9e8e55d54$exports = JSON.parse('{"decrease":"Samazin\u0101\u0161ana {fieldLabel}","increase":"Palielin\u0101\u0161ana {fieldLabel}","numberField":"Skait\u013Cu lauks"}');
var $e1efff358f8fa070$exports = {};
$e1efff358f8fa070$exports = JSON.parse('{"decrease":"Reduser {fieldLabel}","increase":"\xD8k {fieldLabel}","numberField":"Tallfelt"}');
var $78c91c3ffeb5bcda$exports = {};
$78c91c3ffeb5bcda$exports = JSON.parse('{"decrease":"{fieldLabel} verlagen","increase":"{fieldLabel} verhogen","numberField":"Getalveld"}');
var $847dfd0520968639$exports = {};
$847dfd0520968639$exports = JSON.parse('{"decrease":"Zmniejsz {fieldLabel}","increase":"Zwi\u0119ksz {fieldLabel}","numberField":"Pole numeru"}');
var $f4204c08266aeca6$exports = {};
$f4204c08266aeca6$exports = JSON.parse('{"decrease":"Diminuir {fieldLabel}","increase":"Aumentar {fieldLabel}","numberField":"Campo de n\xFAmero"}');
var $d500387cf5000fdc$exports = {};
$d500387cf5000fdc$exports = JSON.parse('{"decrease":"Diminuir {fieldLabel}","increase":"Aumentar {fieldLabel}","numberField":"Campo num\xE9rico"}');
var $ab2719432eedc1bf$exports = {};
$ab2719432eedc1bf$exports = JSON.parse('{"decrease":"Sc\u0103dere {fieldLabel}","increase":"Cre\u0219tere {fieldLabel}","numberField":"C\xE2mp numeric"}');
var $4bf211274c587106$exports = {};
$4bf211274c587106$exports = JSON.parse('{"decrease":"\u0423\u043C\u0435\u043D\u044C\u0448\u0435\u043D\u0438\u0435 {fieldLabel}","increase":"\u0423\u0432\u0435\u043B\u0438\u0447\u0435\u043D\u0438\u0435 {fieldLabel}","numberField":"\u0427\u0438\u0441\u043B\u043E\u0432\u043E\u0435 \u043F\u043E\u043B\u0435"}');
var $5951afc4ac07f078$exports = {};
$5951afc4ac07f078$exports = JSON.parse('{"decrease":"Zn\xED\u017Ei\u0165 {fieldLabel}","increase":"Zv\xFD\u0161i\u0165 {fieldLabel}","numberField":"\u010C\xEDseln\xE9 pole"}');
var $1340581fca173f3e$exports = {};
$1340581fca173f3e$exports = JSON.parse('{"decrease":"Upadati {fieldLabel}","increase":"Pove\u010Dajte {fieldLabel}","numberField":"\u0160tevil\u010Dno polje"}');
var $2b759d676253b2c8$exports = {};
$2b759d676253b2c8$exports = JSON.parse('{"decrease":"Decrease {fieldLabel}","increase":"Increase {fieldLabel}","numberField":"Number field"}');
var $b0c674a42fff90cb$exports = {};
$b0c674a42fff90cb$exports = JSON.parse('{"decrease":"Minska {fieldLabel}","increase":"\xD6ka {fieldLabel}","numberField":"Nummerf\xE4lt"}');
var $76371f1c7f27bc91$exports = {};
$76371f1c7f27bc91$exports = JSON.parse('{"decrease":"{fieldLabel} azalt","increase":"{fieldLabel} artt\u0131r","numberField":"Say\u0131 alan\u0131"}');
var $361acbd473fb967c$exports = {};
$361acbd473fb967c$exports = JSON.parse('{"decrease":"\u0417\u043C\u0435\u043D\u0448\u0438\u0442\u0438 {fieldLabel}","increase":"\u0417\u0431\u0456\u043B\u044C\u0448\u0438\u0442\u0438 {fieldLabel}","numberField":"\u041F\u043E\u043B\u0435 \u043D\u043E\u043C\u0435\u0440\u0430"}');
var $208c820c7d7354a7$exports = {};
$208c820c7d7354a7$exports = JSON.parse('{"decrease":"\u964D\u4F4E {fieldLabel}","increase":"\u63D0\u9AD8 {fieldLabel}","numberField":"\u6570\u5B57\u5B57\u6BB5"}');
var $e03c2cf780f9cea4$exports = {};
$e03c2cf780f9cea4$exports = JSON.parse('{"decrease":"\u7E2E\u5C0F {fieldLabel}","increase":"\u653E\u5927 {fieldLabel}","numberField":"\u6578\u5B57\u6B04\u4F4D"}');
$2dbd11b99107b9a3$exports = {
  "ar-AE": $6549386043ae9318$exports,
  "bg-BG": $e76bce23c5e8423e$exports,
  "cs-CZ": $6129a2a27a7967ba$exports,
  "da-DK": $52dac2657f2e7b91$exports,
  "de-DE": $2d5c0936198b9a1d$exports,
  "el-GR": $037bbc3daaf1c938$exports,
  "en-US": $6f0e76066d1c5161$exports,
  "es-ES": $ae410a5d2bee905f$exports,
  "et-EE": $ba7e088ac7327440$exports,
  "fi-FI": $16b3c05b733de903$exports,
  "fr-FR": $e8b2524c965f690e$exports,
  "he-IL": $a6493a4a0eba3e94$exports,
  "hr-HR": $fc83409ad17dbb8e$exports,
  "hu-HU": $7fbda66289952e59$exports,
  "it-IT": $0ca9c2faa64e1737$exports,
  "ja-JP": $40b39fb57e4e01eb$exports,
  "ko-KR": $eb43f79428829329$exports,
  "lt-LT": $8716579631e81e6b$exports,
  "lv-LV": $fb4343b9e8e55d54$exports,
  "nb-NO": $e1efff358f8fa070$exports,
  "nl-NL": $78c91c3ffeb5bcda$exports,
  "pl-PL": $847dfd0520968639$exports,
  "pt-BR": $f4204c08266aeca6$exports,
  "pt-PT": $d500387cf5000fdc$exports,
  "ro-RO": $ab2719432eedc1bf$exports,
  "ru-RU": $4bf211274c587106$exports,
  "sk-SK": $5951afc4ac07f078$exports,
  "sl-SI": $1340581fca173f3e$exports,
  "sr-SP": $2b759d676253b2c8$exports,
  "sv-SE": $b0c674a42fff90cb$exports,
  "tr-TR": $76371f1c7f27bc91$exports,
  "uk-UA": $361acbd473fb967c$exports,
  "zh-CN": $208c820c7d7354a7$exports,
  "zh-TW": $e03c2cf780f9cea4$exports
};
function $cf0c3bd5e1672ec9$export$23f548e970bdf099(props2, state2, inputRef) {
  let { id: id2, decrementAriaLabel, incrementAriaLabel, isDisabled, isReadOnly, isRequired, minValue, maxValue, autoFocus, validationState, label, formatOptions, onBlur, onFocus, onFocusChange, onKeyDown, onKeyUp, description, errorMessage } = props2;
  let { increment, incrementToMax, decrement, decrementToMin, numberValue, commit } = state2;
  const formatMessage2 = $321bc95feeb923dd$export$ec23bf898b1eed85(/* @__PURE__ */ $parcel$interopDefault($2dbd11b99107b9a3$exports));
  let inputId = $bdb11010cef70236$export$f680877a34711e37(id2);
  let { focusProps } = $a1ea59d68270f0dd$export$f8168d8dd8fd66e6({
    onBlur: () => {
      commit();
    }
  });
  let { spinButtonProps, incrementButtonProps: incButtonProps, decrementButtonProps: decButtonProps } = $7fc2c1269c209e7a$export$e908e06f4b8e3402({
    isDisabled,
    isReadOnly,
    isRequired,
    maxValue,
    minValue,
    onIncrement: increment,
    onIncrementToMax: incrementToMax,
    onDecrement: decrement,
    onDecrementToMin: decrementToMin,
    value: numberValue,
    textValue: state2.inputValue
  });
  let [focusWithin, setFocusWithin] = useState(false);
  let { focusWithinProps } = $9ab94262bd0047c7$export$420e68273165f4ec({
    isDisabled,
    onFocusWithinChange: setFocusWithin
  });
  let onWheel = useCallback((e2) => {
    if (Math.abs(e2.deltaY) <= Math.abs(e2.deltaX))
      return;
    if (e2.deltaY > 0)
      increment();
    else if (e2.deltaY < 0)
      decrement();
  }, [
    decrement,
    increment
  ]);
  let scrollingDisabled = isDisabled || isReadOnly || !focusWithin;
  $7d0a636d7a4dcefd$export$2123ff2b87c81ca({
    onScroll: onWheel,
    isDisabled: scrollingDisabled
  }, inputRef);
  let numberFormatter = $a916eb452884faea$export$b7a616150fdb9f44(formatOptions);
  let intlOptions = useMemo(() => numberFormatter.resolvedOptions(), [
    numberFormatter
  ]);
  let hasDecimals = intlOptions.maximumFractionDigits > 0;
  let hasNegative = isNaN(state2.minValue) || state2.minValue < 0;
  let inputMode = "numeric";
  if ($c87311424ea30a05$export$186c6964ca17d99()) {
    if (hasNegative)
      inputMode = "text";
    else if (hasDecimals)
      inputMode = "decimal";
  } else if ($c87311424ea30a05$export$a11b0059900ceec8()) {
    if (hasNegative)
      inputMode = "numeric";
    else if (hasDecimals)
      inputMode = "decimal";
  }
  let onChange = (value) => {
    state2.setInputValue(value);
  };
  let domProps = $65484d02dcb7eb3e$export$457c3d6518dd4c6f(props2);
  let { labelProps, inputProps: textFieldProps, descriptionProps, errorMessageProps } = $58c0262056d833d5$export$4f384c9210e583c3(__spreadProps(__spreadValues({}, domProps), {
    label,
    autoFocus,
    isDisabled,
    isReadOnly,
    isRequired,
    validationState,
    value: state2.inputValue,
    autoComplete: "off",
    "aria-label": props2["aria-label"] || null,
    "aria-labelledby": props2["aria-labelledby"] || null,
    id: inputId,
    type: "text",
    inputMode,
    onChange,
    onBlur,
    onFocus,
    onFocusChange,
    onKeyDown,
    onKeyUp,
    description,
    errorMessage
  }), state2, inputRef);
  let inputProps = $3ef42575df84b30b$export$9d1611c77c2fe928(spinButtonProps, textFieldProps, focusProps, {
    role: null,
    "aria-roledescription": !$c87311424ea30a05$export$fedb369cb70207f1() ? formatMessage2("numberField") : null,
    "aria-valuemax": null,
    "aria-valuemin": null,
    "aria-valuenow": null,
    "aria-valuetext": null,
    autoCorrect: "off",
    spellCheck: "false"
  });
  let onButtonPressStart = (e2) => {
    if (document.activeElement === inputRef.current)
      return;
    if (e2.pointerType === "mouse")
      inputRef.current.focus();
    else
      e2.target.focus();
  };
  let fieldLabel = props2["aria-label"] || (typeof props2.label === "string" ? props2.label : "");
  let ariaLabelledby;
  if (!fieldLabel)
    ariaLabelledby = props2.label != null ? labelProps.id : props2["aria-labelledby"];
  let incrementId2 = $bdb11010cef70236$export$f680877a34711e37();
  let decrementId = $bdb11010cef70236$export$f680877a34711e37();
  let incrementButtonProps = $3ef42575df84b30b$export$9d1611c77c2fe928(incButtonProps, {
    "aria-label": incrementAriaLabel || formatMessage2("increase", {
      fieldLabel
    }).trim(),
    id: ariaLabelledby && !incrementAriaLabel ? incrementId2 : null,
    "aria-labelledby": ariaLabelledby && !incrementAriaLabel ? `${incrementId2} ${ariaLabelledby}` : null,
    "aria-controls": inputId,
    excludeFromTabOrder: true,
    preventFocusOnPress: true,
    allowFocusWhenDisabled: true,
    isDisabled: !state2.canIncrement,
    onPressStart: onButtonPressStart
  });
  let decrementButtonProps = $3ef42575df84b30b$export$9d1611c77c2fe928(decButtonProps, {
    "aria-label": decrementAriaLabel || formatMessage2("decrease", {
      fieldLabel
    }).trim(),
    id: ariaLabelledby && !decrementAriaLabel ? decrementId : null,
    "aria-labelledby": ariaLabelledby && !decrementAriaLabel ? `${decrementId} ${ariaLabelledby}` : null,
    "aria-controls": inputId,
    excludeFromTabOrder: true,
    preventFocusOnPress: true,
    allowFocusWhenDisabled: true,
    isDisabled: !state2.canDecrement,
    onPressStart: onButtonPressStart
  });
  return {
    groupProps: __spreadValues({
      role: "group",
      "aria-disabled": isDisabled,
      "aria-invalid": validationState === "invalid" ? "true" : void 0
    }, focusWithinProps),
    labelProps,
    inputProps,
    incrementButtonProps,
    decrementButtonProps,
    errorMessageProps,
    descriptionProps
  };
}
function inputFieldStyle(props2) {
  const {
    size = "md",
    startAdornment,
    endAdornment,
    className,
    inline
  } = __spreadValues({}, props2);
  const sizeClass = inputSizeClass(size);
  return {
    label: clsx("block capitalize text-left", sizeClass.font, inline ? "mr-16" : "mb-4"),
    input: clsx("text-left relative focus:ring focus:ring-primary/focus focus:border-primary/60 block w-full bg-transparent border rounded focus:outline-none shadow-sm appearance-none transition-shadow", sizeClass.font, sizeClass.height, startAdornment ? "pl-36" : "pl-12", endAdornment ? "pr-36" : "pr-12"),
    adornment: getIconSizeStyle(size),
    wrapper: clsx(className, sizeClass.font, {
      "flex items-center": inline
    }),
    size: sizeClass
  };
}
const DEFAULT_INPUT_FONT_SIZE = "text-base";
function inputSizeClass(size) {
  switch (size) {
    case "xs":
      return {
        font: "text-xs",
        height: "h-30"
      };
    case "sm":
      return {
        font: "text-sm",
        height: "h-36"
      };
    case "lg":
      return {
        font: "text-lg",
        height: "h-50"
      };
    case "xl":
      return {
        font: "text-xl",
        height: "h-60"
      };
    default:
      return {
        font: DEFAULT_INPUT_FONT_SIZE,
        height: "h-42"
      };
  }
}
const KeyboardArrowUpIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M7.41 15.41 12 10.83l4.59 4.58L18 14l-6-6-6 6 1.41 1.41z"
}), "KeyboardArrowUpOutlined");
const KeyboardArrowDownIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M7.41 8.59 12 13.17l4.59-4.58L18 10l-6 6-6-6 1.41-1.41z"
}), "KeyboardArrowDownOutlined");
function NumberField(props2) {
  const {
    label
  } = props2;
  const {
    locale
  } = $18f2051aff69b9bf$export$43bb16f9c6d9e3f7();
  const style2 = inputFieldStyle(props2);
  const state2 = $9f327308a7d514e5$export$7f629e9dc1ecf37c(__spreadProps(__spreadValues({}, props2), {
    locale
  }));
  const inputRef = useRef(null);
  const {
    labelProps,
    groupProps,
    inputProps,
    incrementButtonProps,
    decrementButtonProps
  } = $cf0c3bd5e1672ec9$export$23f548e970bdf099(props2, state2, inputRef);
  return /* @__PURE__ */ jsxs("div", {
    className: style2.wrapper,
    children: [label && /* @__PURE__ */ jsx("label", __spreadProps(__spreadValues({
      className: style2.label
    }, labelProps), {
      children: label
    })), /* @__PURE__ */ jsxs("div", __spreadProps(__spreadValues({
      className: "relative"
    }, groupProps), {
      children: [/* @__PURE__ */ jsx("input", __spreadProps(__spreadValues({
        className: style2.input
      }, inputProps), {
        ref: inputRef
      })), /* @__PURE__ */ jsxs("div", {
        className: "absolute top-0 right-0 h-full flex flex-col items-center justify-center",
        children: [/* @__PURE__ */ jsx(StepButton, __spreadProps(__spreadValues({
          className: "border-b"
        }, incrementButtonProps), {
          children: /* @__PURE__ */ jsx(KeyboardArrowUpIcon, {})
        })), /* @__PURE__ */ jsx(StepButton, __spreadProps(__spreadValues({}, decrementButtonProps), {
          children: /* @__PURE__ */ jsx(KeyboardArrowDownIcon, {})
        }))]
      })]
    }))]
  });
}
function StepButton(_o) {
  var _p = _o, {
    children,
    className
  } = _p, other = __objRest(_p, [
    "children",
    "className"
  ]);
  const mergedClassName = clsx(className, "flex flex-auto items-center border-l px-2 disabled:text-disabled");
  return /* @__PURE__ */ jsx(IconButton, __spreadProps(__spreadValues({
    variant: null,
    radius: "rounded-none",
    className: mergedClassName
  }, other), {
    children
  }));
}
function CropInputFields() {
  const width = useStore$1((s2) => {
    var _a2;
    return (_a2 = s2.crop.zoneRect) == null ? void 0 : _a2.width;
  }) || 1;
  const height = useStore$1((s2) => {
    var _a2;
    return (_a2 = s2.crop.zoneRect) == null ? void 0 : _a2.height;
  }) || 1;
  const [formVal, setFormVal] = useState({
    width,
    height
  });
  useEffect(() => {
    const newWidth = Math.round(width / state().zoom);
    const newHeight = Math.round(height / state().zoom);
    setFormVal({
      width: newWidth,
      height: newHeight
    });
  }, [width, height]);
  const onInputChange = (value, dimension) => {
    const newValue = __spreadProps(__spreadValues({}, formVal), {
      [dimension]: value
    });
    setFormVal(newValue);
    onBlurAndSubmit(newValue);
  };
  const onBlurAndSubmit = (newValue) => {
    const value = newValue || formVal;
    resizeCropzone(value.width, value.height);
  };
  return /* @__PURE__ */ jsxs("form", {
    className: "flex items-center gap-12",
    onSubmit: (e2) => {
      e2.preventDefault();
      onBlurAndSubmit();
    },
    children: [/* @__PURE__ */ jsx(NumberField, {
      size: "xs",
      "aria-label": "Crop width",
      endAdornment: /* @__PURE__ */ jsx("div", {
        className: "text-muted font-bold text-xs",
        children: /* @__PURE__ */ jsx(FormattedMessage$1, {
          id: "zRkzP5",
          defaultMessage: [{
            "type": 0,
            "value": "W"
          }]
        })
      }),
      minValue: 1,
      className: "w-80",
      value: formVal.width,
      formatOptions: {
        useGrouping: false
      },
      onChange: (value) => {
        onInputChange(value, "width");
      }
    }), /* @__PURE__ */ jsx(NumberField, {
      size: "xs",
      "aria-label": "Crop height",
      endAdornment: /* @__PURE__ */ jsx("div", {
        className: "text-muted font-bold text-xs",
        children: /* @__PURE__ */ jsx(FormattedMessage$1, {
          id: "wFvZzh",
          defaultMessage: [{
            "type": 0,
            "value": "H"
          }]
        })
      }),
      minValue: 1,
      className: "w-80",
      value: formVal.height,
      formatOptions: {
        useGrouping: false
      },
      onChange: (value) => {
        onInputChange(value, "height");
      }
    }), /* @__PURE__ */ jsx("button", {
      type: "submit",
      className: "hidden",
      children: /* @__PURE__ */ jsx(FormattedMessage$1, {
        id: "4dL9o7",
        defaultMessage: [{
          "type": 0,
          "value": "Resize"
        }]
      })
    })]
  });
}
function resizeCropzone(width, height) {
  const interactable = tools().crop.zone;
  if (!state().crop.zoneRect || !interactable)
    return;
  const newRect = __spreadProps(__spreadValues({}, state().crop.zoneRect), {
    width: Math.round(Math.min(state().original.width, width) * state().zoom),
    height: Math.round(Math.min(state().original.height, height) * state().zoom)
  });
  const resizeAction = interactable.config.actions.find((a2) => a2 instanceof ResizeAction);
  if (resizeAction && newRect.width !== interactable.currentRect.width || newRect.height !== interactable.currentRect.height) {
    interactable.executeAction(resizeAction, {}, newRect);
  }
}
const CheckIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M9 16.17 4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z"
}), "CheckOutlined");
function ActiveToolbar() {
  const activeTool = useStore$1((s2) => s2.activeTool);
  return /* @__PURE__ */ jsxs(m$2.div, __spreadProps(__spreadValues({
    className: toolbarStyle
  }, toolbarAnimation), {
    children: [/* @__PURE__ */ jsx(CancelButton, {}), getToolName(activeTool), /* @__PURE__ */ jsx(ApplyButton, {})]
  }));
}
function CancelButton() {
  const {
    isMobile
  } = useEditorMode();
  const isDirty = useStore$1((s2) => s2.dirty);
  if (isMobile) {
    return /* @__PURE__ */ jsx(IconButton, {
      size: "sm",
      onPress: () => {
        state().cancelChanges();
      },
      children: /* @__PURE__ */ jsx(CloseIcon, {})
    });
  }
  return /* @__PURE__ */ jsx(Button, {
    variant: "outline",
    size: "xs",
    startIcon: /* @__PURE__ */ jsx(CloseIcon, {}),
    radius: "rounded-full",
    onPress: () => {
      state().cancelChanges();
    },
    children: isDirty ? /* @__PURE__ */ jsx(FormattedMessage$1, {
      id: "47FYwb",
      defaultMessage: [{
        "type": 0,
        "value": "Cancel"
      }]
    }) : /* @__PURE__ */ jsx(FormattedMessage$1, {
      id: "rbrahO",
      defaultMessage: [{
        "type": 0,
        "value": "Close"
      }]
    })
  });
}
function getToolName(toolName) {
  var _a2, _b, _c;
  const defaultCmp = /* @__PURE__ */ jsx("div", {
    className: "capitalize text-sm",
    children: toolName
  });
  switch (toolName) {
    case ToolName.CROP: {
      const allowCustom = (_c = (_b = (_a2 = state().config.tools) == null ? void 0 : _a2.crop) == null ? void 0 : _b.allowCustomRatio) != null ? _c : true;
      if (allowCustom) {
        return /* @__PURE__ */ jsx(CropInputFields, {});
      }
      return defaultCmp;
    }
    default:
      return defaultCmp;
  }
}
function ApplyButton() {
  const {
    isMobile
  } = useEditorMode();
  const isDirty = useStore$1((s2) => s2.dirty);
  if (isMobile) {
    return /* @__PURE__ */ jsx(IconButton, {
      size: "sm",
      isDisabled: !isDirty,
      onPress: () => {
        state().applyChanges();
      },
      children: /* @__PURE__ */ jsx(CheckIcon, {})
    });
  }
  return /* @__PURE__ */ jsx(Button, {
    variant: "flat",
    color: "primary",
    size: "xs",
    isDisabled: !isDirty,
    startIcon: /* @__PURE__ */ jsx(CheckIcon, {}),
    radius: "rounded-full",
    onPress: () => {
      state().applyChanges();
    },
    children: /* @__PURE__ */ jsx(FormattedMessage$1, {
      id: "EWw/tK",
      defaultMessage: [{
        "type": 0,
        "value": "Apply"
      }]
    })
  });
}
function ToolbarContainer() {
  const activeTool = useStore$1((s2) => s2.activeTool);
  return /* @__PURE__ */ jsx(AnimatePresence, {
    initial: false,
    children: activeTool ? /* @__PURE__ */ jsx(ActiveToolbar, {}, "activeToolbar") : /* @__PURE__ */ jsx(MainToolbar, {}, "mainToolbar")
  });
}
const messages = defineMessages({
  newCanvas: {
    id: "34ELdR",
    defaultMessage: [{
      "type": 0,
      "value": "Loading Canvas"
    }]
  },
  mainImage: {
    id: "ymTE9v",
    defaultMessage: [{
      "type": 0,
      "value": "Loading Image"
    }]
  },
  state: {
    id: "AmIZUR",
    defaultMessage: [{
      "type": 0,
      "value": "Loading State"
    }]
  },
  merge: {
    id: "zP9AYY",
    defaultMessage: [{
      "type": 0,
      "value": "Processing Image"
    }]
  }
});
function LoadingIndicator() {
  const [activeLoadState, setActiveLoadState] = useState(false);
  useEffect(() => {
    useStore$1.subscribe((s2) => s2.loading, (loadState) => {
      if (loadState) {
        setActiveLoadState(loadState);
      }
    });
  }, []);
  return /* @__PURE__ */ jsx(AnimatePresence, {
    children: activeLoadState && /* @__PURE__ */ jsx(m$2.div, {
      initial: {
        y: "60%",
        opacity: 0
      },
      animate: {
        y: 0,
        opacity: 1
      },
      exit: {
        y: "-60%",
        opacity: 0
      },
      transition: {
        type: "tween",
        duration: 0.3
      },
      onAnimationComplete: () => {
        setTimeout(() => {
          setActiveLoadState(false);
        }, 400);
      },
      className: "absolute z-loading-indicator inset-0 m-auto p-6 w-144 h-32 text-center text-sm bg-paper rounded-full shadow-lg",
      children: /* @__PURE__ */ jsx(FormattedMessage$1, __spreadValues({}, messages[activeLoadState]))
    })
  });
}
function clamp(v2, min, max) {
  return Math.max(min, Math.min(v2, max));
}
const V$1 = {
  toVector(v2, fallback) {
    if (v2 === void 0)
      v2 = fallback;
    return Array.isArray(v2) ? v2 : [v2, v2];
  },
  add(v1, v2) {
    return [v1[0] + v2[0], v1[1] + v2[1]];
  },
  sub(v1, v2) {
    return [v1[0] - v2[0], v1[1] - v2[1]];
  },
  addTo(v1, v2) {
    v1[0] += v2[0];
    v1[1] += v2[1];
  },
  subTo(v1, v2) {
    v1[0] -= v2[0];
    v1[1] -= v2[1];
  }
};
function rubberband(distance, dimension, constant) {
  if (dimension === 0 || Math.abs(dimension) === Infinity)
    return Math.pow(distance, constant * 5);
  return distance * dimension * constant / (dimension + constant * distance);
}
function rubberbandIfOutOfBounds(position2, min, max, constant = 0.15) {
  if (constant === 0)
    return clamp(position2, min, max);
  if (position2 < min)
    return -rubberband(min - position2, max - min, constant) + min;
  if (position2 > max)
    return +rubberband(position2 - max, max - min, constant) + max;
  return position2;
}
function computeRubberband(bounds, [Vx, Vy], [Rx, Ry]) {
  const [[X0, X1], [Y0, Y1]] = bounds;
  return [rubberbandIfOutOfBounds(Vx, X0, X1, Rx), rubberbandIfOutOfBounds(Vy, Y0, Y1, Ry)];
}
function _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }
  return obj;
}
function ownKeys(object, enumerableOnly) {
  var keys = Object.keys(object);
  if (Object.getOwnPropertySymbols) {
    var symbols = Object.getOwnPropertySymbols(object);
    enumerableOnly && (symbols = symbols.filter(function(sym) {
      return Object.getOwnPropertyDescriptor(object, sym).enumerable;
    })), keys.push.apply(keys, symbols);
  }
  return keys;
}
function _objectSpread2(target) {
  for (var i2 = 1; i2 < arguments.length; i2++) {
    var source = arguments[i2] != null ? arguments[i2] : {};
    i2 % 2 ? ownKeys(Object(source), true).forEach(function(key) {
      _defineProperty(target, key, source[key]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) {
      Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
    });
  }
  return target;
}
const EVENT_TYPE_MAP = {
  pointer: {
    start: "down",
    change: "move",
    end: "up"
  },
  mouse: {
    start: "down",
    change: "move",
    end: "up"
  },
  touch: {
    start: "start",
    change: "move",
    end: "end"
  },
  gesture: {
    start: "start",
    change: "change",
    end: "end"
  }
};
function capitalize(string) {
  if (!string)
    return "";
  return string[0].toUpperCase() + string.slice(1);
}
function toHandlerProp(device, action = "", capture = false) {
  const deviceProps = EVENT_TYPE_MAP[device];
  const actionKey = deviceProps ? deviceProps[action] || action : action;
  return "on" + capitalize(device) + capitalize(actionKey) + (capture ? "Capture" : "");
}
const pointerCaptureEvents = ["gotpointercapture", "lostpointercapture"];
function parseProp(prop) {
  let eventKey = prop.substring(2).toLowerCase();
  const passive = !!~eventKey.indexOf("passive");
  if (passive)
    eventKey = eventKey.replace("passive", "");
  const captureKey = pointerCaptureEvents.includes(eventKey) ? "capturecapture" : "capture";
  const capture = !!~eventKey.indexOf(captureKey);
  if (capture)
    eventKey = eventKey.replace("capture", "");
  return {
    device: eventKey,
    capture,
    passive
  };
}
function toDomEventType(device, action = "") {
  const deviceProps = EVENT_TYPE_MAP[device];
  const actionKey = deviceProps ? deviceProps[action] || action : action;
  return device + actionKey;
}
function isTouch(event) {
  return "touches" in event;
}
function getCurrentTargetTouchList(event) {
  return Array.from(event.touches).filter((e2) => {
    var _event$currentTarget, _event$currentTarget$;
    return e2.target === event.currentTarget || ((_event$currentTarget = event.currentTarget) === null || _event$currentTarget === void 0 ? void 0 : (_event$currentTarget$ = _event$currentTarget.contains) === null || _event$currentTarget$ === void 0 ? void 0 : _event$currentTarget$.call(_event$currentTarget, e2.target));
  });
}
function getTouchList(event) {
  return event.type === "touchend" || event.type === "touchcancel" ? event.changedTouches : event.targetTouches;
}
function getValueEvent(event) {
  return isTouch(event) ? getTouchList(event)[0] : event;
}
function distanceAngle(P1, P2) {
  const dx = P2.clientX - P1.clientX;
  const dy = P2.clientY - P1.clientY;
  const cx = (P2.clientX + P1.clientX) / 2;
  const cy = (P2.clientY + P1.clientY) / 2;
  const distance = Math.hypot(dx, dy);
  const angle = -(Math.atan2(dx, dy) * 180) / Math.PI;
  const origin = [cx, cy];
  return {
    angle,
    distance,
    origin
  };
}
function touchIds(event) {
  return getCurrentTargetTouchList(event).map((touch) => touch.identifier);
}
function touchDistanceAngle(event, ids) {
  const [P1, P2] = Array.from(event.touches).filter((touch) => ids.includes(touch.identifier));
  return distanceAngle(P1, P2);
}
function pointerId(event) {
  const valueEvent = getValueEvent(event);
  return isTouch(event) ? valueEvent.identifier : valueEvent.pointerId;
}
function pointerValues(event) {
  const valueEvent = getValueEvent(event);
  return [valueEvent.clientX, valueEvent.clientY];
}
const LINE_HEIGHT = 40;
const PAGE_HEIGHT = 800;
function wheelValues(event) {
  let {
    deltaX,
    deltaY,
    deltaMode
  } = event;
  if (deltaMode === 1) {
    deltaX *= LINE_HEIGHT;
    deltaY *= LINE_HEIGHT;
  } else if (deltaMode === 2) {
    deltaX *= PAGE_HEIGHT;
    deltaY *= PAGE_HEIGHT;
  }
  return [deltaX, deltaY];
}
function getEventDetails(event) {
  const payload = {};
  if ("buttons" in event)
    payload.buttons = event.buttons;
  if ("shiftKey" in event) {
    const {
      shiftKey,
      altKey,
      metaKey,
      ctrlKey
    } = event;
    Object.assign(payload, {
      shiftKey,
      altKey,
      metaKey,
      ctrlKey
    });
  }
  return payload;
}
function call(v2, ...args) {
  if (typeof v2 === "function") {
    return v2(...args);
  } else {
    return v2;
  }
}
function noop() {
}
function chain(...fns) {
  if (fns.length === 0)
    return noop;
  if (fns.length === 1)
    return fns[0];
  return function() {
    let result;
    for (const fn2 of fns) {
      result = fn2.apply(this, arguments) || result;
    }
    return result;
  };
}
function assignDefault(value, fallback) {
  return Object.assign({}, fallback, value || {});
}
const BEFORE_LAST_KINEMATICS_DELAY = 32;
class Engine {
  constructor(ctrl, args, key) {
    this.ctrl = ctrl;
    this.args = args;
    this.key = key;
    if (!this.state) {
      this.state = {};
      this.computeValues([0, 0]);
      this.computeInitial();
      if (this.init)
        this.init();
      this.reset();
    }
  }
  get state() {
    return this.ctrl.state[this.key];
  }
  set state(state2) {
    this.ctrl.state[this.key] = state2;
  }
  get shared() {
    return this.ctrl.state.shared;
  }
  get eventStore() {
    return this.ctrl.gestureEventStores[this.key];
  }
  get timeoutStore() {
    return this.ctrl.gestureTimeoutStores[this.key];
  }
  get config() {
    return this.ctrl.config[this.key];
  }
  get sharedConfig() {
    return this.ctrl.config.shared;
  }
  get handler() {
    return this.ctrl.handlers[this.key];
  }
  reset() {
    const {
      state: state2,
      shared,
      ingKey,
      args
    } = this;
    shared[ingKey] = state2._active = state2.active = state2._blocked = state2._force = false;
    state2._step = [false, false];
    state2.intentional = false;
    state2._movement = [0, 0];
    state2._distance = [0, 0];
    state2._direction = [0, 0];
    state2._delta = [0, 0];
    state2._bounds = [[-Infinity, Infinity], [-Infinity, Infinity]];
    state2.args = args;
    state2.axis = void 0;
    state2.memo = void 0;
    state2.elapsedTime = 0;
    state2.direction = [0, 0];
    state2.distance = [0, 0];
    state2.overflow = [0, 0];
    state2._movementBound = [false, false];
    state2.velocity = [0, 0];
    state2.movement = [0, 0];
    state2.delta = [0, 0];
    state2.timeStamp = 0;
  }
  start(event) {
    const state2 = this.state;
    const config = this.config;
    if (!state2._active) {
      this.reset();
      this.computeInitial();
      state2._active = true;
      state2.target = event.target;
      state2.currentTarget = event.currentTarget;
      state2.lastOffset = config.from ? call(config.from, state2) : state2.offset;
      state2.offset = state2.lastOffset;
    }
    state2.startTime = state2.timeStamp = event.timeStamp;
  }
  computeValues(values) {
    const state2 = this.state;
    state2._values = values;
    state2.values = this.config.transform(values);
  }
  computeInitial() {
    const state2 = this.state;
    state2._initial = state2._values;
    state2.initial = state2.values;
  }
  compute(event) {
    const {
      state: state2,
      config,
      shared
    } = this;
    state2.args = this.args;
    let dt = 0;
    if (event) {
      state2.event = event;
      if (config.preventDefault && event.cancelable)
        state2.event.preventDefault();
      state2.type = event.type;
      shared.touches = this.ctrl.pointerIds.size || this.ctrl.touchIds.size;
      shared.locked = !!document.pointerLockElement;
      Object.assign(shared, getEventDetails(event));
      shared.down = shared.pressed = shared.buttons % 2 === 1 || shared.touches > 0;
      dt = event.timeStamp - state2.timeStamp;
      state2.timeStamp = event.timeStamp;
      state2.elapsedTime = state2.timeStamp - state2.startTime;
    }
    if (state2._active) {
      const _absoluteDelta = state2._delta.map(Math.abs);
      V$1.addTo(state2._distance, _absoluteDelta);
    }
    const [_m0, _m1] = state2._movement;
    const [t0, t1] = config.threshold;
    const {
      _step,
      values
    } = state2;
    if (config.hasCustomTransform) {
      if (_step[0] === false)
        _step[0] = Math.abs(_m0) >= t0 && values[0];
      if (_step[1] === false)
        _step[1] = Math.abs(_m1) >= t1 && values[1];
    } else {
      if (_step[0] === false)
        _step[0] = Math.abs(_m0) >= t0 && Math.sign(_m0) * t0;
      if (_step[1] === false)
        _step[1] = Math.abs(_m1) >= t1 && Math.sign(_m1) * t1;
    }
    state2.intentional = _step[0] !== false || _step[1] !== false;
    if (!state2.intentional)
      return;
    const movement = [0, 0];
    if (config.hasCustomTransform) {
      const [v0, v1] = values;
      movement[0] = _step[0] !== false ? v0 - _step[0] : 0;
      movement[1] = _step[1] !== false ? v1 - _step[1] : 0;
    } else {
      movement[0] = _step[0] !== false ? _m0 - _step[0] : 0;
      movement[1] = _step[1] !== false ? _m1 - _step[1] : 0;
    }
    if (this.intent)
      this.intent(movement);
    if (state2._active && !state2._blocked || state2.active) {
      state2.first = state2._active && !state2.active;
      state2.last = !state2._active && state2.active;
      state2.active = shared[this.ingKey] = state2._active;
      if (event) {
        if (state2.first) {
          if ("bounds" in config)
            state2._bounds = call(config.bounds, state2);
          if (this.setup)
            this.setup();
        }
        state2.movement = movement;
        const previousOffset = state2.offset;
        this.computeOffset();
        if (!state2.last || dt > BEFORE_LAST_KINEMATICS_DELAY) {
          state2.delta = V$1.sub(state2.offset, previousOffset);
          const absoluteDelta = state2.delta.map(Math.abs);
          V$1.addTo(state2.distance, absoluteDelta);
          state2.direction = state2.delta.map(Math.sign);
          state2._direction = state2._delta.map(Math.sign);
          if (!state2.first && dt > 0) {
            state2.velocity = [absoluteDelta[0] / dt, absoluteDelta[1] / dt];
          }
        }
      }
    }
    const [ox, oy] = state2.offset;
    const [[x0, x1], [y0, y1]] = state2._bounds;
    state2.overflow = [ox < x0 ? -1 : ox > x1 ? 1 : 0, oy < y0 ? -1 : oy > y1 ? 1 : 0];
    state2._movementBound[0] = state2.overflow[0] ? state2._movementBound[0] === false ? state2._movement[0] : state2._movementBound[0] : false;
    state2._movementBound[1] = state2.overflow[1] ? state2._movementBound[1] === false ? state2._movement[1] : state2._movementBound[1] : false;
    const rubberband2 = state2._active ? config.rubberband || [0, 0] : [0, 0];
    state2.offset = computeRubberband(state2._bounds, state2.offset, rubberband2);
    this.computeMovement();
  }
  emit() {
    const state2 = this.state;
    const shared = this.shared;
    const config = this.config;
    if (!state2._active)
      this.clean();
    if ((state2._blocked || !state2.intentional) && !state2._force && !config.triggerAllEvents)
      return;
    const memo = this.handler(_objectSpread2(_objectSpread2(_objectSpread2({}, shared), state2), {}, {
      [this.aliasKey]: state2.values
    }));
    if (memo !== void 0)
      state2.memo = memo;
  }
  clean() {
    this.eventStore.clean();
    this.timeoutStore.clean();
  }
}
function selectAxis([dx, dy]) {
  const d2 = Math.abs(dx) - Math.abs(dy);
  if (d2 > 0)
    return "x";
  if (d2 < 0)
    return "y";
  return void 0;
}
function restrictVectorToAxis(v2, axis) {
  switch (axis) {
    case "x":
      v2[1] = 0;
      break;
    case "y":
      v2[0] = 0;
      break;
  }
}
class CoordinatesEngine extends Engine {
  constructor(...args) {
    super(...args);
    _defineProperty(this, "aliasKey", "xy");
  }
  reset() {
    super.reset();
    this.state.axis = void 0;
  }
  init() {
    this.state.offset = [0, 0];
    this.state.lastOffset = [0, 0];
  }
  computeOffset() {
    this.state.offset = V$1.add(this.state.lastOffset, this.state.movement);
  }
  computeMovement() {
    this.state.movement = V$1.sub(this.state.offset, this.state.lastOffset);
  }
  intent(v2) {
    this.state.axis = this.state.axis || selectAxis(v2);
    this.state._blocked = (this.config.lockDirection || !!this.config.axis) && !this.state.axis || !!this.config.axis && this.config.axis !== this.state.axis;
    if (this.state._blocked)
      return;
    if (this.config.axis || this.config.lockDirection) {
      restrictVectorToAxis(v2, this.state.axis);
    }
  }
}
const identity = (v2) => v2;
const DEFAULT_RUBBERBAND = 0.15;
const commonConfigResolver = {
  enabled(value = true) {
    return value;
  },
  preventDefault(value = false) {
    return value;
  },
  triggerAllEvents(value = false) {
    return value;
  },
  rubberband(value = 0) {
    switch (value) {
      case true:
        return [DEFAULT_RUBBERBAND, DEFAULT_RUBBERBAND];
      case false:
        return [0, 0];
      default:
        return V$1.toVector(value);
    }
  },
  from(value) {
    if (typeof value === "function")
      return value;
    if (value != null)
      return V$1.toVector(value);
  },
  transform(value, _k, config) {
    const transform2 = value || config.shared.transform;
    this.hasCustomTransform = !!transform2;
    return transform2 || identity;
  },
  threshold(value) {
    return V$1.toVector(value, 0);
  }
};
const coordinatesConfigResolver = _objectSpread2(_objectSpread2({}, commonConfigResolver), {}, {
  axis(_v, _k, {
    axis
  }) {
    this.lockDirection = axis === "lock";
    if (!this.lockDirection)
      return axis;
  },
  bounds(value = {}) {
    if (typeof value === "function") {
      return (state2) => coordinatesConfigResolver.bounds(value(state2));
    }
    if ("current" in value) {
      return () => value.current;
    }
    if (typeof HTMLElement === "function" && value instanceof HTMLElement) {
      return value;
    }
    const {
      left = -Infinity,
      right = Infinity,
      top = -Infinity,
      bottom = Infinity
    } = value;
    return [[left, right], [top, bottom]];
  }
});
const DISPLACEMENT = 10;
const KEYS_DELTA_MAP = {
  ArrowRight: (factor = 1) => [DISPLACEMENT * factor, 0],
  ArrowLeft: (factor = 1) => [-DISPLACEMENT * factor, 0],
  ArrowUp: (factor = 1) => [0, -DISPLACEMENT * factor],
  ArrowDown: (factor = 1) => [0, DISPLACEMENT * factor]
};
class DragEngine extends CoordinatesEngine {
  constructor(...args) {
    super(...args);
    _defineProperty(this, "ingKey", "dragging");
  }
  reset() {
    super.reset();
    const state2 = this.state;
    state2._pointerId = void 0;
    state2._pointerActive = false;
    state2._keyboardActive = false;
    state2._preventScroll = false;
    state2._delayed = false;
    state2.swipe = [0, 0];
    state2.tap = false;
    state2.canceled = false;
    state2.cancel = this.cancel.bind(this);
  }
  setup() {
    const state2 = this.state;
    if (state2._bounds instanceof HTMLElement) {
      const boundRect = state2._bounds.getBoundingClientRect();
      const targetRect = state2.currentTarget.getBoundingClientRect();
      const _bounds = {
        left: boundRect.left - targetRect.left + state2.offset[0],
        right: boundRect.right - targetRect.right + state2.offset[0],
        top: boundRect.top - targetRect.top + state2.offset[1],
        bottom: boundRect.bottom - targetRect.bottom + state2.offset[1]
      };
      state2._bounds = coordinatesConfigResolver.bounds(_bounds);
    }
  }
  cancel() {
    const state2 = this.state;
    if (state2.canceled)
      return;
    state2.canceled = true;
    state2._active = false;
    setTimeout(() => {
      this.compute();
      this.emit();
    }, 0);
  }
  setActive() {
    this.state._active = this.state._pointerActive || this.state._keyboardActive;
  }
  clean() {
    this.pointerClean();
    this.state._pointerActive = false;
    this.state._keyboardActive = false;
    super.clean();
  }
  pointerDown(event) {
    const config = this.config;
    const state2 = this.state;
    if (event.buttons != null && (Array.isArray(config.pointerButtons) ? !config.pointerButtons.includes(event.buttons) : config.pointerButtons !== -1 && config.pointerButtons !== event.buttons))
      return;
    this.ctrl.setEventIds(event);
    if (config.pointerCapture) {
      event.target.setPointerCapture(event.pointerId);
    }
    if (state2._pointerActive)
      return;
    this.start(event);
    this.setupPointer(event);
    state2._pointerId = pointerId(event);
    state2._pointerActive = true;
    this.computeValues(pointerValues(event));
    this.computeInitial();
    if (config.preventScroll) {
      this.setupScrollPrevention(event);
    } else if (config.delay > 0) {
      this.setupDelayTrigger(event);
    } else {
      this.startPointerDrag(event);
    }
  }
  startPointerDrag(event) {
    const state2 = this.state;
    state2._active = true;
    state2._preventScroll = true;
    state2._delayed = false;
    this.compute(event);
    this.emit();
  }
  pointerMove(event) {
    const state2 = this.state;
    const config = this.config;
    if (!state2._pointerActive)
      return;
    if (state2.type === event.type && event.timeStamp === state2.timeStamp)
      return;
    const id2 = pointerId(event);
    if (state2._pointerId && id2 !== state2._pointerId)
      return;
    const _values = pointerValues(event);
    if (document.pointerLockElement === event.target) {
      state2._delta = [event.movementX, event.movementY];
    } else {
      state2._delta = V$1.sub(_values, state2._values);
      this.computeValues(_values);
    }
    V$1.addTo(state2._movement, state2._delta);
    this.compute(event);
    if (state2._delayed) {
      this.timeoutStore.remove("dragDelay");
      state2.active = false;
      this.startPointerDrag(event);
      return;
    }
    if (config.preventScroll && !state2._preventScroll) {
      if (state2.axis) {
        if (state2.axis === config.preventScrollAxis || config.preventScrollAxis === "xy") {
          state2._active = false;
          this.clean();
          return;
        } else {
          this.timeoutStore.remove("startPointerDrag");
          this.startPointerDrag(event);
          return;
        }
      } else {
        return;
      }
    }
    this.emit();
  }
  pointerUp(event) {
    this.ctrl.setEventIds(event);
    try {
      if (this.config.pointerCapture && event.target.hasPointerCapture(event.pointerId)) {
        ;
        event.target.releasePointerCapture(event.pointerId);
      }
    } catch (_unused) {
    }
    const state2 = this.state;
    const config = this.config;
    if (!state2._pointerActive)
      return;
    const id2 = pointerId(event);
    if (state2._pointerId && id2 !== state2._pointerId)
      return;
    this.state._pointerActive = false;
    this.setActive();
    this.compute(event);
    const [dx, dy] = state2._distance;
    state2.tap = dx <= config.tapsThreshold && dy <= config.tapsThreshold;
    if (state2.tap && config.filterTaps) {
      state2._force = true;
    } else {
      const [dirx, diry] = state2.direction;
      const [vx, vy] = state2.velocity;
      const [mx, my] = state2.movement;
      const [svx, svy] = config.swipe.velocity;
      const [sx, sy] = config.swipe.distance;
      const sdt = config.swipe.duration;
      if (state2.elapsedTime < sdt) {
        if (Math.abs(vx) > svx && Math.abs(mx) > sx)
          state2.swipe[0] = dirx;
        if (Math.abs(vy) > svy && Math.abs(my) > sy)
          state2.swipe[1] = diry;
      }
    }
    this.emit();
  }
  pointerClick(event) {
    if (!this.state.tap) {
      event.preventDefault();
      event.stopPropagation();
    }
  }
  setupPointer(event) {
    const config = this.config;
    let device = config.device;
    if (config.pointerLock) {
      event.currentTarget.requestPointerLock();
    }
    if (!config.pointerCapture) {
      this.eventStore.add(this.sharedConfig.window, device, "change", this.pointerMove.bind(this));
      this.eventStore.add(this.sharedConfig.window, device, "end", this.pointerUp.bind(this));
      this.eventStore.add(this.sharedConfig.window, device, "cancel", this.pointerUp.bind(this));
    }
  }
  pointerClean() {
    if (this.config.pointerLock && document.pointerLockElement === this.state.currentTarget) {
      document.exitPointerLock();
    }
  }
  preventScroll(event) {
    if (this.state._preventScroll && event.cancelable) {
      event.preventDefault();
    }
  }
  setupScrollPrevention(event) {
    persistEvent(event);
    this.eventStore.add(this.sharedConfig.window, "touch", "change", this.preventScroll.bind(this), {
      passive: false
    });
    this.eventStore.add(this.sharedConfig.window, "touch", "end", this.clean.bind(this), {
      passive: false
    });
    this.eventStore.add(this.sharedConfig.window, "touch", "cancel", this.clean.bind(this), {
      passive: false
    });
    this.timeoutStore.add("startPointerDrag", this.startPointerDrag.bind(this), this.config.preventScroll, event);
  }
  setupDelayTrigger(event) {
    this.state._delayed = true;
    this.timeoutStore.add("dragDelay", this.startPointerDrag.bind(this), this.config.delay, event);
  }
  keyDown(event) {
    const deltaFn = KEYS_DELTA_MAP[event.key];
    if (deltaFn) {
      const state2 = this.state;
      const factor = event.shiftKey ? 10 : event.altKey ? 0.1 : 1;
      state2._delta = deltaFn(factor);
      this.start(event);
      state2._keyboardActive = true;
      V$1.addTo(state2._movement, state2._delta);
      this.compute(event);
      this.emit();
    }
  }
  keyUp(event) {
    if (!(event.key in KEYS_DELTA_MAP))
      return;
    this.state._keyboardActive = false;
    this.setActive();
    this.compute(event);
    this.emit();
  }
  bind(bindFunction) {
    const device = this.config.device;
    bindFunction(device, "start", this.pointerDown.bind(this));
    if (this.config.pointerCapture) {
      bindFunction(device, "change", this.pointerMove.bind(this));
      bindFunction(device, "end", this.pointerUp.bind(this));
      bindFunction(device, "cancel", this.pointerUp.bind(this));
      bindFunction("lostPointerCapture", "", this.pointerUp.bind(this));
    }
    bindFunction("key", "down", this.keyDown.bind(this));
    bindFunction("key", "up", this.keyUp.bind(this));
    if (this.config.filterTaps) {
      bindFunction("click", "", this.pointerClick.bind(this), {
        capture: true,
        passive: false
      });
    }
  }
}
function persistEvent(event) {
  "persist" in event && typeof event.persist === "function" && event.persist();
}
const isBrowser = typeof window !== "undefined" && window.document && window.document.createElement;
function supportsTouchEvents() {
  return isBrowser && "ontouchstart" in window;
}
function isTouchScreen() {
  return supportsTouchEvents() || isBrowser && window.navigator.maxTouchPoints > 1;
}
function supportsPointerEvents() {
  return isBrowser && "onpointerdown" in window;
}
function supportsPointerLock() {
  return isBrowser && "exitPointerLock" in window.document;
}
function supportsGestureEvents() {
  try {
    return "constructor" in GestureEvent;
  } catch (e2) {
    return false;
  }
}
const SUPPORT = {
  isBrowser,
  gesture: supportsGestureEvents(),
  touch: isTouchScreen(),
  touchscreen: isTouchScreen(),
  pointer: supportsPointerEvents(),
  pointerLock: supportsPointerLock()
};
const DEFAULT_PREVENT_SCROLL_DELAY = 250;
const DEFAULT_DRAG_DELAY = 180;
const DEFAULT_SWIPE_VELOCITY = 0.5;
const DEFAULT_SWIPE_DISTANCE = 50;
const DEFAULT_SWIPE_DURATION = 250;
const dragConfigResolver = _objectSpread2(_objectSpread2({}, coordinatesConfigResolver), {}, {
  pointerLock(_v, _k, {
    pointer: {
      lock = false,
      touch = false
    } = {}
  }) {
    this.useTouch = touch && SUPPORT.touch;
    return lock && SUPPORT.pointerLock;
  },
  device(_v, _k) {
    if (this.useTouch)
      return "touch";
    if (this.pointerLock)
      return "mouse";
    if (SUPPORT.pointer)
      return "pointer";
    if (SUPPORT.touch)
      return "touch";
    return "mouse";
  },
  preventScroll(value = false, _k, {
    preventScrollAxis = "y"
  }) {
    if (preventScrollAxis)
      this.preventScrollAxis = preventScrollAxis;
    if (!SUPPORT.touchscreen)
      return false;
    if (typeof value === "number")
      return value;
    return value ? DEFAULT_PREVENT_SCROLL_DELAY : false;
  },
  pointerCapture(_v, _k, {
    pointer: {
      capture = true,
      buttons = 1
    } = {}
  }) {
    this.pointerButtons = buttons;
    return !this.pointerLock && this.device === "pointer" && capture;
  },
  threshold(value, _k, {
    filterTaps = false,
    tapsThreshold = 3,
    axis = void 0
  }) {
    const threshold = V$1.toVector(value, filterTaps ? tapsThreshold : axis ? 1 : 0);
    this.filterTaps = filterTaps;
    this.tapsThreshold = tapsThreshold;
    return threshold;
  },
  swipe({
    velocity = DEFAULT_SWIPE_VELOCITY,
    distance = DEFAULT_SWIPE_DISTANCE,
    duration = DEFAULT_SWIPE_DURATION
  } = {}) {
    return {
      velocity: this.transform(V$1.toVector(velocity)),
      distance: this.transform(V$1.toVector(distance)),
      duration
    };
  },
  delay(value = 0) {
    switch (value) {
      case true:
        return DEFAULT_DRAG_DELAY;
      case false:
        return 0;
      default:
        return value;
    }
  }
});
const SCALE_ANGLE_RATIO_INTENT_DEG = 30;
const PINCH_WHEEL_RATIO = 36;
class PinchEngine extends Engine {
  constructor(...args) {
    super(...args);
    _defineProperty(this, "ingKey", "pinching");
    _defineProperty(this, "aliasKey", "da");
  }
  init() {
    this.state.offset = [1, 0];
    this.state.lastOffset = [1, 0];
    this.state._pointerEvents = /* @__PURE__ */ new Map();
  }
  reset() {
    super.reset();
    const state2 = this.state;
    state2._touchIds = [];
    state2.canceled = false;
    state2.cancel = this.cancel.bind(this);
    state2.turns = 0;
  }
  computeOffset() {
    const {
      type,
      movement,
      lastOffset
    } = this.state;
    if (type === "wheel") {
      this.state.offset = V$1.add(movement, lastOffset);
    } else {
      this.state.offset = [(1 + movement[0]) * lastOffset[0], movement[1] + lastOffset[1]];
    }
  }
  computeMovement() {
    const {
      offset: offset2,
      lastOffset
    } = this.state;
    this.state.movement = [offset2[0] / lastOffset[0], offset2[1] - lastOffset[1]];
  }
  intent(v2) {
    const state2 = this.state;
    if (!state2.axis) {
      const axisMovementDifference = Math.abs(v2[0]) * SCALE_ANGLE_RATIO_INTENT_DEG - Math.abs(v2[1]);
      if (axisMovementDifference < 0)
        state2.axis = "angle";
      else if (axisMovementDifference > 0)
        state2.axis = "scale";
    }
    if (this.config.lockDirection) {
      if (state2.axis === "scale")
        v2[1] = 0;
      else if (state2.axis === "angle")
        v2[0] = 0;
    }
  }
  cancel() {
    const state2 = this.state;
    if (state2.canceled)
      return;
    setTimeout(() => {
      state2.canceled = true;
      state2._active = false;
      this.compute();
      this.emit();
    }, 0);
  }
  touchStart(event) {
    this.ctrl.setEventIds(event);
    const state2 = this.state;
    const ctrlTouchIds = this.ctrl.touchIds;
    if (state2._active) {
      if (state2._touchIds.every((id2) => ctrlTouchIds.has(id2)))
        return;
    }
    if (ctrlTouchIds.size < 2)
      return;
    this.start(event);
    state2._touchIds = Array.from(ctrlTouchIds).slice(0, 2);
    const payload = touchDistanceAngle(event, state2._touchIds);
    this.pinchStart(event, payload);
  }
  pointerStart(event) {
    if (event.buttons != null && event.buttons % 2 !== 1)
      return;
    this.ctrl.setEventIds(event);
    event.target.setPointerCapture(event.pointerId);
    const state2 = this.state;
    const _pointerEvents = state2._pointerEvents;
    const ctrlPointerIds = this.ctrl.pointerIds;
    if (state2._active) {
      if (Array.from(_pointerEvents.keys()).every((id2) => ctrlPointerIds.has(id2)))
        return;
    }
    if (_pointerEvents.size < 2) {
      _pointerEvents.set(event.pointerId, event);
    }
    if (state2._pointerEvents.size < 2)
      return;
    this.start(event);
    const payload = distanceAngle(...Array.from(_pointerEvents.values()));
    this.pinchStart(event, payload);
  }
  pinchStart(event, payload) {
    const state2 = this.state;
    state2.origin = payload.origin;
    this.computeValues([payload.distance, payload.angle]);
    this.computeInitial();
    this.compute(event);
    this.emit();
  }
  touchMove(event) {
    if (!this.state._active)
      return;
    const payload = touchDistanceAngle(event, this.state._touchIds);
    this.pinchMove(event, payload);
  }
  pointerMove(event) {
    const _pointerEvents = this.state._pointerEvents;
    if (_pointerEvents.has(event.pointerId)) {
      _pointerEvents.set(event.pointerId, event);
    }
    if (!this.state._active)
      return;
    const payload = distanceAngle(...Array.from(_pointerEvents.values()));
    this.pinchMove(event, payload);
  }
  pinchMove(event, payload) {
    const state2 = this.state;
    const prev_a = state2._values[1];
    const delta_a = payload.angle - prev_a;
    let delta_turns = 0;
    if (Math.abs(delta_a) > 270)
      delta_turns += Math.sign(delta_a);
    this.computeValues([payload.distance, payload.angle - 360 * delta_turns]);
    state2.origin = payload.origin;
    state2.turns = delta_turns;
    state2._movement = [state2._values[0] / state2._initial[0] - 1, state2._values[1] - state2._initial[1]];
    this.compute(event);
    this.emit();
  }
  touchEnd(event) {
    this.ctrl.setEventIds(event);
    if (!this.state._active)
      return;
    if (this.state._touchIds.some((id2) => !this.ctrl.touchIds.has(id2))) {
      this.state._active = false;
      this.compute(event);
      this.emit();
    }
  }
  pointerEnd(event) {
    const state2 = this.state;
    this.ctrl.setEventIds(event);
    try {
      event.target.releasePointerCapture(event.pointerId);
    } catch (_unused) {
    }
    if (state2._pointerEvents.has(event.pointerId)) {
      state2._pointerEvents.delete(event.pointerId);
    }
    if (!state2._active)
      return;
    if (state2._pointerEvents.size < 2) {
      state2._active = false;
      this.compute(event);
      this.emit();
    }
  }
  gestureStart(event) {
    if (event.cancelable)
      event.preventDefault();
    const state2 = this.state;
    if (state2._active)
      return;
    this.start(event);
    this.computeValues([event.scale, event.rotation]);
    state2.origin = [event.clientX, event.clientY];
    this.compute(event);
    this.emit();
  }
  gestureMove(event) {
    if (event.cancelable)
      event.preventDefault();
    if (!this.state._active)
      return;
    const state2 = this.state;
    this.computeValues([event.scale, event.rotation]);
    state2.origin = [event.clientX, event.clientY];
    const _previousMovement = state2._movement;
    state2._movement = [event.scale - 1, event.rotation];
    state2._delta = V$1.sub(state2._movement, _previousMovement);
    this.compute(event);
    this.emit();
  }
  gestureEnd(event) {
    if (!this.state._active)
      return;
    this.state._active = false;
    this.compute(event);
    this.emit();
  }
  wheel(event) {
    if (!event.ctrlKey)
      return;
    if (!this.state._active)
      this.wheelStart(event);
    else
      this.wheelChange(event);
    this.timeoutStore.add("wheelEnd", this.wheelEnd.bind(this));
  }
  wheelStart(event) {
    this.start(event);
    this.wheelChange(event);
  }
  wheelChange(event) {
    const isR3f = "uv" in event;
    if (!isR3f) {
      if (event.cancelable) {
        event.preventDefault();
      }
    }
    const state2 = this.state;
    state2._delta = [-wheelValues(event)[1] / PINCH_WHEEL_RATIO * state2.offset[0], 0];
    V$1.addTo(state2._movement, state2._delta);
    this.state.origin = [event.clientX, event.clientY];
    this.compute(event);
    this.emit();
  }
  wheelEnd() {
    if (!this.state._active)
      return;
    this.state._active = false;
    this.compute();
    this.emit();
  }
  bind(bindFunction) {
    const device = this.config.device;
    if (!!device) {
      bindFunction(device, "start", this[device + "Start"].bind(this));
      bindFunction(device, "change", this[device + "Move"].bind(this));
      bindFunction(device, "end", this[device + "End"].bind(this));
      bindFunction(device, "cancel", this[device + "End"].bind(this));
    } else {
      bindFunction("wheel", "", this.wheel.bind(this), {
        passive: false
      });
    }
  }
}
const pinchConfigResolver = _objectSpread2(_objectSpread2({}, commonConfigResolver), {}, {
  useTouch(_v, _k, {
    pointer: {
      touch = false
    } = {}
  }) {
    return touch && SUPPORT.touch;
  },
  device(_v, _k, config) {
    const sharedConfig = config.shared;
    if (sharedConfig.target && !SUPPORT.touch && SUPPORT.gesture)
      return "gesture";
    if (this.useTouch)
      return "touch";
    if (SUPPORT.touchscreen) {
      if (SUPPORT.pointer)
        return "pointer";
      if (SUPPORT.touch)
        return "touch";
    }
  },
  bounds(_v, _k, {
    scaleBounds = {},
    angleBounds = {}
  }) {
    const _scaleBounds = (state2) => {
      const D2 = assignDefault(call(scaleBounds, state2), {
        min: -Infinity,
        max: Infinity
      });
      return [D2.min, D2.max];
    };
    const _angleBounds = (state2) => {
      const A2 = assignDefault(call(angleBounds, state2), {
        min: -Infinity,
        max: Infinity
      });
      return [A2.min, A2.max];
    };
    if (typeof scaleBounds !== "function" && typeof angleBounds !== "function")
      return [_scaleBounds(), _angleBounds()];
    return (state2) => [_scaleBounds(state2), _angleBounds(state2)];
  },
  threshold(value, _k, config) {
    this.lockDirection = config.axis === "lock";
    const threshold = V$1.toVector(value, this.lockDirection ? [0.1, 3] : 0);
    return threshold;
  }
});
_objectSpread2(_objectSpread2({}, coordinatesConfigResolver), {}, {
  mouseOnly: (value = true) => value
});
_objectSpread2(_objectSpread2({}, coordinatesConfigResolver), {}, {
  mouseOnly: (value = true) => value
});
const EngineMap = /* @__PURE__ */ new Map();
const ConfigResolverMap = /* @__PURE__ */ new Map();
function registerAction(action) {
  EngineMap.set(action.key, action.engine);
  ConfigResolverMap.set(action.key, action.resolver);
}
const dragAction = {
  key: "drag",
  engine: DragEngine,
  resolver: dragConfigResolver
};
const pinchAction = {
  key: "pinch",
  engine: PinchEngine,
  resolver: pinchConfigResolver
};
function _objectWithoutPropertiesLoose$1(source, excluded) {
  if (source == null)
    return {};
  var target = {};
  var sourceKeys = Object.keys(source);
  var key, i2;
  for (i2 = 0; i2 < sourceKeys.length; i2++) {
    key = sourceKeys[i2];
    if (excluded.indexOf(key) >= 0)
      continue;
    target[key] = source[key];
  }
  return target;
}
function _objectWithoutProperties(source, excluded) {
  if (source == null)
    return {};
  var target = _objectWithoutPropertiesLoose$1(source, excluded);
  var key, i2;
  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
    for (i2 = 0; i2 < sourceSymbolKeys.length; i2++) {
      key = sourceSymbolKeys[i2];
      if (excluded.indexOf(key) >= 0)
        continue;
      if (!Object.prototype.propertyIsEnumerable.call(source, key))
        continue;
      target[key] = source[key];
    }
  }
  return target;
}
const sharedConfigResolver = {
  target(value) {
    if (value) {
      return () => "current" in value ? value.current : value;
    }
    return void 0;
  },
  enabled(value = true) {
    return value;
  },
  window(value = SUPPORT.isBrowser ? window : void 0) {
    return value;
  },
  eventOptions({
    passive = true,
    capture = false
  } = {}) {
    return {
      passive,
      capture
    };
  },
  transform(value) {
    return value;
  }
};
const _excluded = ["target", "eventOptions", "window", "enabled", "transform"];
function resolveWith(config = {}, resolvers) {
  const result = {};
  for (const [key, resolver] of Object.entries(resolvers)) {
    switch (typeof resolver) {
      case "function":
        {
          result[key] = resolver.call(result, config[key], key, config);
        }
        break;
      case "object":
        result[key] = resolveWith(config[key], resolver);
        break;
      case "boolean":
        if (resolver)
          result[key] = config[key];
        break;
    }
  }
  return result;
}
function parse(config, gestureKey) {
  const _ref = config, {
    target,
    eventOptions,
    window: window2,
    enabled,
    transform: transform2
  } = _ref, rest = _objectWithoutProperties(_ref, _excluded);
  const _config = {
    shared: resolveWith({
      target,
      eventOptions,
      window: window2,
      enabled,
      transform: transform2
    }, sharedConfigResolver)
  };
  if (gestureKey) {
    const resolver = ConfigResolverMap.get(gestureKey);
    _config[gestureKey] = resolveWith(_objectSpread2({
      shared: _config.shared
    }, rest), resolver);
  } else {
    for (const key in rest) {
      const resolver = ConfigResolverMap.get(key);
      if (resolver) {
        _config[key] = resolveWith(_objectSpread2({
          shared: _config.shared
        }, rest[key]), resolver);
      }
    }
  }
  return _config;
}
class EventStore {
  constructor(ctrl) {
    _defineProperty(this, "_listeners", []);
    this._ctrl = ctrl;
  }
  add(element, device, action, handler, options) {
    const type = toDomEventType(device, action);
    const eventOptions = _objectSpread2(_objectSpread2({}, this._ctrl.config.shared.eventOptions), options);
    element.addEventListener(type, handler, eventOptions);
    this._listeners.push(() => element.removeEventListener(type, handler, eventOptions));
  }
  clean() {
    this._listeners.forEach((remove) => remove());
    this._listeners = [];
  }
}
class TimeoutStore {
  constructor() {
    _defineProperty(this, "_timeouts", /* @__PURE__ */ new Map());
  }
  add(key, callback, ms = 140, ...args) {
    this.remove(key);
    this._timeouts.set(key, window.setTimeout(callback, ms, ...args));
  }
  remove(key) {
    const timeout = this._timeouts.get(key);
    if (timeout)
      window.clearTimeout(timeout);
  }
  clean() {
    this._timeouts.forEach((timeout) => void window.clearTimeout(timeout));
    this._timeouts.clear();
  }
}
class Controller {
  constructor(handlers2) {
    _defineProperty(this, "gestures", /* @__PURE__ */ new Set());
    _defineProperty(this, "_targetEventStore", new EventStore(this));
    _defineProperty(this, "gestureEventStores", {});
    _defineProperty(this, "gestureTimeoutStores", {});
    _defineProperty(this, "handlers", {});
    _defineProperty(this, "config", {});
    _defineProperty(this, "pointerIds", /* @__PURE__ */ new Set());
    _defineProperty(this, "touchIds", /* @__PURE__ */ new Set());
    _defineProperty(this, "state", {
      shared: {
        shiftKey: false,
        metaKey: false,
        ctrlKey: false,
        altKey: false
      }
    });
    resolveGestures(this, handlers2);
  }
  setEventIds(event) {
    if (isTouch(event)) {
      this.touchIds = new Set(touchIds(event));
    } else if ("pointerId" in event) {
      if (event.type === "pointerup" || event.type === "pointercancel")
        this.pointerIds.delete(event.pointerId);
      else if (event.type === "pointerdown")
        this.pointerIds.add(event.pointerId);
    }
  }
  applyHandlers(handlers2, nativeHandlers) {
    this.handlers = handlers2;
    this.nativeHandlers = nativeHandlers;
  }
  applyConfig(config, gestureKey) {
    this.config = parse(config, gestureKey);
  }
  clean() {
    this._targetEventStore.clean();
    for (const key of this.gestures) {
      this.gestureEventStores[key].clean();
      this.gestureTimeoutStores[key].clean();
    }
  }
  effect() {
    if (this.config.shared.target)
      this.bind();
    return () => this._targetEventStore.clean();
  }
  bind(...args) {
    const sharedConfig = this.config.shared;
    const eventOptions = sharedConfig.eventOptions;
    const props2 = {};
    let target;
    if (sharedConfig.target) {
      target = sharedConfig.target();
      if (!target)
        return;
    }
    const bindFunction = bindToProps(props2, eventOptions, !!target);
    if (sharedConfig.enabled) {
      for (const gestureKey of this.gestures) {
        if (this.config[gestureKey].enabled) {
          const Engine2 = EngineMap.get(gestureKey);
          new Engine2(this, args, gestureKey).bind(bindFunction);
        }
      }
      for (const eventKey in this.nativeHandlers) {
        bindFunction(eventKey, "", (event) => this.nativeHandlers[eventKey](_objectSpread2(_objectSpread2({}, this.state.shared), {}, {
          event,
          args
        })), void 0, true);
      }
    }
    for (const handlerProp in props2) {
      props2[handlerProp] = chain(...props2[handlerProp]);
    }
    if (!target)
      return props2;
    for (const handlerProp in props2) {
      const {
        device,
        capture,
        passive
      } = parseProp(handlerProp);
      this._targetEventStore.add(target, device, "", props2[handlerProp], {
        capture,
        passive
      });
    }
  }
}
function setupGesture(ctrl, gestureKey) {
  ctrl.gestures.add(gestureKey);
  ctrl.gestureEventStores[gestureKey] = new EventStore(ctrl);
  ctrl.gestureTimeoutStores[gestureKey] = new TimeoutStore();
}
function resolveGestures(ctrl, internalHandlers) {
  if (internalHandlers.drag)
    setupGesture(ctrl, "drag");
  if (internalHandlers.wheel)
    setupGesture(ctrl, "wheel");
  if (internalHandlers.scroll)
    setupGesture(ctrl, "scroll");
  if (internalHandlers.move)
    setupGesture(ctrl, "move");
  if (internalHandlers.pinch)
    setupGesture(ctrl, "pinch");
  if (internalHandlers.hover)
    setupGesture(ctrl, "hover");
}
const bindToProps = (props2, eventOptions, withPassiveOption) => (device, action, handler, options = {}, isNative = false) => {
  var _options$capture, _options$passive;
  const capture = (_options$capture = options.capture) !== null && _options$capture !== void 0 ? _options$capture : eventOptions.capture;
  const passive = (_options$passive = options.passive) !== null && _options$passive !== void 0 ? _options$passive : eventOptions.passive;
  let handlerProp = isNative ? device : toHandlerProp(device, action, capture);
  if (withPassiveOption && passive)
    handlerProp += "Passive";
  props2[handlerProp] = props2[handlerProp] || [];
  props2[handlerProp].push(handler);
};
const RE_NOT_NATIVE = /^on(Drag|Wheel|Scroll|Move|Pinch|Hover)/;
function sortHandlers(_handlers) {
  const native = {};
  const handlers2 = {};
  const actions = /* @__PURE__ */ new Set();
  for (let key in _handlers) {
    if (RE_NOT_NATIVE.test(key)) {
      actions.add(RegExp.lastMatch);
      handlers2[key] = _handlers[key];
    } else {
      native[key] = _handlers[key];
    }
  }
  return [handlers2, native, actions];
}
function registerGesture(actions, handlers2, handlerKey, key, internalHandlers, config) {
  if (!actions.has(handlerKey))
    return;
  if (!EngineMap.has(key)) {
    return;
  }
  const startKey = handlerKey + "Start";
  const endKey = handlerKey + "End";
  const fn2 = (state2) => {
    let memo = void 0;
    if (state2.first && startKey in handlers2)
      handlers2[startKey](state2);
    if (handlerKey in handlers2)
      memo = handlers2[handlerKey](state2);
    if (state2.last && endKey in handlers2)
      handlers2[endKey](state2);
    return memo;
  };
  internalHandlers[key] = fn2;
  config[key] = config[key] || {};
}
function parseMergedHandlers(mergedHandlers, mergedConfig) {
  const [handlers2, nativeHandlers, actions] = sortHandlers(mergedHandlers);
  const internalHandlers = {};
  registerGesture(actions, handlers2, "onDrag", "drag", internalHandlers, mergedConfig);
  registerGesture(actions, handlers2, "onWheel", "wheel", internalHandlers, mergedConfig);
  registerGesture(actions, handlers2, "onScroll", "scroll", internalHandlers, mergedConfig);
  registerGesture(actions, handlers2, "onPinch", "pinch", internalHandlers, mergedConfig);
  registerGesture(actions, handlers2, "onMove", "move", internalHandlers, mergedConfig);
  registerGesture(actions, handlers2, "onHover", "hover", internalHandlers, mergedConfig);
  return {
    handlers: internalHandlers,
    config: mergedConfig,
    nativeHandlers
  };
}
function useRecognizers(handlers2, config = {}, gestureKey, nativeHandlers) {
  const ctrl = React__default.useMemo(() => new Controller(handlers2), []);
  ctrl.applyHandlers(handlers2, nativeHandlers);
  ctrl.applyConfig(config, gestureKey);
  React__default.useEffect(ctrl.effect.bind(ctrl));
  React__default.useEffect(() => {
    return ctrl.clean.bind(ctrl);
  }, []);
  if (config.target === void 0) {
    return ctrl.bind.bind(ctrl);
  }
  return void 0;
}
function createUseGesture(actions) {
  actions.forEach(registerAction);
  return function useGesture2(_handlers, _config = {}) {
    const {
      handlers: handlers2,
      nativeHandlers,
      config
    } = parseMergedHandlers(_handlers, _config);
    return useRecognizers(handlers2, config, void 0, nativeHandlers);
  };
}
function CornerHandle({
  position: position2,
  inset = false
}) {
  const className = getPositionClass(position2, inset);
  return /* @__PURE__ */ jsx("div", {
    "data-position": position2,
    className: `border-white absolute w-20 h-20 ${className}`
  });
}
function getPositionClass(position2, inset) {
  const left = inset ? "left-0" : "-left-5";
  const top = inset ? "top-0" : "-top-5";
  const bottom = inset ? "bottom-0" : "-bottom-5";
  const right = inset ? "right-0" : "-right-5";
  switch (position2) {
    case "top-left":
      return `${left} ${top} border-l-4 border-t-4 cursor-nwse-resize`;
    case "top-right":
      return `${right} ${top} border-r-4 border-t-4 cursor-nesw-resize`;
    case "bottom-right":
      return `${right} ${bottom} border-r-4 border-b-4 cursor-se-resize`;
    case "bottom-left":
      return `${left} ${bottom} border-l-4 border-b-4 cursor-sw-resize`;
    default:
      return "";
  }
}
var MaskPosition = /* @__PURE__ */ ((MaskPosition2) => {
  MaskPosition2["top"] = "maskTop";
  MaskPosition2["right"] = "maskRight";
  MaskPosition2["bottom"] = "maskBottom";
  MaskPosition2["left"] = "maskLeft";
  return MaskPosition2;
})(MaskPosition || {});
function MaskPart({
  position: position2,
  refs
}) {
  const className = getClassNameByPosition(position2);
  return /* @__PURE__ */ jsx("div", {
    className: `cropzone-transition bg-black/50 bottom absolute ${className}`,
    ref: (el) => refs.current[position2] = el
  });
}
function getClassNameByPosition(position2) {
  switch (position2) {
    case "maskTop":
      return "left-0 top-0";
    case "maskBottom":
      return "bottom-0 left-0";
    default:
      return "";
  }
}
function Line({
  name,
  refs
}) {
  const className = clsx("cropzone-transition pointer-events-none absolute left-0 top-0 bg-white/50", name.startsWith("lineHor") ? "h-px" : "w-px");
  return /* @__PURE__ */ jsx("div", {
    className,
    ref: (el) => {
      refs.current[name] = el;
    }
  });
}
class Interactable {
  constructor(el, config) {
    __publicField(this, "doubleTapTimer", null);
    __publicField(this, "boundOnPointerDown");
    __publicField(this, "boundOnPointerUp");
    __publicField(this, "currentRect", {
      width: 0,
      height: 0,
      left: 0,
      top: 0,
      angle: 0
    });
    __publicField(this, "currentAction");
    __publicField(this, "initialAspectRatio", 0);
    __publicField(this, "lastPosition", {
      pageX: 0,
      pageY: 0
    });
    this.el = el;
    this.config = config;
    this.boundOnPointerDown = this.onPointerDown.bind(this);
    this.boundOnPointerUp = this.onPointerUp.bind(this);
    el.addEventListener("pointerdown", this.boundOnPointerDown);
    el.addEventListener("pointerup", this.boundOnPointerUp);
  }
  get aspectRatio() {
    if (this.config.maintainInitialAspectRatio) {
      return this.initialAspectRatio;
    }
    if (this.config.aspectRatio) {
      return this.config.aspectRatio;
    }
    return null;
  }
  setConfig(newConfig) {
    this.config = __spreadValues(__spreadValues({}, this.config), newConfig);
  }
  destroy() {
    this.el.removeEventListener("pointerdown", this.boundOnPointerDown);
    this.el.removeEventListener("pointerup", this.boundOnPointerUp);
  }
  onPointerDown(e2) {
    var _a2, _b, _c, _d;
    e2.stopPropagation();
    e2.preventDefault();
    this.lastPosition = {
      pageX: e2.pageX,
      pageY: e2.pageY
    };
    this.el.style.touchAction = "none";
    this.el.style.userSelect = "none";
    this.syncCurrentRectWithEl(this.el);
    this.currentAction = this.config.actions.find((a2) => a2.matches(e2));
    if (this.currentAction) {
      this.currentRect = __spreadValues(__spreadValues({}, this.currentRect), (_b = (_a2 = this.currentAction).onPointerDown) == null ? void 0 : _b.call(_a2, e2));
    }
    (_d = (_c = this.config.listeners).onPointerDown) == null ? void 0 : _d.call(_c, {
      rect: this.currentRect
    });
    this.el.onpointermove = this.onPointerMove.bind(this);
    this.el.setPointerCapture(e2.pointerId);
  }
  onPointerMove(e2) {
    e2.stopPropagation();
    e2.preventDefault();
    if (this.currentAction) {
      this.executeAction(this.currentAction, e2);
    }
    this.lastPosition = {
      pageX: e2.pageX,
      pageY: e2.pageY
    };
  }
  executeAction(action, e2, extra) {
    const prevRect = __spreadValues({}, this.currentRect);
    this.currentRect = action.execute({
      deltaX: e2.pageX - this.lastPosition.pageX,
      deltaY: e2.pageY - this.lastPosition.pageY,
      pageX: e2.pageX,
      pageY: e2.pageY,
      aspectRatio: this.aspectRatio,
      currentRect: this.currentRect
    }, extra);
    if (this.config.modifiers) {
      this.currentRect = this.config.modifiers.reduce((rect, modifier) => modifier({
        currentRect: this.currentRect,
        prevRect
      }, this.config), this.currentRect);
    }
    const callback = this.config.listeners[action.callbackName];
    const payload = {
      rect: __spreadValues({}, this.currentRect),
      prevRect
    };
    callback == null ? void 0 : callback(payload);
  }
  syncCurrentRectWithEl(el) {
    var _a2;
    const translateVal = (_a2 = el.style.transform.match(/translate\((.+?)\)/)) == null ? void 0 : _a2[1];
    const [left = "0", top = "0"] = (translateVal || "").split(",");
    this.currentRect = {
      width: el.offsetWidth,
      height: el.offsetHeight,
      left: parseInt(left, 10),
      top: parseInt(top, 10),
      angle: 0
    };
    this.initialAspectRatio = this.currentRect.width / this.currentRect.height;
  }
  onPointerUp(e2) {
    var _a2, _b;
    e2.stopPropagation();
    e2.preventDefault();
    const currentTarget = e2.currentTarget;
    this.currentAction = null;
    currentTarget.onpointermove = null;
    currentTarget.releasePointerCapture(e2.pointerId);
    this.config.actions.forEach((a2) => {
      var _a3;
      return (_a3 = a2.onPointerUp) == null ? void 0 : _a3.call(a2, e2);
    });
    (_b = (_a2 = this.config.listeners).onPointerUp) == null ? void 0 : _b.call(_a2, {
      rect: this.currentRect
    });
    this.handleDoubleTap(e2);
  }
  handleDoubleTap(e2) {
    var _a2, _b;
    if (!this.doubleTapTimer) {
      this.doubleTapTimer = setTimeout(() => {
        this.doubleTapTimer = null;
      }, 300);
    } else {
      clearTimeout(this.doubleTapTimer);
      this.doubleTapTimer = null;
      (_b = (_a2 = this.config.listeners).onDoubleTap) == null ? void 0 : _b.call(_a2, e2);
    }
  }
}
class MoveAction {
  constructor() {
    __publicField(this, "callbackName", "onMove");
    __publicField(this, "lockMovement", false);
  }
  matches(e2) {
    return !!e2.target && !!e2.currentTarget && e2.target === e2.currentTarget;
  }
  execute(e2) {
    if (this.lockMovement) {
      return e2.currentRect;
    }
    const newRect = e2.currentRect;
    newRect.left += e2.deltaX;
    newRect.top += e2.deltaY;
    return newRect;
  }
}
function constrainWithinBoundary({
  currentRect,
  prevRect
}, {
  boundaryRect,
  minWidth,
  minHeight,
  aspectRatio
}) {
  let cr = __spreadValues({}, currentRect);
  const pr = __spreadValues({}, prevRect);
  if (boundaryRect) {
    if (cr.left < 0) {
      cr = pr;
    }
    if (cr.top < 0) {
      cr = pr;
    }
    if (cr.left + cr.width > boundaryRect.width) {
      cr = pr;
    }
    if (cr.top + cr.height > boundaryRect.height) {
      cr = pr;
    }
  }
  if (minWidth || minHeight) {
    let min;
    if (aspectRatio) {
      min = calcNewSizeFromAspectRatio(aspectRatio, minWidth, minHeight);
    } else {
      min = {
        width: minWidth,
        height: minHeight
      };
    }
    if (min.width && cr.width < min.width) {
      cr.left = pr.left;
      cr.width = min.width;
    }
    if (min.height && cr.height < min.height) {
      cr.top = pr.top;
      cr.height = min.height;
    }
  }
  return cr;
}
function Cropzone() {
  const refs = useRef({});
  const [isMoving, setIsMoving] = useState(true);
  const boundaryRect = useStore$1((s2) => s2.canvasSize);
  const controlConfig = useStore$1((s2) => {
    var _a2, _b;
    return (_b = (_a2 = s2.config.tools) == null ? void 0 : _a2.crop) == null ? void 0 : _b.cropzone;
  });
  const defaultRatio = useStore$1((s2) => {
    var _a2, _b;
    return (_b = (_a2 = s2.config.tools) == null ? void 0 : _a2.crop) == null ? void 0 : _b.defaultRatio;
  }) || null;
  useEffect(() => {
    if (tools().crop) {
      tools().crop.zone = new Interactable(refs.current.innerZone, {
        actions: [new MoveAction(), new ResizeAction()],
        modifiers: [constrainWithinBoundary],
        listeners: {
          onPointerDown: () => {
            setIsMoving(true);
          },
          onMove: (e2) => {
            tools().crop.drawZone(e2.rect);
          },
          onResize: (e2) => {
            tools().crop.drawZone(e2.rect);
          },
          onPointerUp: () => {
            setIsMoving(false);
          }
        },
        minHeight: 50,
        minWidth: 50,
        boundaryRect,
        aspectRatio: aspectRatioFromStr(defaultRatio)
      });
    }
    return () => {
      var _a2;
      (_a2 = tools().crop.zone) == null ? void 0 : _a2.destroy();
    };
  }, []);
  useLayoutEffect(() => {
    tools().crop.registerRefs(refs);
    tools().crop.resetCropzone(defaultRatio);
  }, [defaultRatio, boundaryRect]);
  const className = clsx("cropzone absolute z-cropzone isolate left-0 top-0 w-full h-full overflow-hidden", {
    moving: isMoving
  });
  return /* @__PURE__ */ jsxs("div", {
    className,
    onPointerDown: (e2) => {
      e2.stopPropagation();
      e2.preventDefault();
    },
    children: [/* @__PURE__ */ jsxs("div", {
      className: "cropzone-transition border-white/50 absolute z-10 left-0 top-0 border",
      ref: (el) => {
        refs.current.innerZone = el;
      },
      children: [!(controlConfig == null ? void 0 : controlConfig.hideTopLeft) && /* @__PURE__ */ jsx(CornerHandle, {
        position: "top-left",
        inset: true
      }), !(controlConfig == null ? void 0 : controlConfig.hideTopRight) && /* @__PURE__ */ jsx(CornerHandle, {
        position: "top-right",
        inset: true
      }), !(controlConfig == null ? void 0 : controlConfig.hideBottomLeft) && /* @__PURE__ */ jsx(CornerHandle, {
        position: "bottom-left",
        inset: true
      }), !(controlConfig == null ? void 0 : controlConfig.hideBottomRight) && /* @__PURE__ */ jsx(CornerHandle, {
        position: "bottom-right",
        inset: true
      }), /* @__PURE__ */ jsx(Line, {
        name: "lineVer1",
        refs
      }), /* @__PURE__ */ jsx(Line, {
        name: "lineVer2",
        refs
      }), /* @__PURE__ */ jsx(Line, {
        name: "lineHor1",
        refs
      }), /* @__PURE__ */ jsx(Line, {
        name: "lineHor2",
        refs
      })]
    }), /* @__PURE__ */ jsx(MaskPart, {
      refs,
      position: MaskPosition.top
    }), /* @__PURE__ */ jsx(MaskPart, {
      refs,
      position: MaskPosition.left
    }), /* @__PURE__ */ jsx(MaskPart, {
      refs,
      position: MaskPosition.right
    }), /* @__PURE__ */ jsx(MaskPart, {
      refs,
      position: MaskPosition.bottom
    })]
  });
}
const ROTATION_HANDLE_CLASS = "rotation-handle";
class RotateAction {
  constructor() {
    __publicField(this, "callbackName", "onRotate");
    __publicField(this, "centerX", 0);
    __publicField(this, "centerY", 0);
    __publicField(this, "startAngle", 0);
  }
  matches(e2) {
    const target = e2.target;
    return target.classList.contains(ROTATION_HANDLE_CLASS);
  }
  onPointerDown(e2) {
    var _a2;
    const currentTarget = e2.currentTarget;
    const rect = currentTarget.getBoundingClientRect();
    this.centerX = rect.left + rect.width / 2;
    this.centerY = rect.top + rect.height / 2;
    const rotateVal = (_a2 = currentTarget.style.transform.match(/rotate\((.+?)\)/)) == null ? void 0 : _a2[1];
    const [rotation = "0"] = rotateVal ? rotateVal.split(",") : [];
    this.startAngle = parseFloat(rotation);
    this.startAngle = this.getDragAngle(e2);
    return {
      angle: this.startAngle
    };
  }
  onPointerUp() {
    this.centerX = 0;
    this.centerY = 0;
    this.startAngle = 0;
  }
  execute(e2) {
    const newRect = __spreadValues({}, e2.currentRect);
    newRect.angle = this.getDragAngle(e2);
    newRect.left += e2.deltaX;
    newRect.top += e2.deltaY;
    return newRect;
  }
  getDragAngle(e2) {
    const center = {
      x: this.centerX || 0,
      y: this.centerY || 0
    };
    const angle = Math.atan2(center.y - e2.pageY, center.x - e2.pageX);
    return angle - (this.startAngle || 0);
  }
}
const CustomDuplicateIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M 7 2 C 6.448 2 6 2.448 6 3 C 6 3.552 6.448 4 7 4 L 20 4 L 20 17 C 20 17.552 20.448 18 21 18 C 21.552 18 22 17.552 22 17 L 22 4 C 22 2.895 21.105 2 20 2 L 7 2 z M 4 6 C 2.895 6 2 6.895 2 8 L 2 20 C 2 21.105 2.895 22 4 22 L 16 22 C 17.105 22 18 21.105 18 20 L 18 8 C 18 6.895 17.105 6 16 6 L 4 6 z M 10 10 C 10.552 10 11 10.448 11 11 L 11 13 L 13 13 C 13.552 13 14 13.448 14 14 C 14 14.552 13.552 15 13 15 L 11 15 L 11 17 C 11 17.552 10.552 18 10 18 C 9.448 18 9 17.552 9 17 L 9 15 L 7 15 C 6.448 15 6 14.552 6 14 C 6 13.448 6.448 13 7 13 L 9 13 L 9 11 C 9 10.448 9.448 10 10 10 z"
}));
const CustomFlipIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M 11 3 L 2 21 L 11 21 L 11 3 z M 13 3 L 13 21 L 22 21 L 13 3 z M 9 11.472656 L 9 19 L 5.2363281 19 L 9 11.472656 z"
}));
const CustomFrontSortingIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M 16.476562 2.4511719 C 16.392047 2.4657656 16.308531 2.5061719 16.238281 2.5761719 L 14.130859 4.6835938 C 13.956859 4.8575938 13.956859 5.1394531 14.130859 5.3144531 L 16.238281 7.4238281 C 16.519281 7.7048281 17 7.5054219 17 7.1074219 L 17 6 L 20 6 L 20 9 A 1.0001 1.0001 0 1 0 22 9 L 22 6 C 22 4.9069372 21.093063 4 20 4 L 17 4 L 17 2.8925781 C 17 2.5940781 16.730109 2.4073906 16.476562 2.4511719 z M 4 5 C 2.9069372 5 2 5.9069372 2 7 L 2 14 C 2 15.093063 2.9069372 16 4 16 L 7 16 L 7 19 C 7 20.105 7.895 21 9 21 L 16 21 C 17.105 21 18 20.105 18 19 L 18 12 C 18 10.895 17.105 10 16 10 L 13 10 L 13 7 C 13 5.9069372 12.093063 5 11 5 L 4 5 z M 4 7 L 11 7 L 11 14 L 4 14 L 4 7 z"
}));
const CustomRemoveIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M 10 2 L 9 3 L 3 3 L 3 5 L 21 5 L 21 3 L 15 3 L 14 2 L 10 2 z M 4.3652344 7 L 5.8925781 20.263672 C 6.0245781 21.253672 6.877 22 7.875 22 L 16.123047 22 C 17.121047 22 17.974422 21.254859 18.107422 20.255859 L 19.634766 7 L 4.3652344 7 z"
}));
const floatingControlsSize = {
  width: 120,
  height: 30
};
const controls = [{
  name: "Duplicate",
  icon: CustomDuplicateIcon,
  onPress: () => {
    tools().objects.duplicate();
  }
}, {
  name: "Flip",
  icon: CustomFlipIcon,
  onPress: () => {
    tools().objects.flipHorizontally();
  }
}, {
  name: "Bring to front",
  icon: CustomFrontSortingIcon,
  onPress: () => {
    tools().objects.bringToFront();
  }
}, {
  name: "Delete",
  icon: CustomRemoveIcon,
  onPress: () => {
    tools().objects.delete();
  }
}];
const FloatingObjectControls = React__default.forwardRef((props2, ref) => {
  const isHidden = useStore$1((s2) => s2.objects.active.isMoving);
  const opacity = isHidden ? "opacity-0" : "opacity-100";
  return /* @__PURE__ */ jsx("div", {
    ref,
    className: `${opacity} absolute z-obj-box left-0 top-0 flex items-center text-white bg-controls rounded shadow transition-opacity overflow-hidden`,
    children: controls.map((control) => {
      const Icon = control.icon;
      return /* @__PURE__ */ jsx(IconButton, {
        className: "w-30 h-30 hover:bg-white/hover",
        radius: "rounded-none",
        onPress: control.onPress,
        children: /* @__PURE__ */ jsx(Icon, {
          className: "icon-sm"
        })
      }, control.name);
    })
  });
});
function repositionFloatingControls(obj, el) {
  if (!el)
    return;
  const angle = obj.angle || 0;
  const floatingControlsTopOffset = angle > 168 && angle < 188 ? -30 : -15;
  const canvas = state().canvasSize;
  const stage = state().stageSize;
  const size = floatingControlsSize;
  const canvasTopMargin = canvas.top - stage.top;
  const canvasLeftMargin = canvas.left - stage.left;
  const canvasRightMargin = stage.width - (canvasLeftMargin + canvas.width);
  const canvasBottomMargin = stage.height - (canvasTopMargin + canvas.height);
  const maxTop = -canvasTopMargin;
  const maxLeft = -(canvas.left - stage.left);
  const maxRight = canvas.width - size.width + canvasRightMargin;
  const maxBottom = canvas.height - size.height + canvasBottomMargin;
  const boundingRect = obj.getBoundingRect();
  let floatingTop = boundingRect.top - size.height + floatingControlsTopOffset;
  let floatingLeft = boundingRect.left + boundingRect.width / 2 - size.width / 2;
  floatingTop = Math.min(maxBottom, Math.max(maxTop, floatingTop));
  floatingLeft = Math.min(maxRight, Math.max(maxLeft, floatingLeft));
  el.style.transform = `translate(${floatingLeft}px, ${floatingTop}px) rotate(0deg)`;
}
function rotateActiveObj(e2) {
  const obj = tools().objects.getActive();
  if (!obj)
    return;
  const newAngle = fabric.fabric.util.radiansToDegrees(e2.rect.angle);
  if (newAngle !== obj.angle) {
    tools().objects.setValues({
      angle: newAngle
    });
  }
}
function moveActiveObj(e2) {
  const centerX = e2.rect.width / 2;
  const centerY = e2.rect.height / 2;
  tools().objects.setValues({
    left: (e2.rect.left + centerX) / state().zoom,
    top: (e2.rect.top + centerY) / state().zoom
  });
}
function resizeActiveObj(e2) {
  var _a2, _b;
  const obj = tools().objects.getActive();
  if (!obj)
    return;
  const newValues = {};
  if (isText(obj)) {
    const delta = e2.rect.width - ((_b = (_a2 = e2.prevRect) == null ? void 0 : _a2.width) != null ? _b : 0);
    if (delta > 0 || obj.getScaledHeight() >= 20 && obj.getScaledWidth() >= 20) {
      newValues.fontSize = (obj.fontSize || 1) + delta;
    }
  } else {
    if (obj.width) {
      newValues.scaleX = e2.rect.width / state().zoom / obj.width;
    }
    if (obj.height) {
      newValues.scaleY = e2.rect.height / state().zoom / obj.height;
    }
  }
  tools().objects.setValues(newValues);
}
function syncBoxPositionWithActiveObj(boxRef, floatingControlsRef) {
  var _a2, _b, _c;
  const obj = tools().objects.getActive();
  if (!obj || !boxRef.current)
    return;
  const el = boxRef.current;
  const angleRad = fabric.fabric.util.degreesToRadians((_a2 = obj.angle) != null ? _a2 : 0);
  let width = Math.round(obj.getScaledWidth() * state().zoom);
  let height = Math.round(obj.getScaledHeight() * state().zoom);
  let left = Math.round(((_b = obj.left) != null ? _b : 0) * state().zoom);
  let top = Math.round(((_c = obj.top) != null ? _c : 0) * state().zoom);
  const centerX = obj.originX === "center" ? width / 2 : 0;
  const centerY = obj.originY === "center" ? height / 2 : 0;
  if (obj.padding) {
    width += obj.padding * 2;
    height += obj.padding * 2;
    left -= obj.padding;
    top -= obj.padding;
  }
  el.style.width = `${width}px`;
  el.style.height = `${height}px`;
  el.style.transform = `translate(${left - centerX}px, ${top - centerY}px) rotate(${angleRad}rad)`;
  tools().canvas.render();
  repositionFloatingControls(obj, floatingControlsRef.current);
}
function enableTextEditing() {
  var _a2;
  const obj = tools().objects.getActive();
  if (isText(obj)) {
    obj.enterEditing();
    (_a2 = obj.hiddenTextarea) == null ? void 0 : _a2.focus();
  }
}
function RotationControl() {
  return /* @__PURE__ */ jsx("div", {
    className: "absolute -bottom-20 left-1/2 w-2 h-20 bg-white cursor-default -translate-x-1/2",
    children: /* @__PURE__ */ jsx("div", {
      className: `${ROTATION_HANDLE_CLASS} w-18 h-18 absolute -bottom-10 -left-8 bg-white rounded-full cursor-move`
    })
  });
}
function ObjectBox() {
  const boxRef = useRef(null);
  const interactableRef = useRef(null);
  const floatingControlsRef = useRef(null);
  const objectControlConfig = useStore$1((s2) => s2.config.objectControls);
  const activeObjId = useStore$1((s2) => s2.objects.active.id);
  const isEditingText = useStore$1((s2) => s2.objects.isEditingText);
  const zoom = useStore$1((s2) => s2.zoom);
  const objTypeConfig = getObjTypeConfig();
  useEffect(() => {
    if (!fabricCanvas())
      return;
    state().editor.on("object:modified", (e2) => {
      if (e2.sizeOrPositionChanged) {
        syncBoxPositionWithActiveObj(boxRef, floatingControlsRef);
      }
    });
    interactableRef.current = new Interactable(boxRef.current, {
      minWidth: 50,
      minHeight: 50,
      maintainInitialAspectRatio: true,
      actions: [new MoveAction(), new ResizeAction(), new RotateAction()],
      listeners: {
        onPointerUp: () => {
          state().objects.setActiveIsMoving(false);
        },
        onDoubleTap: () => {
          enableTextEditing();
        },
        onRotate: (e2) => {
          state().objects.setActiveIsMoving(true);
          rotateActiveObj(e2);
        },
        onMove: (e2) => {
          state().objects.setActiveIsMoving(true);
          moveActiveObj(e2);
        },
        onResize: (e2) => {
          state().objects.setActiveIsMoving(true);
          resizeActiveObj(e2);
        }
      }
    });
    return () => {
      interactableRef.current.destroy();
    };
  }, []);
  useEffect(() => {
    onObjectControlConfigChange(interactableRef.current, objTypeConfig);
  }, [objectControlConfig]);
  useEffect(() => {
    syncBoxPositionWithActiveObj(boxRef, floatingControlsRef);
  }, [activeObjId, zoom, isEditingText]);
  const display = activeObjId && !isEditingText ? "block" : "hidden";
  return /* @__PURE__ */ jsxs("div", {
    className: display,
    children: [/* @__PURE__ */ jsxs("div", {
      ref: boxRef,
      className: "absolute z-obj-box border-2 border-white shadow-md cursor-move",
      children: [!objTypeConfig.hideTopLeft && /* @__PURE__ */ jsx(CornerHandle, {
        position: "top-left"
      }), !objTypeConfig.hideTopRight && /* @__PURE__ */ jsx(CornerHandle, {
        position: "top-right"
      }), !objTypeConfig.hideBottomLeft && /* @__PURE__ */ jsx(CornerHandle, {
        position: "bottom-left"
      }), !objTypeConfig.hideBottomRight && /* @__PURE__ */ jsx(CornerHandle, {
        position: "bottom-right"
      }), !objTypeConfig.hideRotatingPoint && /* @__PURE__ */ jsx(RotationControl, {})]
    }), /* @__PURE__ */ jsx(FloatingObjectControls, {
      ref: floatingControlsRef
    })]
  });
}
function onObjectControlConfigChange(interactable, objTypeConfig) {
  const moveAction = interactable.config.actions.find((a2) => a2 instanceof MoveAction);
  moveAction.lockMovement = !!objTypeConfig.lockMovement;
  interactable.setConfig({
    maintainInitialAspectRatio: !objTypeConfig.unlockAspectRatio
  });
}
function getObjTypeConfig() {
  const obj = tools().objects.getActive();
  if (!obj || !obj.name)
    return {};
  const userConfig = state().config.objectControls || {};
  const objName = obj.name;
  return __spreadValues(__spreadValues({}, userConfig.global), userConfig[objName]);
}
function StageOverlays() {
  const cropToolIsActive = useStore$1((s2) => s2.activeTool === ToolName.CROP);
  const objIsSelected = useStore$1((s2) => s2.objects.active.id);
  return /* @__PURE__ */ jsxs("div", {
    children: [cropToolIsActive && /* @__PURE__ */ jsx(Cropzone, {}), objIsSelected && /* @__PURE__ */ jsx(ObjectBox, {})]
  });
}
const useGesture = createUseGesture([dragAction, pinchAction]);
const CanvasWrapper = React__default.forwardRef((props2, canvasRef) => {
  const [isVisible, setIsVisible] = useState(false);
  useEffect(() => {
    return useStore$1.subscribe((s2) => s2.loading, (loading) => {
      if (!loading) {
        setIsVisible(true);
      } else {
        setIsVisible(false);
      }
    });
  }, []);
  const variants = {
    visible: {
      opacity: 1,
      transition: {
        duration: 0.35,
        delay: 0.5
      }
    },
    hidden: {
      opacity: 0,
      transition: {
        duration: 0
      }
    }
  };
  return /* @__PURE__ */ jsx(PanContainer, {
    children: /* @__PURE__ */ jsxs(m$2.div, {
      initial: {
        opacity: 0
      },
      variants,
      animate: isVisible ? "visible" : "hidden",
      className: "relative m-auto",
      style: {
        backgroundImage: `url(${assetUrl("images/empty-canvas-bg.png")})`
      },
      children: [/* @__PURE__ */ jsx(StageOverlays, {}), /* @__PURE__ */ jsx("canvas", {
        ref: canvasRef
      })]
    })
  });
});
function PanContainer({
  children
}) {
  const ref = useRef(null);
  const bind = useGesture({
    onPinch: (e2) => {
      if (!tools().zoom.allowUserZoom || !shouldHandleGesture(e2)) {
        return e2.cancel();
      }
      if (e2.direction[0] === 1) {
        tools().zoom.zoomIn(0.01);
      } else {
        tools().zoom.zoomOut(0.01);
      }
      e2.event.stopPropagation();
      e2.event.preventDefault();
    },
    onDrag: (e2) => {
      if (e2.pinching || !shouldHandleGesture(e2)) {
        return e2.cancel();
      }
      ref.current.scrollLeft -= e2.delta[0];
      ref.current.scrollTop -= e2.delta[1];
    }
  });
  return /* @__PURE__ */ jsx("div", __spreadProps(__spreadValues({
    ref,
    className: "flex items-center justify-center w-full h-full overflow-hidden touch-none"
  }, bind()), {
    children
  }));
}
function shouldHandleGesture(e2) {
  return !(fabricCanvas().findTarget(e2.event, false) || fabricCanvas().isDrawingMode);
}
function ToolControlsOverlayWrapper({
  actionBtn,
  children,
  className
}) {
  return /* @__PURE__ */ jsxs("div", {
    className: clsx(className, "flex gap-16 items-center h-full"),
    children: [actionBtn && /* @__PURE__ */ jsx("div", {
      className: "flex-shrink-0",
      children: actionBtn
    }), /* @__PURE__ */ jsx("div", {
      className: "w-full flex-auto",
      children
    }), actionBtn && /* @__PURE__ */ jsx("div", {
      className: "w-96"
    })]
  });
}
function u() {
  return (u = Object.assign || function(e2) {
    for (var r2 = 1; r2 < arguments.length; r2++) {
      var t2 = arguments[r2];
      for (var n2 in t2)
        Object.prototype.hasOwnProperty.call(t2, n2) && (e2[n2] = t2[n2]);
    }
    return e2;
  }).apply(this, arguments);
}
function c(e2, r2) {
  if (e2 == null)
    return {};
  var t2, n2, o2 = {}, a2 = Object.keys(e2);
  for (n2 = 0; n2 < a2.length; n2++)
    r2.indexOf(t2 = a2[n2]) >= 0 || (o2[t2] = e2[t2]);
  return o2;
}
function i(e2) {
  var t2 = useRef(e2), n2 = useRef(function(e3) {
    t2.current && t2.current(e3);
  });
  return t2.current = e2, n2.current;
}
var s = function(e2, r2, t2) {
  return r2 === void 0 && (r2 = 0), t2 === void 0 && (t2 = 1), e2 > t2 ? t2 : e2 < r2 ? r2 : e2;
}, f = function(e2) {
  return "touches" in e2;
}, v = function(e2) {
  return e2 && e2.ownerDocument.defaultView || self;
}, d = function(e2, r2, t2) {
  var n2 = e2.getBoundingClientRect(), o2 = f(r2) ? function(e3, r3) {
    for (var t3 = 0; t3 < e3.length; t3++)
      if (e3[t3].identifier === r3)
        return e3[t3];
    return e3[0];
  }(r2.touches, t2) : r2;
  return { left: s((o2.pageX - (n2.left + v(e2).pageXOffset)) / n2.width), top: s((o2.pageY - (n2.top + v(e2).pageYOffset)) / n2.height) };
}, h = function(e2) {
  !f(e2) && e2.preventDefault();
}, m = React__default.memo(function(o2) {
  var a2 = o2.onMove, l2 = o2.onKey, s2 = c(o2, ["onMove", "onKey"]), m2 = useRef(null), g2 = i(a2), p2 = i(l2), b2 = useRef(null), _2 = useRef(false), x2 = useMemo(function() {
    var e2 = function(e3) {
      h(e3), (f(e3) ? e3.touches.length > 0 : e3.buttons > 0) && m2.current ? g2(d(m2.current, e3, b2.current)) : t2(false);
    }, r2 = function() {
      return t2(false);
    };
    function t2(t3) {
      var n2 = _2.current, o3 = v(m2.current), a3 = t3 ? o3.addEventListener : o3.removeEventListener;
      a3(n2 ? "touchmove" : "mousemove", e2), a3(n2 ? "touchend" : "mouseup", r2);
    }
    return [function(e3) {
      var r3 = e3.nativeEvent, n2 = m2.current;
      if (n2 && (h(r3), !function(e4, r4) {
        return r4 && !f(e4);
      }(r3, _2.current) && n2)) {
        if (f(r3)) {
          _2.current = true;
          var o3 = r3.changedTouches || [];
          o3.length && (b2.current = o3[0].identifier);
        }
        n2.focus(), g2(d(n2, r3, b2.current)), t2(true);
      }
    }, function(e3) {
      var r3 = e3.which || e3.keyCode;
      r3 < 37 || r3 > 40 || (e3.preventDefault(), p2({ left: r3 === 39 ? 0.05 : r3 === 37 ? -0.05 : 0, top: r3 === 40 ? 0.05 : r3 === 38 ? -0.05 : 0 }));
    }, t2];
  }, [p2, g2]), C2 = x2[0], E2 = x2[1], H2 = x2[2];
  return useEffect(function() {
    return H2;
  }, [H2]), React__default.createElement("div", u({}, s2, { onTouchStart: C2, onMouseDown: C2, className: "react-colorful__interactive", ref: m2, onKeyDown: E2, tabIndex: 0, role: "slider" }));
}), g = function(e2) {
  return e2.filter(Boolean).join(" ");
}, p = function(r2) {
  var t2 = r2.color, n2 = r2.left, o2 = r2.top, a2 = o2 === void 0 ? 0.5 : o2, l2 = g(["react-colorful__pointer", r2.className]);
  return React__default.createElement("div", { className: l2, style: { top: 100 * a2 + "%", left: 100 * n2 + "%" } }, React__default.createElement("div", { className: "react-colorful__pointer-fill", style: { backgroundColor: t2 } }));
}, b = function(e2, r2, t2) {
  return r2 === void 0 && (r2 = 0), t2 === void 0 && (t2 = Math.pow(10, r2)), Math.round(t2 * e2) / t2;
}, x = function(e2) {
  return e2[0] === "#" && (e2 = e2.substr(1)), e2.length < 6 ? { r: parseInt(e2[0] + e2[0], 16), g: parseInt(e2[1] + e2[1], 16), b: parseInt(e2[2] + e2[2], 16), a: 1 } : { r: parseInt(e2.substr(0, 2), 16), g: parseInt(e2.substr(2, 2), 16), b: parseInt(e2.substr(4, 2), 16), a: 1 };
}, N = function(e2) {
  var r2 = e2.s, t2 = e2.v, n2 = e2.a, o2 = (200 - r2) * t2 / 100;
  return { h: b(e2.h), s: b(o2 > 0 && o2 < 200 ? r2 * t2 / 100 / (o2 <= 100 ? o2 : 200 - o2) * 100 : 0), l: b(o2 / 2), a: b(n2, 2) };
}, w = function(e2) {
  var r2 = N(e2);
  return "hsl(" + r2.h + ", " + r2.s + "%, " + r2.l + "%)";
}, q = function(e2) {
  var r2 = e2.h, t2 = e2.s, n2 = e2.v, o2 = e2.a;
  r2 = r2 / 360 * 6, t2 /= 100, n2 /= 100;
  var a2 = Math.floor(r2), l2 = n2 * (1 - t2), u2 = n2 * (1 - (r2 - a2) * t2), c2 = n2 * (1 - (1 - r2 + a2) * t2), i2 = a2 % 6;
  return { r: b(255 * [n2, u2, l2, l2, c2, n2][i2]), g: b(255 * [c2, n2, n2, u2, l2, l2][i2]), b: b(255 * [l2, l2, c2, n2, n2, u2][i2]), a: b(o2, 2) };
}, z = function(e2) {
  var r2 = e2.toString(16);
  return r2.length < 2 ? "0" + r2 : r2;
}, B = function(e2) {
  var r2 = e2.r, t2 = e2.g, n2 = e2.b, o2 = e2.a, a2 = Math.max(r2, t2, n2), l2 = a2 - Math.min(r2, t2, n2), u2 = l2 ? a2 === r2 ? (t2 - n2) / l2 : a2 === t2 ? 2 + (n2 - r2) / l2 : 4 + (r2 - t2) / l2 : 0;
  return { h: b(60 * (u2 < 0 ? u2 + 6 : u2)), s: b(a2 ? l2 / a2 * 100 : 0), v: b(a2 / 255 * 100), a: o2 };
}, K = React__default.memo(function(r2) {
  var t2 = r2.hue, n2 = r2.onChange, o2 = g(["react-colorful__hue", r2.className]);
  return React__default.createElement("div", { className: o2 }, React__default.createElement(m, { onMove: function(e2) {
    n2({ h: 360 * e2.left });
  }, onKey: function(e2) {
    n2({ h: s(t2 + 360 * e2.left, 0, 360) });
  }, "aria-label": "Hue", "aria-valuetext": b(t2) }, React__default.createElement(p, { className: "react-colorful__hue-pointer", left: t2 / 360, color: w({ h: t2, s: 100, v: 100, a: 1 }) })));
}), L = React__default.memo(function(r2) {
  var t2 = r2.hsva, n2 = r2.onChange, o2 = { backgroundColor: w({ h: t2.h, s: 100, v: 100, a: 1 }) };
  return React__default.createElement("div", { className: "react-colorful__saturation", style: o2 }, React__default.createElement(m, { onMove: function(e2) {
    n2({ s: 100 * e2.left, v: 100 - 100 * e2.top });
  }, onKey: function(e2) {
    n2({ s: s(t2.s + 100 * e2.left, 0, 100), v: s(t2.v - 100 * e2.top, 0, 100) });
  }, "aria-label": "Color", "aria-valuetext": "Saturation " + b(t2.s) + "%, Brightness " + b(t2.v) + "%" }, React__default.createElement(p, { className: "react-colorful__saturation-pointer", top: 1 - t2.v / 100, left: t2.s / 100, color: w(t2) })));
}), A = function(e2, r2) {
  if (e2 === r2)
    return true;
  for (var t2 in e2)
    if (e2[t2] !== r2[t2])
      return false;
  return true;
};
function T(e2, t2, l2) {
  var u2 = i(l2), c2 = useState(function() {
    return e2.toHsva(t2);
  }), s2 = c2[0], f2 = c2[1], v2 = useRef({ color: t2, hsva: s2 });
  useEffect(function() {
    if (!e2.equal(t2, v2.current.color)) {
      var r2 = e2.toHsva(t2);
      v2.current = { hsva: r2, color: t2 }, f2(r2);
    }
  }, [t2, e2]), useEffect(function() {
    var r2;
    A(s2, v2.current.hsva) || e2.equal(r2 = e2.fromHsva(s2), v2.current.color) || (v2.current = { hsva: s2, color: r2 }, u2(r2));
  }, [s2, e2, u2]);
  var d2 = useCallback(function(e3) {
    f2(function(r2) {
      return Object.assign({}, r2, e3);
    });
  }, []);
  return [s2, d2];
}
var P = typeof window != "undefined" ? useLayoutEffect : useEffect, X = function() {
  return typeof __webpack_nonce__ != "undefined" ? __webpack_nonce__ : void 0;
}, R = /* @__PURE__ */ new Map(), V = function(e2) {
  P(function() {
    var r2 = e2.current ? e2.current.ownerDocument : document;
    if (r2 !== void 0 && !R.has(r2)) {
      var t2 = r2.createElement("style");
      t2.innerHTML = `.react-colorful{position:relative;display:flex;flex-direction:column;width:200px;height:200px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;cursor:default}.react-colorful__saturation{position:relative;flex-grow:1;border-color:transparent;border-bottom:12px solid #000;border-radius:8px 8px 0 0;background-image:linear-gradient(0deg,#000,transparent),linear-gradient(90deg,#fff,hsla(0,0%,100%,0))}.react-colorful__alpha-gradient,.react-colorful__pointer-fill{content:"";position:absolute;left:0;top:0;right:0;bottom:0;pointer-events:none;border-radius:inherit}.react-colorful__alpha-gradient,.react-colorful__saturation{box-shadow:inset 0 0 0 1px rgba(0,0,0,.05)}.react-colorful__alpha,.react-colorful__hue{position:relative;height:24px}.react-colorful__hue{background:linear-gradient(90deg,red 0,#ff0 17%,#0f0 33%,#0ff 50%,#00f 67%,#f0f 83%,red)}.react-colorful__last-control{border-radius:0 0 8px 8px}.react-colorful__interactive{position:absolute;left:0;top:0;right:0;bottom:0;border-radius:inherit;outline:none;touch-action:none}.react-colorful__pointer{position:absolute;z-index:1;box-sizing:border-box;width:28px;height:28px;transform:translate(-50%,-50%);background-color:#fff;border:2px solid #fff;border-radius:50%;box-shadow:0 2px 4px rgba(0,0,0,.2)}.react-colorful__interactive:focus .react-colorful__pointer{transform:translate(-50%,-50%) scale(1.1)}.react-colorful__alpha,.react-colorful__alpha-pointer{background-color:#fff;background-image:url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill-opacity=".05"><path d="M8 0h8v8H8zM0 8h8v8H0z"/></svg>')}.react-colorful__saturation-pointer{z-index:3}.react-colorful__hue-pointer{z-index:2}`, R.set(r2, t2);
      var n2 = X();
      n2 && t2.setAttribute("nonce", n2), r2.head.appendChild(t2);
    }
  }, []);
}, $ = function(t2) {
  var n2 = t2.className, o2 = t2.colorModel, a2 = t2.color, l2 = a2 === void 0 ? o2.defaultColor : a2, i2 = t2.onChange, s2 = c(t2, ["className", "colorModel", "color", "onChange"]), f2 = useRef(null);
  V(f2);
  var v2 = T(o2, l2, i2), d2 = v2[0], h2 = v2[1], m2 = g(["react-colorful", n2]);
  return React__default.createElement("div", u({}, s2, { ref: f2, className: m2 }), React__default.createElement(L, { hsva: d2, onChange: h2 }), React__default.createElement(K, { hue: d2.h, onChange: h2, className: "react-colorful__last-control" }));
}, G = { defaultColor: "000", toHsva: function(e2) {
  return B(x(e2));
}, fromHsva: function(e2) {
  return t2 = (r2 = q(e2)).g, n2 = r2.b, "#" + z(r2.r) + z(t2) + z(n2);
  var r2, t2, n2;
}, equal: function(e2, r2) {
  return e2.toLowerCase() === r2.toLowerCase() || A(x(e2), x(r2));
} }, J = function(r2) {
  return React__default.createElement($, u({}, r2, { colorModel: G }));
};
function ColorSwatch({
  onChange,
  selectedColor,
  colors
}) {
  const presetBtns = colors.map((color2) => {
    const isSelected = selectedColor === color2;
    return /* @__PURE__ */ jsx(ButtonBase, {
      onPress: () => {
        onChange == null ? void 0 : onChange(color2);
      },
      className: clsx("relative block flex-shrink-0 w-26 h-26 border rounded", isSelected && "shadow-md"),
      style: {
        backgroundColor: color2
      },
      children: isSelected && /* @__PURE__ */ jsx("span", {
        className: "absolute inset-0 m-auto rounded-full w-8 h-8 bg-white"
      })
    }, color2);
  });
  return /* @__PURE__ */ jsx("div", {
    className: "flex gap-6 p-12",
    children: presetBtns
  });
}
function ColorPicker({
  onChange,
  selectedColor,
  colorPresets
}) {
  return /* @__PURE__ */ jsxs("div", {
    className: "bg-paper rounded shadow-md",
    children: [/* @__PURE__ */ jsx(J, {
      className: "!w-auto",
      onChange
    }), colorPresets && /* @__PURE__ */ jsx(ColorSwatch, {
      colors: colorPresets,
      onChange,
      selectedColor
    })]
  });
}
const DialogContext = React__default.createContext(null);
function DialogTriggerBase({
  state: state2,
  triggerProps,
  type,
  isDismissable,
  overlay,
  overlayProps = {},
  trigger,
  disableInitialTransition
}) {
  const context = __spreadValues({
    type,
    onClose: state2.close,
    isDismissable,
    disableInitialTransition
  }, overlayProps);
  return /* @__PURE__ */ jsxs(Fragment, {
    children: [trigger && React__default.cloneElement(trigger, $3ef42575df84b30b$export$9d1611c77c2fe928({
      onPress: () => state2.toggle(),
      key: trigger.key || trigger.props.id
    }, triggerProps)), /* @__PURE__ */ jsx(AnimatePresence, {
      children: state2.isOpen && /* @__PURE__ */ jsx(DialogContext.Provider, {
        value: context,
        children: overlay
      })
    })]
  });
}
function PopoverTrigger(_q) {
  var _r = _q, {
    state: state2,
    targetRef,
    trigger,
    hideArrow,
    children
  } = _r, props2 = __objRest(_r, [
    "state",
    "targetRef",
    "trigger",
    "hideArrow",
    "children"
  ]);
  const {
    triggerRef,
    overlayRef,
    positionStyle,
    triggerObjRef
  } = useOverlayPosition(props2);
  const {
    triggerProps,
    overlayProps
  } = $628037886ba31236$export$f9d5c8beee7d008d({
    type: "dialog"
  }, state2, triggerObjRef);
  const overlay = /* @__PURE__ */ jsx(Popover, {
    style: positionStyle,
    isOpen: state2.isOpen,
    ref: overlayRef,
    onClose: state2.close,
    hideArrow,
    children
  });
  return /* @__PURE__ */ jsx(DialogTriggerBase, {
    type: "popover",
    state: state2,
    triggerProps: __spreadProps(__spreadValues({}, triggerProps), {
      ref: triggerRef
    }),
    overlayProps,
    overlay,
    trigger
  });
}
function Modal(props2) {
  const _a2 = props2, {
    children,
    onClose,
    type,
    isOpen,
    isDismissable
  } = _a2, otherProps = __objRest(_a2, [
    "children",
    "onClose",
    "type",
    "isOpen",
    "isDismissable"
  ]);
  const ref = useRef(null);
  const {
    disableInitialTransition
  } = useContext(DialogContext);
  const {
    overlayProps,
    underlayProps
  } = $a11501f3d1d39e6c$export$ea8f71083e90600f(props2, ref);
  return /* @__PURE__ */ jsxs(Overlay, __spreadProps(__spreadValues({
    type: "modal"
  }, otherProps), {
    className: "absolute inset-0 flex items-center justify-center",
    children: [/* @__PURE__ */ jsx(Underlay, __spreadValues({
      disableInitialTransition
    }, underlayProps), "modal-underlay"), /* @__PURE__ */ jsx(ModalWrapper, {
      onClose,
      isOpen,
      type,
      ref,
      overlayProps,
      children
    }, "modal-wrapper")]
  }));
}
const ModalWrapper = forwardRef((props2, ref) => {
  const _a2 = props2, {
    children,
    isOpen,
    type,
    overlayProps
  } = _a2, otherProps = __objRest(_a2, [
    "children",
    "isOpen",
    "type",
    "overlayProps"
  ]);
  const {
    disableInitialTransition
  } = useContext(DialogContext);
  $49c51c25361d4cd2$export$ee0f7cc6afcd1c18();
  const {
    modalProps
  } = $f57aed4a881a3485$export$33ffd74ebf07f060();
  const animate2 = {
    opacity: 1,
    scale: 1
  };
  return /* @__PURE__ */ jsx(m$2.div, {
    className: "z-20",
    initial: disableInitialTransition ? animate2 : {
      opacity: 0,
      scale: 0.7
    },
    animate: animate2,
    exit: {
      opacity: 0,
      scale: 1
    },
    children: /* @__PURE__ */ jsx("div", __spreadProps(__spreadValues({}, $3ef42575df84b30b$export$9d1611c77c2fe928(otherProps, overlayProps, modalProps)), {
      ref,
      children
    }))
  });
});
function ModalTrigger({
  state: state2,
  trigger,
  children,
  type,
  isDismissable,
  disableInitialTransition
}) {
  const triggerRef = useRef(null);
  const renderOverlay = () => {
    switch (type) {
      case "tray":
        return /* @__PURE__ */ jsx(Tray, {
          isOpen: state2.isOpen,
          onClose: state2.close,
          children
        });
      default:
        return /* @__PURE__ */ jsx(Modal, {
          isOpen: state2.isOpen,
          isDismissable,
          onClose: state2.close,
          type,
          children
        });
    }
  };
  return /* @__PURE__ */ jsx(DialogTriggerBase, {
    type,
    state: state2,
    disableInitialTransition,
    triggerProps: {
      ref: triggerRef
    },
    isDismissable,
    overlay: renderOverlay(),
    trigger
  });
}
function useMediaQuery(query) {
  const supportsMatchMedia = typeof window !== "undefined" && typeof window.matchMedia === "function";
  const [matches, setMatches] = useState(() => supportsMatchMedia ? window.matchMedia(query).matches : false);
  useEffect(() => {
    if (!supportsMatchMedia) {
      return;
    }
    const mq = window.matchMedia(query);
    const onChange = (e2) => {
      setMatches(e2.matches);
    };
    mq.addEventListener("change", onChange);
    return () => {
      mq.removeEventListener("change", onChange);
    };
  }, [supportsMatchMedia, query]);
  const isSSR2 = $9d939cbc98267846$export$535bd6ca7f90a273();
  return isSSR2 ? false : matches;
}
function useIsMobileMediaQuery() {
  return useMediaQuery("(max-width: 700px)");
}
function DialogTrigger(props2) {
  let {
    type = "modal",
    isDismissable = true,
    mobileType = type === "popover" ? "modal" : type
  } = props2;
  const {
    children,
    hideArrow,
    targetRef,
    disableInitialTransition,
    onClose
  } = props2;
  const isMobile = useIsMobileMediaQuery();
  if (isMobile) {
    if (type !== "modal" && mobileType === "modal") {
      isDismissable = true;
    }
    type = mobileType;
  }
  const state2 = $fc909762b330b746$export$61c6a8c84e605fb6(__spreadProps(__spreadValues({}, props2), {
    onOpenChange: (isOpen) => {
      if (!isOpen && onClose) {
        onClose();
      }
    }
  }));
  const {
    trigger,
    content
  } = unwrapChildren(children, state2);
  if (type === "popover") {
    return /* @__PURE__ */ jsx(PopoverTrigger, {
      state: state2,
      targetRef,
      trigger,
      hideArrow,
      children: content
    });
  }
  return /* @__PURE__ */ jsx(ModalTrigger, {
    state: state2,
    trigger,
    type,
    isDismissable,
    disableInitialTransition,
    children: content
  });
}
function unwrapChildren(children, state2) {
  if (Array.isArray(children)) {
    const [trigger, content] = children;
    return {
      trigger: typeof trigger === "function" ? trigger(state2) : trigger,
      content: typeof content === "function" ? content(state2) : content
    };
  }
  return {
    content: children
  };
}
function $parcel$export$d(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $3c6c2b36038e497e$exports = {};
$parcel$export$d($3c6c2b36038e497e$exports, "useDialog", () => $3c6c2b36038e497e$export$d55e7ee900f34e93);
function $3c6c2b36038e497e$export$d55e7ee900f34e93(props2, ref) {
  let { role = "dialog" } = props2;
  let titleId = $bdb11010cef70236$export$b4cc09c592e8fdb8();
  titleId = props2["aria-label"] ? void 0 : titleId;
  useEffect(() => {
    if (ref.current && !ref.current.contains(document.activeElement)) {
      $1159c3b6ba210e4f$export$80f3e147d781571c(ref.current);
      let timeout = setTimeout(() => {
        if (document.activeElement === ref.current) {
          ref.current.blur();
          $1159c3b6ba210e4f$export$80f3e147d781571c(ref.current);
        }
      }, 500);
      return () => {
        clearTimeout(timeout);
      };
    }
  }, [
    ref
  ]);
  return {
    dialogProps: __spreadProps(__spreadValues({}, $65484d02dcb7eb3e$export$457c3d6518dd4c6f(props2, {
      labelable: true
    })), {
      role,
      tabIndex: -1,
      "aria-labelledby": props2["aria-labelledby"] || titleId
    }),
    titleProps: {
      id: titleId
    }
  };
}
function DialogHeader({
  children,
  className,
  titleProps
}) {
  return /* @__PURE__ */ jsx("h3", __spreadProps(__spreadValues({}, titleProps), {
    className,
    children
  }));
}
function Dialog(props2) {
  const _a2 = useContext(DialogContext), {
    type = "modal"
  } = _a2, contextProps = __objRest(_a2, [
    "type"
  ]);
  const ref = useRef(null);
  const {
    dialogProps,
    titleProps
  } = $3c6c2b36038e497e$export$d55e7ee900f34e93($3ef42575df84b30b$export$9d1611c77c2fe928(contextProps, props2), ref);
  const {
    children,
    className
  } = props2;
  let dismissButton = null;
  if (type === "popover" || type === "tray") {
    dismissButton = /* @__PURE__ */ jsx($86ea4cb521eb2e37$export$2317d149ed6f78c4, {
      onDismiss: contextProps.onClose
    });
  }
  let hasHeader = false;
  const dialogChildren = React__default.Children.map(children, (child) => {
    if (React__default.isValidElement(child) && child.type === DialogHeader) {
      hasHeader = true;
      return React__default.cloneElement(child, __spreadProps(__spreadValues({}, child.props), {
        titleProps
      }));
    }
    return child;
  });
  const mergedClassName = clsx("bg-paper rounded shadow-lg max-h-inherit max-w-full focus:outline-none", className);
  return /* @__PURE__ */ jsx($14e5c84cbc2e6e2e$export$20e40289641fbbb6, {
    contain: true,
    restoreFocus: true,
    children: /* @__PURE__ */ jsxs("section", __spreadProps(__spreadValues({}, dialogProps), {
      className: mergedClassName,
      ref,
      children: [contextProps.isDismissable && hasHeader && /* @__PURE__ */ jsx(IconButton, {
        "aria-label": "Dismiss",
        onPress: contextProps.onClose,
        children: /* @__PURE__ */ jsx(CloseIcon, {})
      }), dialogChildren, dismissButton]
    }))
  });
}
function ColorPickerButton(props2) {
  const {
    label,
    className,
    value,
    onChange,
    size
  } = props2;
  const colors = useStore$1((s2) => {
    var _a2, _b;
    return (_b = (_a2 = s2.config.ui) == null ? void 0 : _a2.colorPresets) == null ? void 0 : _b.items;
  }) || [];
  const style2 = inputFieldStyle({
    size
  });
  const [selectedColor, setSelectedColor] = useState(value);
  const {
    labelProps,
    fieldProps
  } = $8f1f06f2efd295ee$export$294aa081a6c6f55d(__spreadValues({
    labelElementType: "span"
  }, props2));
  const onColorChange = (newColor) => {
    setSelectedColor(newColor);
    onChange == null ? void 0 : onChange(newColor);
  };
  return /* @__PURE__ */ jsxs("div", {
    className,
    children: [label && /* @__PURE__ */ jsx("span", __spreadProps(__spreadValues({
      className: style2.label
    }, labelProps), {
      children: label
    })), /* @__PURE__ */ jsxs(DialogTrigger, {
      type: "popover",
      hideArrow: true,
      children: [(state2) => /* @__PURE__ */ jsxs(ButtonBase, __spreadProps(__spreadValues({
        className: clsx(style2.input, "inline-flex items-center")
      }, fieldProps), {
        children: [/* @__PURE__ */ jsx("span", {
          className: "block flex-shrink-0 mr-5 border rounded h-2/4 aspect-square",
          style: {
            backgroundColor: selectedColor
          }
        }), /* @__PURE__ */ jsx(ArrowIcon, {
          isActive: state2.isOpen,
          className: style2.adornment
        })]
      })), /* @__PURE__ */ jsx(Dialog, {
        children: /* @__PURE__ */ jsx(ColorPicker, {
          onChange: onColorChange,
          selectedColor,
          colorPresets: colors
        })
      })]
    })]
  });
}
function ArrowIcon({
  isActive,
  className
}) {
  const rotation = isActive ? "rotate-180" : "rotate-0";
  return /* @__PURE__ */ jsx(KeyboardArrowDownIcon, {
    className: `transition-transform ml-auto flex-shrink-0 ${rotation} ${className}`
  });
}
function $parcel$export$c(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $8f011f344c0ccbcc$exports = {};
$parcel$export$c($8f011f344c0ccbcc$exports, "useSliderState", () => $8f011f344c0ccbcc$export$e5fda3247f5d67f9);
const $8f011f344c0ccbcc$var$DEFAULT_MIN_VALUE = 0;
const $8f011f344c0ccbcc$var$DEFAULT_MAX_VALUE = 100;
const $8f011f344c0ccbcc$var$DEFAULT_STEP_VALUE = 1;
function $8f011f344c0ccbcc$export$e5fda3247f5d67f9(props2) {
  const { isDisabled, minValue = $8f011f344c0ccbcc$var$DEFAULT_MIN_VALUE, maxValue = $8f011f344c0ccbcc$var$DEFAULT_MAX_VALUE, numberFormatter: formatter, step = $8f011f344c0ccbcc$var$DEFAULT_STEP_VALUE } = props2;
  var _defaultValue;
  const [values, setValues] = $bfee1151ccb0650f$export$40bfa8c7b0832715(props2.value, (_defaultValue = props2.defaultValue) !== null && _defaultValue !== void 0 ? _defaultValue : [
    minValue
  ], props2.onChange);
  const [isDraggings, setDraggings] = useState(new Array(values.length).fill(false));
  const isEditablesRef = useRef(new Array(values.length).fill(true));
  const [focusedIndex, setFocusedIndex] = useState(void 0);
  const valuesRef = useRef(null);
  valuesRef.current = values;
  const isDraggingsRef = useRef(null);
  isDraggingsRef.current = isDraggings;
  function getValuePercent(value) {
    return (value - minValue) / (maxValue - minValue);
  }
  function getThumbMinValue(index2) {
    return index2 === 0 ? minValue : values[index2 - 1];
  }
  function getThumbMaxValue(index2) {
    return index2 === values.length - 1 ? maxValue : values[index2 + 1];
  }
  function isThumbEditable(index2) {
    return isEditablesRef.current[index2];
  }
  function setThumbEditable(index2, editable) {
    isEditablesRef.current[index2] = editable;
  }
  function updateValue(index2, value) {
    if (isDisabled || !isThumbEditable(index2))
      return;
    const thisMin = getThumbMinValue(index2);
    const thisMax = getThumbMaxValue(index2);
    value = $48d9f1d165180307$export$cb6e0bb50bc19463(value, thisMin, thisMax, step);
    valuesRef.current = $8f011f344c0ccbcc$var$replaceIndex(valuesRef.current, index2, value);
    setValues(valuesRef.current);
  }
  function updateDragging(index2, dragging) {
    if (isDisabled || !isThumbEditable(index2))
      return;
    const wasDragging = isDraggingsRef.current[index2];
    isDraggingsRef.current = $8f011f344c0ccbcc$var$replaceIndex(isDraggingsRef.current, index2, dragging);
    setDraggings(isDraggingsRef.current);
    if (props2.onChangeEnd && wasDragging && !isDraggingsRef.current.some(Boolean))
      props2.onChangeEnd(valuesRef.current);
  }
  function getFormattedValue(value) {
    return formatter.format(value);
  }
  function setThumbPercent(index2, percent2) {
    updateValue(index2, getPercentValue(percent2));
  }
  function getRoundedValue(value) {
    return Math.round((value - minValue) / step) * step + minValue;
  }
  function getPercentValue(percent2) {
    const val = percent2 * (maxValue - minValue) + minValue;
    return $48d9f1d165180307$export$7d15b64cf5a3a4c4(getRoundedValue(val), minValue, maxValue);
  }
  return {
    values,
    getThumbValue: (index2) => values[index2],
    setThumbValue: updateValue,
    setThumbPercent,
    isThumbDragging: (index2) => isDraggings[index2],
    setThumbDragging: updateDragging,
    focusedThumb: focusedIndex,
    setFocusedThumb: setFocusedIndex,
    getThumbPercent: (index2) => getValuePercent(values[index2]),
    getValuePercent,
    getThumbValueLabel: (index2) => getFormattedValue(values[index2]),
    getFormattedValue,
    getThumbMinValue,
    getThumbMaxValue,
    getPercentValue,
    isThumbEditable,
    setThumbEditable,
    step
  };
}
function $8f011f344c0ccbcc$var$replaceIndex(array, index2, value) {
  if (array[index2] === value)
    return array;
  return [
    ...array.slice(0, index2),
    value,
    ...array.slice(index2 + 1)
  ];
}
function $parcel$export$b(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $330dff91662306eb$exports = {};
$parcel$export$b($330dff91662306eb$exports, "useSlider", () => $330dff91662306eb$export$56b2c08e277f365);
const $8983e12064147eaf$export$7a8d2b02c9371cbf = /* @__PURE__ */ new WeakMap();
function $8983e12064147eaf$export$68e648cbec363a18(state2, index2) {
  let id2 = $8983e12064147eaf$export$7a8d2b02c9371cbf.get(state2);
  if (!id2)
    throw new Error("Unknown slider state");
  return `${id2}-${index2}`;
}
function $330dff91662306eb$export$56b2c08e277f365(props2, state2, trackRef) {
  let { labelProps, fieldProps } = $6f8f5e0de5a77844$export$8467354a121f1b9f(props2);
  let isVertical = props2.orientation === "vertical";
  var _id;
  $8983e12064147eaf$export$7a8d2b02c9371cbf.set(state2, (_id = labelProps.id) !== null && _id !== void 0 ? _id : fieldProps.id);
  let { direction } = $18f2051aff69b9bf$export$43bb16f9c6d9e3f7();
  let { addGlobalListener, removeGlobalListener } = $03deb23ff14920c4$export$4eaf04e54aa8eed6();
  const realTimeTrackDraggingIndex = useRef(null);
  const stateRef = useRef(null);
  stateRef.current = state2;
  const reverseX = direction === "rtl";
  const currentPosition = useRef(null);
  const { moveProps } = $e8a7022cf87cba2a$export$36da96379f79f245({
    onMoveStart() {
      currentPosition.current = null;
    },
    onMove({ deltaX, deltaY }) {
      let size = isVertical ? trackRef.current.offsetHeight : trackRef.current.offsetWidth;
      if (currentPosition.current == null)
        currentPosition.current = stateRef.current.getThumbPercent(realTimeTrackDraggingIndex.current) * size;
      let delta = isVertical ? deltaY : deltaX;
      if (isVertical || reverseX)
        delta = -delta;
      currentPosition.current += delta;
      if (realTimeTrackDraggingIndex.current != null && trackRef.current) {
        const percent2 = $48d9f1d165180307$export$7d15b64cf5a3a4c4(currentPosition.current / size, 0, 1);
        stateRef.current.setThumbPercent(realTimeTrackDraggingIndex.current, percent2);
      }
    },
    onMoveEnd() {
      if (realTimeTrackDraggingIndex.current != null) {
        stateRef.current.setThumbDragging(realTimeTrackDraggingIndex.current, false);
        realTimeTrackDraggingIndex.current = null;
      }
    }
  });
  let currentPointer = useRef(void 0);
  let onDownTrack = (e2, id2, clientX, clientY) => {
    if (trackRef.current && !props2.isDisabled && state2.values.every((_2, i2) => !state2.isThumbDragging(i2))) {
      let size = isVertical ? trackRef.current.offsetHeight : trackRef.current.offsetWidth;
      const trackPosition = trackRef.current.getBoundingClientRect()[isVertical ? "top" : "left"];
      const clickPosition = isVertical ? clientY : clientX;
      const offset2 = clickPosition - trackPosition;
      let percent2 = offset2 / size;
      if (direction === "rtl" || isVertical)
        percent2 = 1 - percent2;
      let value = state2.getPercentValue(percent2);
      let closestThumb;
      let split = state2.values.findIndex((v2) => value - v2 < 0);
      if (split === 0)
        closestThumb = split;
      else if (split === -1)
        closestThumb = state2.values.length - 1;
      else {
        let lastLeft = state2.values[split - 1];
        let firstRight = state2.values[split];
        if (Math.abs(lastLeft - value) < Math.abs(firstRight - value))
          closestThumb = split - 1;
        else
          closestThumb = split;
      }
      if (closestThumb >= 0 && state2.isThumbEditable(closestThumb)) {
        e2.preventDefault();
        realTimeTrackDraggingIndex.current = closestThumb;
        state2.setFocusedThumb(closestThumb);
        currentPointer.current = id2;
        state2.setThumbDragging(realTimeTrackDraggingIndex.current, true);
        state2.setThumbValue(closestThumb, value);
        addGlobalListener(window, "mouseup", onUpTrack, false);
        addGlobalListener(window, "touchend", onUpTrack, false);
        addGlobalListener(window, "pointerup", onUpTrack, false);
      } else
        realTimeTrackDraggingIndex.current = null;
    }
  };
  let onUpTrack = (e2) => {
    var ref;
    var _pointerId;
    let id2 = (_pointerId = e2.pointerId) !== null && _pointerId !== void 0 ? _pointerId : (ref = e2.changedTouches) === null || ref === void 0 ? void 0 : ref[0].identifier;
    if (id2 === currentPointer.current) {
      if (realTimeTrackDraggingIndex.current != null) {
        state2.setThumbDragging(realTimeTrackDraggingIndex.current, false);
        realTimeTrackDraggingIndex.current = null;
      }
      removeGlobalListener(window, "mouseup", onUpTrack, false);
      removeGlobalListener(window, "touchend", onUpTrack, false);
      removeGlobalListener(window, "pointerup", onUpTrack, false);
    }
  };
  if (labelProps.htmlFor) {
    delete labelProps.htmlFor;
    labelProps.onClick = () => {
      var ref;
      (ref = document.getElementById($8983e12064147eaf$export$68e648cbec363a18(state2, 0))) === null || ref === void 0 ? void 0 : ref.focus();
      $507fabe10e71c6fb$export$8397ddfc504fdb9a("keyboard");
    };
  }
  return {
    labelProps,
    groupProps: __spreadValues({
      role: "group"
    }, fieldProps),
    trackProps: $3ef42575df84b30b$export$9d1611c77c2fe928({
      onMouseDown(e2) {
        if (e2.button !== 0 || e2.altKey || e2.ctrlKey || e2.metaKey)
          return;
        onDownTrack(e2, void 0, e2.clientX, e2.clientY);
      },
      onPointerDown(e2) {
        if (e2.pointerType === "mouse" && (e2.button !== 0 || e2.altKey || e2.ctrlKey || e2.metaKey))
          return;
        onDownTrack(e2, e2.pointerId, e2.clientX, e2.clientY);
      },
      onTouchStart(e2) {
        onDownTrack(e2, e2.changedTouches[0].identifier, e2.changedTouches[0].clientX, e2.changedTouches[0].clientY);
      }
    }, moveProps),
    outputProps: {
      htmlFor: state2.values.map((_2, index2) => $8983e12064147eaf$export$68e648cbec363a18(state2, index2)).join(" "),
      "aria-live": "off"
    }
  };
}
var $661f0f6c696c467d$exports = {};
$parcel$export$b($661f0f6c696c467d$exports, "useSliderThumb", () => $661f0f6c696c467d$export$8d15029008292ae);
function $661f0f6c696c467d$export$8d15029008292ae(opts, state2) {
  let { index: index2, isRequired, isDisabled, validationState, trackRef, inputRef } = opts;
  let isVertical = opts.orientation === "vertical";
  let { direction } = $18f2051aff69b9bf$export$43bb16f9c6d9e3f7();
  let { addGlobalListener, removeGlobalListener } = $03deb23ff14920c4$export$4eaf04e54aa8eed6();
  let labelId = $8983e12064147eaf$export$7a8d2b02c9371cbf.get(state2);
  var ref1;
  const { labelProps, fieldProps } = $6f8f5e0de5a77844$export$8467354a121f1b9f(__spreadProps(__spreadValues({}, opts), {
    id: $8983e12064147eaf$export$68e648cbec363a18(state2, index2),
    "aria-labelledby": `${labelId} ${(ref1 = opts["aria-labelledby"]) !== null && ref1 !== void 0 ? ref1 : ""}`.trim()
  }));
  const value = state2.values[index2];
  const focusInput = useCallback(() => {
    if (inputRef.current)
      $7215afc6de606d6b$export$de79e2c695e052f3(inputRef.current);
  }, [
    inputRef
  ]);
  const isFocused = state2.focusedThumb === index2;
  useEffect(() => {
    if (isFocused)
      focusInput();
  }, [
    isFocused,
    focusInput
  ]);
  const stateRef = useRef(null);
  stateRef.current = state2;
  let reverseX = direction === "rtl";
  let currentPosition = useRef(null);
  let { moveProps } = $e8a7022cf87cba2a$export$36da96379f79f245({
    onMoveStart() {
      currentPosition.current = null;
      state2.setThumbDragging(index2, true);
    },
    onMove({ deltaX, deltaY, pointerType }) {
      let size = isVertical ? trackRef.current.offsetHeight : trackRef.current.offsetWidth;
      if (currentPosition.current == null)
        currentPosition.current = stateRef.current.getThumbPercent(index2) * size;
      if (pointerType === "keyboard") {
        let delta = ((reverseX ? -deltaX : deltaX) + (isVertical ? -deltaY : -deltaY)) * stateRef.current.step;
        currentPosition.current += delta * size;
        stateRef.current.setThumbValue(index2, stateRef.current.getThumbValue(index2) + delta);
      } else {
        let delta = isVertical ? deltaY : deltaX;
        if (isVertical || reverseX)
          delta = -delta;
        currentPosition.current += delta;
        stateRef.current.setThumbPercent(index2, $48d9f1d165180307$export$7d15b64cf5a3a4c4(currentPosition.current / size, 0, 1));
      }
    },
    onMoveEnd() {
      state2.setThumbDragging(index2, false);
    }
  });
  state2.setThumbEditable(index2, !isDisabled);
  const { focusableProps } = $391c6482f25a1991$export$4c014de7c8940b4c($3ef42575df84b30b$export$9d1611c77c2fe928(opts, {
    onFocus: () => state2.setFocusedThumb(index2),
    onBlur: () => state2.setFocusedThumb(void 0)
  }), inputRef);
  let currentPointer = useRef(void 0);
  let onDown = (id2) => {
    focusInput();
    currentPointer.current = id2;
    state2.setThumbDragging(index2, true);
    addGlobalListener(window, "mouseup", onUp, false);
    addGlobalListener(window, "touchend", onUp, false);
    addGlobalListener(window, "pointerup", onUp, false);
  };
  let onUp = (e2) => {
    var ref;
    var _pointerId;
    let id2 = (_pointerId = e2.pointerId) !== null && _pointerId !== void 0 ? _pointerId : (ref = e2.changedTouches) === null || ref === void 0 ? void 0 : ref[0].identifier;
    if (id2 === currentPointer.current) {
      focusInput();
      state2.setThumbDragging(index2, false);
      removeGlobalListener(window, "mouseup", onUp, false);
      removeGlobalListener(window, "touchend", onUp, false);
      removeGlobalListener(window, "pointerup", onUp, false);
    }
  };
  return {
    inputProps: $3ef42575df84b30b$export$9d1611c77c2fe928(focusableProps, fieldProps, {
      type: "range",
      tabIndex: !isDisabled ? 0 : void 0,
      min: state2.getThumbMinValue(index2),
      max: state2.getThumbMaxValue(index2),
      step: state2.step,
      value,
      disabled: isDisabled,
      "aria-orientation": opts.orientation,
      "aria-valuetext": state2.getThumbValueLabel(index2),
      "aria-required": isRequired || void 0,
      "aria-invalid": validationState === "invalid" || void 0,
      "aria-errormessage": opts["aria-errormessage"],
      onChange: (e2) => {
        state2.setThumbValue(index2, parseFloat(e2.target.value));
      }
    }),
    thumbProps: !isDisabled ? $3ef42575df84b30b$export$9d1611c77c2fe928(moveProps, {
      onMouseDown: (e2) => {
        if (e2.button !== 0 || e2.altKey || e2.ctrlKey || e2.metaKey)
          return;
        onDown();
      },
      onPointerDown: (e2) => {
        if (e2.button !== 0 || e2.altKey || e2.ctrlKey || e2.metaKey)
          return;
        onDown(e2.pointerId);
      },
      onTouchStart: (e2) => {
        onDown(e2.changedTouches[0].identifier);
      }
    }) : {},
    labelProps
  };
}
function Slider(props2) {
  const _a2 = props2, {
    size = "md",
    onChange,
    onChangeEnd,
    value,
    defaultValue,
    formatOptions,
    inline,
    label,
    getValueLabel,
    showValueLabel = !!label,
    className,
    isDisabled
  } = _a2, otherProps = __objRest(_a2, [
    "size",
    "onChange",
    "onChangeEnd",
    "value",
    "defaultValue",
    "formatOptions",
    "inline",
    "label",
    "getValueLabel",
    "showValueLabel",
    "className",
    "isDisabled"
  ]);
  const numberFormatter = $a916eb452884faea$export$b7a616150fdb9f44(formatOptions);
  const style2 = inputFieldStyle({
    size
  });
  const trackRef = useRef(null);
  const sliderStateOptions = __spreadProps(__spreadValues({}, otherProps), {
    isDisabled,
    label,
    numberFormatter,
    value: value != null ? [value] : void 0,
    defaultValue: defaultValue != null ? [defaultValue] : void 0,
    onChange: (v2) => onChange == null ? void 0 : onChange(v2[0]),
    onChangeEnd: (v2) => onChangeEnd == null ? void 0 : onChangeEnd(v2[0])
  });
  const state2 = $8f011f344c0ccbcc$export$e5fda3247f5d67f9(sliderStateOptions);
  const {
    groupProps,
    trackProps,
    labelProps,
    outputProps
  } = $330dff91662306eb$export$56b2c08e277f365(sliderStateOptions, state2, trackRef);
  const wrapperClassname = clsx("w-full flex-shrink-0 touch-none", className, {
    "flex items-center": inline
  });
  return /* @__PURE__ */ jsxs("div", __spreadProps(__spreadValues({}, groupProps), {
    className: wrapperClassname,
    children: [/* @__PURE__ */ jsxs("div", {
      className: "flex",
      children: [label && /* @__PURE__ */ jsx("label", __spreadProps(__spreadValues({
        className: style2.label
      }, labelProps), {
        children: label
      })), showValueLabel && /* @__PURE__ */ jsx("output", __spreadProps(__spreadValues({}, outputProps), {
        className: clsx(style2.label, "ml-auto"),
        children: getValueLabel ? getValueLabel(state2.values[0]) : state2.getThumbValueLabel(0)
      }))]
    }), /* @__PURE__ */ jsxs("div", __spreadProps(__spreadValues({}, trackProps), {
      ref: trackRef,
      className: "h-30 relative",
      children: [/* @__PURE__ */ jsx("div", {
        className: `absolute inset-0 m-auto h-4 rounded ${isDisabled ? "bg-disabled" : "bg-primary-light"}`
      }), /* @__PURE__ */ jsx("div", {
        className: `absolute inset-0 my-auto h-4 rounded ${isDisabled ? "bg-disabled-fg" : "bg-primary"}`,
        style: {
          width: `${state2.getThumbPercent(0) * 100}%`
        }
      }), /* @__PURE__ */ jsx(Thumb, {
        index: 0,
        state: state2,
        trackRef,
        isDisabled
      })]
    }))]
  }));
}
function Thumb(props2) {
  const {
    state: state2,
    trackRef,
    index: index2,
    isDisabled
  } = props2;
  const inputRef = useRef(null);
  const {
    thumbProps,
    inputProps
  } = $661f0f6c696c467d$export$8d15029008292ae({
    index: index2,
    trackRef,
    inputRef
  }, state2);
  const isDragging = state2.isThumbDragging(index2);
  const {
    focusProps,
    isFocusVisible
  } = $e63d024ca16f2165$export$4e328f61c538687f();
  const {
    hoverProps,
    isHovered
  } = $6179b936705e76d3$export$ae780daf29e6d456(__spreadProps(__spreadValues({}, props2), {
    isDisabled
  }));
  const innerClassName = clsx("rounded-full w-20 h-20 top-1/2 -translate-y-1/2 -translate-x-1/2 absolute inset-0 transition-colors duration-200", {
    "outline outline-offset-2": isFocusVisible && !isDisabled,
    "shadow-md": !isDisabled
  }, thumbColor({
    isDisabled,
    isHovered,
    isDragging
  }));
  return /* @__PURE__ */ jsx("div", __spreadProps(__spreadValues({}, $3ef42575df84b30b$export$9d1611c77c2fe928(thumbProps, hoverProps)), {
    className: innerClassName,
    style: {
      left: `${Math.max(state2.getThumbPercent(index2) * 100, 0)}%`
    },
    children: /* @__PURE__ */ jsx($5c3e21d68f1c4674$export$439d29a4e110a164, {
      children: /* @__PURE__ */ jsx("input", __spreadValues({
        ref: inputRef
      }, $3ef42575df84b30b$export$9d1611c77c2fe928(inputProps, focusProps)))
    })
  }));
}
function thumbColor({
  isDisabled,
  isHovered,
  isDragging
}) {
  if (isDisabled) {
    return "bg-slider-disabled cursor-default";
  }
  if (isDragging) {
    return "bg-primary-dark ring ring-primary-light ring-inset";
  }
  if (isHovered) {
    return "bg-primary-dark";
  }
  return "bg-primary";
}
function $parcel$export$a(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $4b9a49966c91856a$exports = {};
$parcel$export$a($4b9a49966c91856a$exports, "useListState", () => $4b9a49966c91856a$export$2f645645f7bca764);
var $80be09205507c5ec$exports = {};
$parcel$export$a($80be09205507c5ec$exports, "ListCollection", () => $80be09205507c5ec$export$d085fb9e920b5ca7);
var tmp = Symbol.iterator;
class $80be09205507c5ec$export$d085fb9e920b5ca7 {
  *[tmp]() {
    yield* this.iterable;
  }
  get size() {
    return this.keyMap.size;
  }
  getKeys() {
    return this.keyMap.keys();
  }
  getKeyBefore(key) {
    let node = this.keyMap.get(key);
    return node ? node.prevKey : null;
  }
  getKeyAfter(key) {
    let node = this.keyMap.get(key);
    return node ? node.nextKey : null;
  }
  getFirstKey() {
    return this.firstKey;
  }
  getLastKey() {
    return this.lastKey;
  }
  getItem(key) {
    return this.keyMap.get(key);
  }
  at(idx) {
    const keys = [
      ...this.getKeys()
    ];
    return this.getItem(keys[idx]);
  }
  constructor(nodes) {
    this.keyMap = /* @__PURE__ */ new Map();
    this.iterable = nodes;
    let visit = (node) => {
      this.keyMap.set(node.key, node);
      if (node.childNodes && node.type === "section")
        for (let child of node.childNodes)
          visit(child);
    };
    for (let node2 of nodes)
      visit(node2);
    let last;
    let index2 = 0;
    for (let [key, node1] of this.keyMap) {
      if (last) {
        last.nextKey = key;
        node1.prevKey = last.key;
      } else {
        this.firstKey = key;
        node1.prevKey = void 0;
      }
      if (node1.type === "item")
        node1.index = index2++;
      last = node1;
      last.nextKey = void 0;
    }
    this.lastKey = last === null || last === void 0 ? void 0 : last.key;
  }
}
function $4b9a49966c91856a$export$2f645645f7bca764(props2) {
  let { filter: filter2 } = props2;
  let selectionState = $ec35bdc00c823be9$export$253fe78d46329472(props2);
  let disabledKeys = useMemo(() => props2.disabledKeys ? new Set(props2.disabledKeys) : /* @__PURE__ */ new Set(), [
    props2.disabledKeys
  ]);
  let factory = (nodes) => filter2 ? new $80be09205507c5ec$export$d085fb9e920b5ca7(filter2(nodes)) : new $80be09205507c5ec$export$d085fb9e920b5ca7(nodes);
  let context = useMemo(() => ({
    suppressTextValueWarning: props2.suppressTextValueWarning
  }), [
    props2.suppressTextValueWarning
  ]);
  let collection = $54e9526d7573190f$export$6cd28814d92fa9c9(props2, factory, context, [
    filter2
  ]);
  useEffect(() => {
    if (selectionState.focusedKey != null && !collection.getItem(selectionState.focusedKey))
      selectionState.setFocusedKey(null);
  }, [
    collection,
    selectionState.focusedKey
  ]);
  return {
    collection,
    disabledKeys,
    selectionManager: new $1c74ece56c82b9c4$export$6c8a5aaad13c9852(collection, selectionState)
  };
}
var $e08e0e9da1306088$exports = {};
$parcel$export$a($e08e0e9da1306088$exports, "useSingleSelectListState", () => $e08e0e9da1306088$export$e7f05e985daf4b5f);
function $e08e0e9da1306088$export$e7f05e985daf4b5f(props2) {
  var _defaultSelectedKey;
  let [selectedKey, setSelectedKey] = $bfee1151ccb0650f$export$40bfa8c7b0832715(props2.selectedKey, (_defaultSelectedKey = props2.defaultSelectedKey) !== null && _defaultSelectedKey !== void 0 ? _defaultSelectedKey : null, props2.onSelectionChange);
  let selectedKeys = useMemo(() => selectedKey != null ? [
    selectedKey
  ] : [], [
    selectedKey
  ]);
  let { collection, disabledKeys, selectionManager } = $4b9a49966c91856a$export$2f645645f7bca764(__spreadProps(__spreadValues({}, props2), {
    selectionMode: "single",
    disallowEmptySelection: true,
    allowDuplicateSelectionEvents: true,
    selectedKeys,
    onSelectionChange: (keys) => {
      let key = keys.values().next().value;
      if (key === selectedKey && props2.onSelectionChange)
        props2.onSelectionChange(key);
      setSelectedKey(key);
    }
  }));
  let selectedItem = selectedKey != null ? collection.getItem(selectedKey) : null;
  return {
    collection,
    disabledKeys,
    selectionManager,
    selectedKey,
    setSelectedKey,
    selectedItem
  };
}
function $parcel$export$9(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $2cf721c498a73112$exports = {};
$parcel$export$9($2cf721c498a73112$exports, "useSelectState", () => $2cf721c498a73112$export$5159ec8b34d4ec12);
function $2cf721c498a73112$export$5159ec8b34d4ec12(props2) {
  let triggerState = $89a94a12744b972a$export$79fefeb1c2091ac3(props2);
  let listState = $e08e0e9da1306088$export$e7f05e985daf4b5f(__spreadProps(__spreadValues({}, props2), {
    onSelectionChange: (key) => {
      if (props2.onSelectionChange != null)
        props2.onSelectionChange(key);
      triggerState.close();
    }
  }));
  let [isFocused, setFocused] = useState(false);
  return __spreadProps(__spreadValues(__spreadValues({}, listState), triggerState), {
    open() {
      if (listState.collection.size !== 0)
        triggerState.open();
    },
    toggle(focusStrategy) {
      if (listState.collection.size !== 0)
        triggerState.toggle(focusStrategy);
    },
    isFocused,
    setFocused
  });
}
function $parcel$export$8(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $36b2c435d5f32f05$exports = {};
$parcel$export$8($36b2c435d5f32f05$exports, "useSelect", () => $36b2c435d5f32f05$export$e64b2f635402ca43);
function $36b2c435d5f32f05$export$e64b2f635402ca43(props2, state2, ref) {
  let { keyboardDelegate, isDisabled } = props2;
  let collator = $325a3faab7a68acd$export$a16aca283550c30d({
    usage: "search",
    sensitivity: "base"
  });
  let delegate = useMemo(() => keyboardDelegate || new $8dd8d9b0d53d6ca8$export$a05409b8bb224a5a(state2.collection, state2.disabledKeys, null, collator), [
    keyboardDelegate,
    state2.collection,
    state2.disabledKeys,
    collator
  ]);
  let { menuTriggerProps, menuProps } = $235cea8b956832d5$export$dc9c12ed27dd1b49({
    isDisabled,
    type: "listbox"
  }, state2, ref);
  let onKeyDown = (e2) => {
    switch (e2.key) {
      case "ArrowLeft": {
        e2.preventDefault();
        let key = state2.selectedKey != null ? delegate.getKeyAbove(state2.selectedKey) : delegate.getFirstKey();
        if (key)
          state2.setSelectedKey(key);
        break;
      }
      case "ArrowRight": {
        e2.preventDefault();
        let key = state2.selectedKey != null ? delegate.getKeyBelow(state2.selectedKey) : delegate.getFirstKey();
        if (key)
          state2.setSelectedKey(key);
        break;
      }
    }
  };
  let { typeSelectProps } = $a6f03d1cafa48b51$export$e32c88dfddc6e1d8({
    keyboardDelegate: delegate,
    selectionManager: state2.selectionManager,
    onTypeSelect(key) {
      state2.setSelectedKey(key);
    }
  });
  let { labelProps, fieldProps, descriptionProps, errorMessageProps } = $8f1f06f2efd295ee$export$294aa081a6c6f55d(__spreadProps(__spreadValues({}, props2), {
    labelElementType: "span"
  }));
  typeSelectProps.onKeyDown = typeSelectProps.onKeyDownCapture;
  delete typeSelectProps.onKeyDownCapture;
  let domProps = $65484d02dcb7eb3e$export$457c3d6518dd4c6f(props2, {
    labelable: true
  });
  let triggerProps = $3ef42575df84b30b$export$9d1611c77c2fe928(typeSelectProps, menuTriggerProps, fieldProps);
  let valueId = $bdb11010cef70236$export$f680877a34711e37();
  return {
    labelProps: __spreadProps(__spreadValues({}, labelProps), {
      onClick: () => {
        if (!props2.isDisabled) {
          ref.current.focus();
          $507fabe10e71c6fb$export$8397ddfc504fdb9a("keyboard");
        }
      }
    }),
    triggerProps: $3ef42575df84b30b$export$9d1611c77c2fe928(domProps, __spreadProps(__spreadValues({}, triggerProps), {
      onKeyDown: $ff5963eb1fccf552$export$e08e3b67e392101e(triggerProps.onKeyDown, onKeyDown, props2.onKeyDown),
      onKeyUp: props2.onKeyUp,
      "aria-labelledby": [
        triggerProps["aria-labelledby"],
        triggerProps["aria-label"] && !triggerProps["aria-labelledby"] ? triggerProps.id : null,
        valueId
      ].filter(Boolean).join(" "),
      onFocus(e2) {
        if (state2.isFocused)
          return;
        if (props2.onFocus)
          props2.onFocus(e2);
        state2.setFocused(true);
      },
      onBlur(e2) {
        if (state2.isOpen)
          return;
        if (props2.onBlur)
          props2.onBlur(e2);
        state2.setFocused(false);
      }
    })),
    valueProps: {
      id: valueId
    },
    menuProps: __spreadProps(__spreadValues({}, menuProps), {
      autoFocus: state2.focusStrategy || true,
      shouldSelectOnPressUp: true,
      shouldFocusOnHover: true,
      disallowEmptySelection: true,
      onBlur: (e2) => {
        if (e2.currentTarget.contains(e2.relatedTarget))
          return;
        if (props2.onBlur)
          props2.onBlur(e2);
        state2.setFocused(false);
      },
      "aria-labelledby": [
        fieldProps["aria-labelledby"],
        triggerProps["aria-label"] && !fieldProps["aria-labelledby"] ? triggerProps.id : null
      ].filter(Boolean).join(" ")
    }),
    descriptionProps,
    errorMessageProps
  };
}
var $b6311686a239550d$exports = {};
$parcel$export$8($b6311686a239550d$exports, "useHiddenSelect", () => $b6311686a239550d$export$f809e80f58e251d1);
$parcel$export$8($b6311686a239550d$exports, "HiddenSelect", () => $b6311686a239550d$export$cbd84cdb2e668835);
function $b6311686a239550d$export$f809e80f58e251d1(props2, state2, triggerRef) {
  let { autoComplete, name, isDisabled } = props2;
  let modality = $507fabe10e71c6fb$export$98e20ec92f614cfe();
  let { visuallyHiddenProps } = $5c3e21d68f1c4674$export$a966af930f325cab();
  var _selectedKey;
  return {
    containerProps: __spreadProps(__spreadValues({}, visuallyHiddenProps), {
      "aria-hidden": true
    }),
    inputProps: {
      type: "text",
      tabIndex: modality == null || state2.isFocused || state2.isOpen ? -1 : 0,
      style: {
        fontSize: 16
      },
      onFocus: () => triggerRef.current.focus(),
      disabled: isDisabled
    },
    selectProps: {
      tabIndex: -1,
      autoComplete,
      disabled: isDisabled,
      name,
      size: state2.collection.size,
      value: (_selectedKey = state2.selectedKey) !== null && _selectedKey !== void 0 ? _selectedKey : "",
      onChange: (e2) => state2.setSelectedKey(e2.target.value)
    }
  };
}
function $b6311686a239550d$export$cbd84cdb2e668835(props2) {
  let { state: state2, triggerRef, label, name, isDisabled } = props2;
  let { containerProps, inputProps, selectProps } = $b6311686a239550d$export$f809e80f58e251d1(props2, state2, triggerRef);
  if (state2.collection.size <= 300)
    return /* @__PURE__ */ React__default.createElement("div", containerProps, /* @__PURE__ */ React__default.createElement("input", inputProps), /* @__PURE__ */ React__default.createElement("label", null, label, /* @__PURE__ */ React__default.createElement("select", selectProps, /* @__PURE__ */ React__default.createElement("option", null), [
      ...state2.collection.getKeys()
    ].map((key) => {
      let item = state2.collection.getItem(key);
      if (item.type === "item")
        return /* @__PURE__ */ React__default.createElement("option", {
          key: item.key,
          value: item.key
        }, item.textValue);
    }))));
  else if (name)
    return /* @__PURE__ */ React__default.createElement("input", {
      type: "hidden",
      autoComplete: selectProps.autoComplete,
      name,
      disabled: isDisabled,
      value: state2.selectedKey
    });
  return null;
}
function Adornment({
  children,
  direction
}) {
  const dirClass = direction === "start" ? "left-12" : "right-12";
  if (!children)
    return null;
  return /* @__PURE__ */ jsx("div", {
    className: `absolute h-full flex items-center ${dirClass} top-0`,
    children
  });
}
function $parcel$export$7(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $4599f731efac101a$exports = {};
$parcel$export$7($4599f731efac101a$exports, "useListBox", () => $4599f731efac101a$export$50eacbbf140a3141);
var $fc40a93251bc17d1$exports = {};
$parcel$export$7($fc40a93251bc17d1$exports, "listData", () => $fc40a93251bc17d1$export$3585ede4d035bf14);
$parcel$export$7($fc40a93251bc17d1$exports, "getItemId", () => $fc40a93251bc17d1$export$9145995848b05025);
const $fc40a93251bc17d1$export$3585ede4d035bf14 = /* @__PURE__ */ new WeakMap();
function $fc40a93251bc17d1$var$normalizeKey(key) {
  if (typeof key === "string")
    return key.replace(/\s*/g, "");
  return "" + key;
}
function $fc40a93251bc17d1$export$9145995848b05025(state2, itemKey) {
  let data = $fc40a93251bc17d1$export$3585ede4d035bf14.get(state2);
  if (!data)
    throw new Error("Unknown list");
  return `${data.id}-option-${$fc40a93251bc17d1$var$normalizeKey(itemKey)}`;
}
function $4599f731efac101a$export$50eacbbf140a3141(props2, state2, ref) {
  let domProps = $65484d02dcb7eb3e$export$457c3d6518dd4c6f(props2, {
    labelable: true
  });
  let { listProps } = $38e0ab555fbd8768$export$b95089534ab7c1fd(__spreadProps(__spreadValues({}, props2), {
    ref,
    selectionManager: state2.selectionManager,
    collection: state2.collection,
    disabledKeys: state2.disabledKeys
  }));
  let { focusWithinProps } = $9ab94262bd0047c7$export$420e68273165f4ec({
    onFocusWithin: props2.onFocus,
    onBlurWithin: props2.onBlur,
    onFocusWithinChange: props2.onFocusChange
  });
  let id2 = $bdb11010cef70236$export$f680877a34711e37(props2.id);
  $fc40a93251bc17d1$export$3585ede4d035bf14.set(state2, {
    id: id2,
    shouldUseVirtualFocus: props2.shouldUseVirtualFocus,
    shouldSelectOnPressUp: props2.shouldSelectOnPressUp,
    shouldFocusOnHover: props2.shouldFocusOnHover,
    isVirtualized: props2.isVirtualized
  });
  let { labelProps, fieldProps } = $6f8f5e0de5a77844$export$8467354a121f1b9f(__spreadProps(__spreadValues({}, props2), {
    id: id2,
    labelElementType: "span"
  }));
  return {
    labelProps,
    listBoxProps: $3ef42575df84b30b$export$9d1611c77c2fe928(domProps, focusWithinProps, state2.selectionManager.selectionMode === "multiple" ? {
      "aria-multiselectable": "true"
    } : {}, __spreadValues({
      role: "listbox"
    }, $3ef42575df84b30b$export$9d1611c77c2fe928(fieldProps, listProps)))
  };
}
var $320d38f7a0623e79$exports = {};
$parcel$export$7($320d38f7a0623e79$exports, "useOption", () => $320d38f7a0623e79$export$497855f14858aa34);
function $320d38f7a0623e79$export$497855f14858aa34(props2, state2, ref) {
  let { key } = props2;
  let data = $fc40a93251bc17d1$export$3585ede4d035bf14.get(state2);
  var _isDisabled;
  let isDisabled = (_isDisabled = props2.isDisabled) !== null && _isDisabled !== void 0 ? _isDisabled : state2.disabledKeys.has(key);
  var _isSelected;
  let isSelected = (_isSelected = props2.isSelected) !== null && _isSelected !== void 0 ? _isSelected : state2.selectionManager.isSelected(key);
  let isFocused = state2.selectionManager.focusedKey === key;
  var _shouldSelectOnPressUp;
  let shouldSelectOnPressUp = (_shouldSelectOnPressUp = props2.shouldSelectOnPressUp) !== null && _shouldSelectOnPressUp !== void 0 ? _shouldSelectOnPressUp : data.shouldSelectOnPressUp;
  var _shouldFocusOnHover;
  let shouldFocusOnHover = (_shouldFocusOnHover = props2.shouldFocusOnHover) !== null && _shouldFocusOnHover !== void 0 ? _shouldFocusOnHover : data.shouldFocusOnHover;
  var _shouldUseVirtualFocus;
  let shouldUseVirtualFocus = (_shouldUseVirtualFocus = props2.shouldUseVirtualFocus) !== null && _shouldUseVirtualFocus !== void 0 ? _shouldUseVirtualFocus : data.shouldUseVirtualFocus;
  var _isVirtualized;
  let isVirtualized = (_isVirtualized = props2.isVirtualized) !== null && _isVirtualized !== void 0 ? _isVirtualized : data.isVirtualized;
  let labelId = $bdb11010cef70236$export$b4cc09c592e8fdb8();
  let descriptionId = $bdb11010cef70236$export$b4cc09c592e8fdb8();
  let optionProps = {
    role: "option",
    "aria-disabled": isDisabled,
    "aria-selected": state2.selectionManager.selectionMode !== "none" ? isSelected : void 0
  };
  if (!($c87311424ea30a05$export$9ac100e40613ea10() && $c87311424ea30a05$export$78551043582a6a98())) {
    optionProps["aria-label"] = props2["aria-label"];
    optionProps["aria-labelledby"] = labelId;
    optionProps["aria-describedby"] = descriptionId;
  }
  if (isVirtualized) {
    optionProps["aria-posinset"] = state2.collection.getItem(key).index + 1;
    optionProps["aria-setsize"] = $c6b7d36982dcfffc$export$77d5aafae4e095b2(state2.collection);
  }
  let { itemProps, isPressed } = $5ec5a493f6042709$export$ecf600387e221c37({
    selectionManager: state2.selectionManager,
    key,
    ref,
    shouldSelectOnPressUp,
    isVirtualized,
    shouldUseVirtualFocus,
    isDisabled
  });
  let { hoverProps } = $6179b936705e76d3$export$ae780daf29e6d456({
    isDisabled: isDisabled || !shouldFocusOnHover,
    onHoverStart() {
      if (!$507fabe10e71c6fb$export$b9b3dfddab17db27()) {
        state2.selectionManager.setFocused(true);
        state2.selectionManager.setFocusedKey(key);
      }
    }
  });
  return {
    optionProps: __spreadProps(__spreadValues(__spreadValues({}, optionProps), $3ef42575df84b30b$export$9d1611c77c2fe928(itemProps, hoverProps)), {
      id: $fc40a93251bc17d1$export$9145995848b05025(state2, key)
    }),
    labelProps: {
      id: labelId
    },
    descriptionProps: {
      id: descriptionId
    },
    isFocused,
    isSelected,
    isDisabled,
    isPressed
  };
}
var $da55f015385fe4fc$exports = {};
$parcel$export$7($da55f015385fe4fc$exports, "useListBoxSection", () => $da55f015385fe4fc$export$c3f9f39876e4bc7);
function $da55f015385fe4fc$export$c3f9f39876e4bc7(props2) {
  let { heading, "aria-label": ariaLabel } = props2;
  let headingId = $bdb11010cef70236$export$f680877a34711e37();
  return {
    itemProps: {
      role: "presentation"
    },
    headingProps: heading ? {
      id: headingId,
      "aria-hidden": true
    } : {},
    groupProps: {
      role: "group",
      "aria-label": ariaLabel,
      "aria-labelledby": heading ? headingId : void 0
    }
  };
}
function ListboxOption(props2) {
  const {
    item,
    state: state2
  } = props2;
  const ref = useRef(null);
  const {
    optionProps,
    isDisabled,
    isSelected,
    isFocused
  } = $320d38f7a0623e79$export$497855f14858aa34({
    "aria-label": item["aria-label"],
    key: item.key
  }, state2, ref);
  const {
    hoverProps,
    isHovered
  } = $6179b936705e76d3$export$ae780daf29e6d456(__spreadProps(__spreadValues({}, props2), {
    isDisabled
  }));
  const isKeyboardModality = $507fabe10e71c6fb$export$b9b3dfddab17db27();
  const className = listboxItemStyle({
    isFocused: isFocused && isKeyboardModality,
    isSelected,
    isDisabled,
    isHovered
  });
  return /* @__PURE__ */ jsx("li", __spreadProps(__spreadValues({
    className
  }, $3ef42575df84b30b$export$9d1611c77c2fe928(optionProps, hoverProps)), {
    ref,
    children: item.rendered
  }));
}
const ListBox = forwardRef((_s, ref) => {
  var _t = _s, {
    className,
    style: style2
  } = _t, props2 = __objRest(_t, [
    "className",
    "style"
  ]);
  const refObj = $df56164dff5785e2$export$4338b53315abf666(ref);
  const {
    state: state2
  } = props2;
  const {
    listBoxProps
  } = $4599f731efac101a$export$50eacbbf140a3141(props2, state2, refObj);
  const mergedClassname = listboxWrapperStyle(className);
  return /* @__PURE__ */ jsx("ul", __spreadProps(__spreadValues({
    className: mergedClassname,
    style: style2
  }, listBoxProps), {
    ref: refObj,
    children: [...state2.collection].map((item) => /* @__PURE__ */ jsx(ListboxOption, {
      item,
      state: state2
    }, item.key))
  }));
});
function Picker(props2) {
  var _a2;
  const {
    label,
    name,
    value,
    onChange,
    isDisabled,
    autoComplete,
    shouldFlip
  } = __spreadValues({}, props2);
  const style2 = inputFieldStyle(__spreadProps(__spreadValues({}, props2), {
    endAdornment: true
  }));
  const state2 = $2cf721c498a73112$export$5159ec8b34d4ec12(__spreadProps(__spreadValues({}, props2), {
    onSelectionChange: onChange,
    selectedKey: value
  }));
  const listboxRef = useRef(null);
  const {
    triggerRef,
    overlayRef,
    positionStyle,
    triggerObjRef
  } = useOverlayPosition({
    shouldFlip
  });
  const {
    labelProps,
    triggerProps,
    valueProps,
    menuProps,
    descriptionProps,
    errorMessageProps
  } = $36b2c435d5f32f05$export$e64b2f635402ca43(props2, state2, triggerObjRef);
  const isMobile = useIsMobileDevice();
  const {
    buttonProps
  } = $4e9d283129286548$export$ea18c227d4417cc3(triggerProps, triggerObjRef);
  const listbox = /* @__PURE__ */ jsxs($14e5c84cbc2e6e2e$export$20e40289641fbbb6, {
    restoreFocus: true,
    contain: isMobile,
    children: [/* @__PURE__ */ jsx($86ea4cb521eb2e37$export$2317d149ed6f78c4, {
      onDismiss: () => state2.close()
    }), /* @__PURE__ */ jsx(ListBox, __spreadProps(__spreadValues({}, menuProps), {
      ref: listboxRef,
      state: state2,
      disallowEmptySelection: true,
      autoFocus: state2.focusStrategy || true,
      shouldSelectOnPressUp: true
    })), /* @__PURE__ */ jsx($86ea4cb521eb2e37$export$2317d149ed6f78c4, {
      onDismiss: () => state2.close()
    })]
  });
  const [buttonWidth, setButtonWidth] = useState(null);
  const onResize = useCallback(() => {
    if (!isMobile && triggerObjRef.current) {
      const width = triggerObjRef.current.offsetWidth;
      setButtonWidth(width);
    }
  }, [setButtonWidth, isMobile, triggerObjRef]);
  $9daab02d461809db$export$683480f191c0e3ea({
    ref: triggerObjRef,
    onResize
  });
  $f0a04ccd8dbdd83b$export$e5c5a5f917a5871c(onResize, [state2.selectedKey, onResize]);
  let overlay;
  if (isMobile) {
    overlay = /* @__PURE__ */ jsx(Tray, {
      isOpen: state2.isOpen,
      onClose: state2.close,
      children: listbox
    });
  } else {
    overlay = /* @__PURE__ */ jsx(Popover, {
      isOpen: state2.isOpen,
      ref: overlayRef,
      hideArrow: true,
      onClose: state2.close,
      shouldCloseOnBlur: true,
      style: __spreadProps(__spreadValues({}, positionStyle), {
        width: `${buttonWidth}px`
      }),
      children: listbox
    });
  }
  return /* @__PURE__ */ jsxs("div", {
    className: style2.wrapper,
    children: [/* @__PURE__ */ jsx("div", __spreadProps(__spreadValues({}, labelProps), {
      className: style2.label,
      children: label
    })), /* @__PURE__ */ jsx($b6311686a239550d$export$cbd84cdb2e668835, {
      state: state2,
      autoComplete,
      isDisabled,
      triggerRef: triggerObjRef,
      label,
      name
    }), /* @__PURE__ */ jsxs("button", __spreadProps(__spreadValues({
      type: "button",
      className: style2.input,
      disabled: isDisabled
    }, buttonProps), {
      ref: triggerRef,
      children: [/* @__PURE__ */ jsx("span", __spreadProps(__spreadValues({}, valueProps), {
        children: (_a2 = state2.selectedItem) == null ? void 0 : _a2.rendered
      })), /* @__PURE__ */ jsx(Adornment, {
        direction: "end",
        children: /* @__PURE__ */ jsx(KeyboardArrowDownIcon, {
          className: "text-muted"
        })
      })]
    })), /* @__PURE__ */ jsx(AnimatePresence, {
      children: state2.isOpen && overlay
    })]
  });
}
function FilterControls() {
  const selectedFilter = useStore$1((s2) => s2.filter.selected);
  if (!selectedFilter)
    return null;
  const options = tools().filter.getByName(selectedFilter).options;
  const applyValue = (optionName, value) => {
    var _a2;
    (_a2 = tools().filter) == null ? void 0 : _a2.applyValue(selectedFilter, optionName, value);
    state().setDirty(true);
  };
  const activeFilters = tools().canvas.getMainImage().filters;
  const i2 = tools().filter.findFilterIndex(selectedFilter, activeFilters);
  const fabricFilter = activeFilters == null ? void 0 : activeFilters[i2];
  if (options) {
    const controls2 = Object.entries(options).map(([optionName, config]) => {
      let component;
      const value = fabricFilter ? fabricFilter[optionName] : config.current;
      if (config.type === "slider") {
        component = /* @__PURE__ */ jsx(Slider, {
          label: /* @__PURE__ */ jsx(FormattedMessage$1, __spreadValues({}, filterOptionMessages[optionName])),
          minValue: config.min,
          maxValue: config.max,
          step: config.step,
          defaultValue: value,
          formatOptions: {
            style: "percent"
          },
          size: "sm",
          onChange: (newValue) => {
            applyValue(optionName, newValue);
          }
        });
      } else if (config.type === "colorPicker") {
        component = /* @__PURE__ */ jsx(ColorPickerButton, {
          label: /* @__PURE__ */ jsx(FormattedMessage$1, __spreadValues({}, filterOptionMessages[optionName])),
          size: "sm",
          className: "w-full",
          defaultValue: value,
          onChange: (newValue) => {
            applyValue(optionName, newValue);
          }
        });
      } else if (config.type === "select") {
        component = /* @__PURE__ */ jsx(Picker, {
          size: "sm",
          label: /* @__PURE__ */ jsx(FormattedMessage$1, __spreadValues({}, filterOptionMessages[optionName])),
          defaultValue: value,
          onChange: (newValue) => {
            applyValue(optionName, newValue);
          },
          items: config.available,
          children: (item) => /* @__PURE__ */ jsx($89e587cd0f107a73$export$6d08773d2e66f8f2, {
            textValue: item.key,
            children: /* @__PURE__ */ jsx("span", {
              className: "capitalize",
              children: item.key
            })
          })
        });
      }
      return /* @__PURE__ */ jsx("div", {
        className: "pb-10",
        children: component
      }, optionName);
    });
    return /* @__PURE__ */ jsx(ToolControlsOverlayWrapper, {
      children: /* @__PURE__ */ jsx("div", {
        className: "max-w-240 pt-10 mx-auto",
        children: controls2
      })
    });
  }
  return null;
}
function ActiveFrameControls() {
  const activeFrame = useStore$1((s2) => s2.frame.active);
  const showColorPicker = (activeFrame == null ? void 0 : activeFrame.mode) === "basic";
  return /* @__PURE__ */ jsx(ToolControlsOverlayWrapper, {
    className: "pb-18 pt-6",
    children: /* @__PURE__ */ jsxs("div", {
      className: "max-w-288 m-auto",
      children: [showColorPicker && /* @__PURE__ */ jsx("div", {
        className: "mb-16",
        children: /* @__PURE__ */ jsx(ColorPickerButton, {
          size: "sm",
          label: /* @__PURE__ */ jsx(FormattedMessage$1, {
            id: "uMhpKe",
            defaultMessage: [{
              "type": 0,
              "value": "Color"
            }]
          }),
          value: tools().frame.builder.defaultColor,
          onChange: (newColor) => {
            tools().frame.active.changeColor(newColor);
          }
        })
      }), /* @__PURE__ */ jsx(Slider, {
        size: "sm",
        label: /* @__PURE__ */ jsx(FormattedMessage$1, {
          id: "agOXPD",
          defaultMessage: [{
            "type": 0,
            "value": "Size"
          }]
        }),
        step: 1,
        minValue: tools().frame.active.getMinSize(),
        maxValue: tools().frame.active.getMaxSize(),
        defaultValue: tools().frame.active.currentSizeInPercent,
        getValueLabel: (value) => {
          return `${value}%`;
        },
        onChange: (value) => {
          tools().frame.resize(value);
        }
      })]
    })
  });
}
function $parcel$export$6(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $fbeca008f459f5aa$exports = {};
$parcel$export$6($fbeca008f459f5aa$exports, "useTab", () => $fbeca008f459f5aa$export$fdf4756d5b8ef90a);
const $2bc294289400274c$export$c5f62239608282b6 = /* @__PURE__ */ new WeakMap();
function $2bc294289400274c$export$567fc7097e064344(state2, key, role) {
  if (typeof key === "string")
    key = key.replace(/\s+/g, "");
  let baseId = $2bc294289400274c$export$c5f62239608282b6.get(state2);
  return `${baseId}-${role}-${key}`;
}
function $fbeca008f459f5aa$export$fdf4756d5b8ef90a(props2, state2, ref) {
  let { key, isDisabled: propsDisabled } = props2;
  let { selectionManager: manager, selectedKey } = state2;
  let isSelected = key === selectedKey;
  let isDisabled = propsDisabled || state2.disabledKeys.has(key);
  let { itemProps } = $5ec5a493f6042709$export$ecf600387e221c37({
    selectionManager: manager,
    key,
    ref,
    isDisabled
  });
  let tabId = $2bc294289400274c$export$567fc7097e064344(state2, key, "tab");
  let tabPanelId = $2bc294289400274c$export$567fc7097e064344(state2, key, "tabpanel");
  let { tabIndex } = itemProps;
  return {
    tabProps: __spreadProps(__spreadValues({}, itemProps), {
      id: tabId,
      "aria-selected": isSelected,
      "aria-disabled": isDisabled || void 0,
      "aria-controls": isSelected ? tabPanelId : void 0,
      tabIndex: isDisabled ? void 0 : tabIndex,
      role: "tab"
    })
  };
}
var $bc77009ac794dd15$exports = {};
$parcel$export$6($bc77009ac794dd15$exports, "useTabPanel", () => $bc77009ac794dd15$export$fae0121b5afe572d);
function $bc77009ac794dd15$export$fae0121b5afe572d(props2, state2, ref) {
  let [tabIndex, setTabIndex] = useState(0);
  $f0a04ccd8dbdd83b$export$e5c5a5f917a5871c(() => {
    if (ref === null || ref === void 0 ? void 0 : ref.current) {
      let update = () => {
        let walker = $14e5c84cbc2e6e2e$export$2d6ec8fc375ceafa(ref.current, {
          tabbable: true
        });
        setTabIndex(walker.nextNode() ? void 0 : 0);
      };
      update();
      let observer = new MutationObserver(update);
      observer.observe(ref.current, {
        subtree: true,
        childList: true,
        attributes: true,
        attributeFilter: [
          "tabIndex",
          "disabled"
        ]
      });
      return () => {
        observer.disconnect();
      };
    }
  }, [
    ref
  ]);
  const id2 = $2bc294289400274c$export$567fc7097e064344(state2, state2 === null || state2 === void 0 ? void 0 : state2.selectedKey, "tabpanel");
  const tabPanelProps = $313b98861ee5dd6c$export$d6875122194c7b44(__spreadProps(__spreadValues({}, props2), {
    id: id2,
    "aria-labelledby": $2bc294289400274c$export$567fc7097e064344(state2, state2 === null || state2 === void 0 ? void 0 : state2.selectedKey, "tab")
  }));
  return {
    tabPanelProps: $3ef42575df84b30b$export$9d1611c77c2fe928(tabPanelProps, {
      tabIndex,
      role: "tabpanel",
      "aria-describedby": props2["aria-describedby"],
      "aria-details": props2["aria-details"]
    })
  };
}
var $67cd7a6663dbdf35$exports = {};
$parcel$export$6($67cd7a6663dbdf35$exports, "useTabList", () => $67cd7a6663dbdf35$export$773e389e644c5874);
class $d9c38f86f4c836f2$export$15010ca3c1abe90b {
  getKeyLeftOf(key) {
    if (this.flipDirection)
      return this.getNextKey(key);
    else {
      if (this.orientation === "horizontal")
        return this.getPreviousKey(key);
      return null;
    }
  }
  getKeyRightOf(key) {
    if (this.flipDirection)
      return this.getPreviousKey(key);
    else {
      if (this.orientation === "horizontal")
        return this.getNextKey(key);
      return null;
    }
  }
  getKeyAbove(key) {
    if (this.orientation === "vertical")
      return this.getPreviousKey(key);
    return null;
  }
  getKeyBelow(key) {
    if (this.orientation === "vertical")
      return this.getNextKey(key);
    return null;
  }
  getFirstKey() {
    let key = this.collection.getFirstKey();
    if (this.disabledKeys.has(key))
      key = this.getNextKey(key);
    return key;
  }
  getLastKey() {
    let key = this.collection.getLastKey();
    if (this.disabledKeys.has(key))
      key = this.getPreviousKey(key);
    return key;
  }
  getNextKey(key) {
    do {
      key = this.collection.getKeyAfter(key);
      if (key == null)
        key = this.collection.getFirstKey();
    } while (this.disabledKeys.has(key));
    return key;
  }
  getPreviousKey(key) {
    do {
      key = this.collection.getKeyBefore(key);
      if (key == null)
        key = this.collection.getLastKey();
    } while (this.disabledKeys.has(key));
    return key;
  }
  constructor(collection, direction, orientation, disabledKeys = /* @__PURE__ */ new Set()) {
    this.collection = collection;
    this.flipDirection = direction === "rtl" && orientation === "horizontal";
    this.orientation = orientation;
    this.disabledKeys = disabledKeys;
  }
}
function $67cd7a6663dbdf35$export$773e389e644c5874(props2, state2, ref) {
  let { orientation = "horizontal", keyboardActivation = "automatic" } = props2;
  let { collection, selectionManager: manager, disabledKeys } = state2;
  let { direction } = $18f2051aff69b9bf$export$43bb16f9c6d9e3f7();
  let delegate = useMemo(() => new $d9c38f86f4c836f2$export$15010ca3c1abe90b(collection, direction, orientation, disabledKeys), [
    collection,
    disabledKeys,
    orientation,
    direction
  ]);
  let { collectionProps } = $52ac987c016884e9$export$d6daf82dcd84e87c({
    ref,
    selectionManager: manager,
    keyboardDelegate: delegate,
    selectOnFocus: keyboardActivation === "automatic",
    disallowEmptySelection: true,
    scrollRef: ref
  });
  let tabsId = $bdb11010cef70236$export$f680877a34711e37();
  $2bc294289400274c$export$c5f62239608282b6.set(state2, tabsId);
  let tabListLabelProps = $313b98861ee5dd6c$export$d6875122194c7b44(__spreadProps(__spreadValues({}, props2), {
    id: tabsId
  }));
  return {
    tabListProps: __spreadProps(__spreadValues({}, $3ef42575df84b30b$export$9d1611c77c2fe928(collectionProps, tabListLabelProps)), {
      role: "tablist",
      "aria-orientation": orientation,
      tabIndex: void 0
    })
  };
}
const TabContext = React__default.createContext(null);
function Tab(props2) {
  const tabContext = useContext(TabContext);
  const {
    item,
    state: state2,
    className
  } = props2;
  const {
    key,
    rendered
  } = item;
  const isDisabled = state2.disabledKeys.has(key);
  const isSelected = state2.selectedKey === key;
  const ref = useRef(null);
  const {
    tabProps
  } = $fbeca008f459f5aa$export$fdf4756d5b8ef90a({
    key
  }, state2, ref);
  const {
    hoverProps,
    isHovered
  } = $6179b936705e76d3$export$ae780daf29e6d456(__spreadProps(__spreadValues({}, props2), {
    isDisabled
  }));
  const size = tabContext.tabProps.size;
  const mergedClassname = clsx("tracking-wide overflow-hidden capitalize flex-shrink-0 flex items-center outline-none transition-colors", textColor({
    isDisabled,
    isHovered,
    isSelected
  }), className, {
    "px-16 h-48": !size || size === "md",
    "px-12 h-32": size === "sm",
    "cursor-pointer": !isDisabled
  });
  return /* @__PURE__ */ jsx($503734efc0922182$export$1a38b4ad7f578e1d, {
    focusRingClass: "ring-2 ring-inset ring-primary-light rounded",
    children: /* @__PURE__ */ jsx("div", __spreadProps(__spreadValues({
      className: mergedClassname
    }, $3ef42575df84b30b$export$9d1611c77c2fe928(tabProps, hoverProps)), {
      ref,
      children: rendered
    }))
  });
}
function textColor({
  isDisabled,
  isHovered,
  isSelected
}) {
  if (isDisabled) {
    return "text-disabled cursor-default";
  }
  if (isSelected) {
    return "text-primary";
  }
  if (isHovered) {
    return "text-main";
  }
  return "text-muted";
}
function TabLine(props2) {
  const {
    selectedTab,
    selectedKey
  } = props2;
  const [style2, setStyle] = useState({
    width: void 0,
    transform: void 0
  });
  $f0a04ccd8dbdd83b$export$e5c5a5f917a5871c(() => {
    if (selectedTab) {
      setStyle({
        width: `${selectedTab.offsetWidth}px`,
        transform: `translateX(${selectedTab.offsetLeft}px)`
      });
    }
  }, [setStyle, selectedTab, selectedKey]);
  return /* @__PURE__ */ jsx("div", {
    className: "absolute bottom-0 left-0 h-2 bg-primary transition-all",
    role: "presentation",
    style: style2
  });
}
function TabList(props2) {
  const tabContext = useContext(TabContext);
  const {
    refs,
    tabState,
    tabProps
  } = tabContext;
  const {
    selectedTab,
    tabListState: state2
  } = tabState;
  const {
    tablistRef
  } = refs;
  const {
    tabListProps
  } = $67cd7a6663dbdf35$export$773e389e644c5874(__spreadValues(__spreadValues({}, tabProps), props2), state2, tablistRef);
  return /* @__PURE__ */ jsxs("div", __spreadProps(__spreadValues({
    className: "flex relative max-w-full overflow-auto hide-scrollbar"
  }, tabListProps), {
    ref: tablistRef,
    children: [[...state2.collection].map((item, index2) => {
      return /* @__PURE__ */ jsx(Tab, {
        className: clsx(index2 === 0 && "ml-auto", index2 === state2.collection.size - 1 && "mr-auto"),
        item,
        state: state2
      }, item.key);
    }), /* @__PURE__ */ jsx(TabLine, {
      selectedTab
    })]
  }));
}
function $parcel$export$5(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $ead76093e5740fb6$exports = {};
$parcel$export$5($ead76093e5740fb6$exports, "useTabListState", () => $ead76093e5740fb6$export$4ba071daf4e486);
function $ead76093e5740fb6$export$4ba071daf4e486(props2) {
  let state2 = $e08e0e9da1306088$export$e7f05e985daf4b5f(__spreadProps(__spreadValues({}, props2), {
    suppressTextValueWarning: true
  }));
  useEffect(() => {
    let selectedKey = state2.selectedKey;
    if (state2.selectionManager.isEmpty || !state2.collection.getItem(selectedKey)) {
      selectedKey = state2.collection.getFirstKey();
      state2.selectionManager.replaceSelection(selectedKey);
    }
    if (state2.selectionManager.focusedKey == null)
      state2.selectionManager.setFocusedKey(selectedKey);
  }, [
    state2.selectionManager,
    state2.selectedKey,
    state2.collection
  ]);
  return state2;
}
function Tabs(props2) {
  const _a2 = props2, {
    size = "md",
    children,
    className
  } = _a2, otherProps = __objRest(_a2, [
    "size",
    "children",
    "className"
  ]);
  const domRef = useRef(null);
  const tablistRef = useRef(null);
  const [selectedTab, setSelectedTab] = useState(null);
  const tabListState = $ead76093e5740fb6$export$4ba071daf4e486(__spreadProps(__spreadValues({}, props2), {
    children: children[0].props.children
  }));
  useEffect(() => {
    if (tablistRef.current) {
      const selectedTabEl = tablistRef.current.querySelector(`[data-key="${tabListState == null ? void 0 : tabListState.selectedKey}"]`);
      if (selectedTabEl != null) {
        setSelectedTab(selectedTabEl);
      }
    }
  }, [children, tabListState == null ? void 0 : tabListState.selectedKey, tablistRef]);
  return /* @__PURE__ */ jsx(TabContext.Provider, {
    value: {
      tabProps: __spreadProps(__spreadValues({}, props2), {
        size
      }),
      tabState: {
        tabListState,
        selectedTab
      },
      refs: {
        tablistRef
      }
    },
    children: /* @__PURE__ */ jsx("div", __spreadProps(__spreadValues({
      className: clsx(className, "max-w-full overflow-hidden")
    }, $65484d02dcb7eb3e$export$457c3d6518dd4c6f(otherProps)), {
      ref: domRef,
      children
    }))
  });
}
const FormatUnderlinedIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M12 17c3.31 0 6-2.69 6-6V3h-2.5v8c0 1.93-1.57 3.5-3.5 3.5S8.5 12.93 8.5 11V3H6v8c0 3.31 2.69 6 6 6zm-7 2v2h14v-2H5z"
}), "FormatUnderlinedOutlined");
const FormatStrikethroughIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M10 19h4v-3h-4v3zM5 4v3h5v3h4V7h5V4H5zM3 14h18v-2H3v2z"
}), "FormatStrikethroughOutlined");
const FormatItalicIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M10 4v3h2.21l-3.42 8H6v3h8v-3h-2.21l3.42-8H18V4h-8z"
}), "FormatItalicOutlined");
const FormatAlignRightIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M3 21h18v-2H3v2zm6-4h12v-2H9v2zm-6-4h18v-2H3v2zm6-4h12V7H9v2zM3 3v2h18V3H3z"
}), "FormatAlignRightOutlined");
const FormatAlignLeftIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M15 15H3v2h12v-2zm0-8H3v2h12V7zM3 13h18v-2H3v2zm0 8h18v-2H3v2zM3 3v2h18V3H3z"
}), "FormatAlignLeftOutlined");
const FormatAlignCenterIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M7 15v2h10v-2H7zm-4 6h18v-2H3v2zm0-8h18v-2H3v2zm4-6v2h10V7H7zM3 3v2h18V3H3z"
}), "FormatAlignCenterOutlined");
function TextStyleTabPanel() {
  return /* @__PURE__ */ jsxs("div", {
    className: "flex gap-20 justify-center",
    children: [/* @__PURE__ */ jsx(FontSizeSelector, {}), /* @__PURE__ */ jsx(StyleSelector, {}), /* @__PURE__ */ jsx(AlignmentSelector, {})]
  });
}
function FontSizeSelector() {
  var _a2;
  const fontSize = (_a2 = useStore$1((s2) => s2.objects.active.editableProps.fontSize)) != null ? _a2 : 40;
  const {
    formatMessage: formatMessage2
  } = useIntl();
  return /* @__PURE__ */ jsx(NumberField, {
    size: "xs",
    "aria-label": formatMessage2({
      id: "SqP3AR",
      defaultMessage: [{
        "type": 0,
        "value": "Font Size"
      }]
    }),
    minValue: 1,
    maxValue: 300,
    className: "w-64 flex-shrink-0",
    value: fontSize,
    onChange: (value) => {
      tools().objects.setValues({
        fontSize: value
      });
      state().setDirty(true);
    }
  });
}
function StyleSelector() {
  const fontStyle = useStore$1((s2) => s2.objects.active.editableProps.fontStyle);
  const underline = useStore$1((s2) => s2.objects.active.editableProps.underline);
  const linethrough = useStore$1((s2) => s2.objects.active.editableProps.linethrough);
  const [styles, setStyles] = useState([fontStyle, underline && "underline", linethrough && "linethrough"]);
  return /* @__PURE__ */ jsxs(ButtonGroup, {
    size: "xs",
    variant: "outline",
    radius: "rounded",
    value: styles,
    multiple: true,
    onChange: (newStyles) => {
      setStyles(newStyles);
      tools().objects.setValues({
        underline: newStyles.includes("underline"),
        linethrough: newStyles.includes("linethrough"),
        fontStyle: newStyles.includes("italic") ? "italic" : ""
      });
      state().setDirty(true);
    },
    children: [/* @__PURE__ */ jsx(IconButton, {
      value: "underline",
      children: /* @__PURE__ */ jsx(FormatUnderlinedIcon, {})
    }), /* @__PURE__ */ jsx(IconButton, {
      value: "linethrough",
      children: /* @__PURE__ */ jsx(FormatStrikethroughIcon, {})
    }), /* @__PURE__ */ jsx(IconButton, {
      value: "italic",
      children: /* @__PURE__ */ jsx(FormatItalicIcon, {})
    })]
  });
}
function AlignmentSelector() {
  const textAlign = useStore$1((s2) => s2.objects.active.editableProps.textAlign);
  return /* @__PURE__ */ jsxs(ButtonGroup, {
    size: "xs",
    variant: "outline",
    radius: "rounded",
    value: textAlign,
    onChange: (newAlign) => {
      tools().objects.setValues({
        textAlign: newAlign
      });
      state().setDirty(true);
    },
    children: [/* @__PURE__ */ jsx(IconButton, {
      value: "left",
      children: /* @__PURE__ */ jsx(FormatAlignLeftIcon, {})
    }), /* @__PURE__ */ jsx(IconButton, {
      value: "center",
      children: /* @__PURE__ */ jsx(FormatAlignCenterIcon, {})
    }), /* @__PURE__ */ jsx(IconButton, {
      value: "right",
      children: /* @__PURE__ */ jsx(FormatAlignRightIcon, {})
    })]
  });
}
function TabPanels(props2) {
  const {
    tabState,
    tabProps
  } = useContext(TabContext);
  const {
    tabListState
  } = tabState;
  const factory = (nodes) => new $80be09205507c5ec$export$d085fb9e920b5ca7(nodes);
  const collection = $54e9526d7573190f$export$6cd28814d92fa9c9(__spreadValues({
    items: tabProps.items
  }, props2), factory, {
    suppressTextValueWarning: true
  });
  const selectedItem = tabListState ? collection.getItem(tabListState.selectedKey) : null;
  return /* @__PURE__ */ createElement(TabPanel, __spreadProps(__spreadValues({}, props2), {
    key: tabListState == null ? void 0 : tabListState.selectedKey
  }), selectedItem && selectedItem.props.children);
}
function TabPanel(props2) {
  const {
    children,
    className
  } = props2;
  const {
    tabState
  } = useContext(TabContext);
  const ref = useRef(null);
  const {
    tabPanelProps
  } = $bc77009ac794dd15$export$fae0121b5afe572d(props2, tabState.tabListState, ref);
  return /* @__PURE__ */ jsx($503734efc0922182$export$1a38b4ad7f578e1d, {
    focusRingClass: "outline-primary-light",
    children: /* @__PURE__ */ jsx("div", __spreadProps(__spreadValues({
      className
    }, tabPanelProps), {
      ref,
      children
    }))
  });
}
const DEFAULT_GRADIENTS = [{
  type: "linear",
  coords: {
    x1: -80,
    y1: 0,
    x2: 80,
    y2: 0
  },
  colorStops: [{
    color: "#ffe47b",
    offset: 0
  }, {
    color: "rgb(111,154,211)",
    offset: 1
  }]
}, {
  type: "linear",
  coords: {
    x1: 0,
    y1: -120,
    x2: 0,
    y2: 120
  },
  colorStops: [{
    color: "#ff4040",
    offset: 0
  }, {
    color: "#e6399b",
    offset: 1
  }]
}, {
  type: "linear",
  coords: {
    x1: -90,
    y1: -90,
    x2: 90,
    y2: 90
  },
  colorStops: [{
    offset: 0,
    color: "rgb(166,111,213)"
  }, {
    offset: 0.5,
    color: "rgba(106, 72, 215, 0.5)"
  }, {
    offset: 1,
    color: "#200772"
  }]
}, {
  type: "radial",
  coords: {
    r1: 100,
    r2: 10,
    x1: 0,
    y1: 0,
    x2: 0,
    y2: 0
  },
  colorStops: [{
    offset: 0,
    color: "#FF4F4F"
  }, {
    offset: 1,
    color: "rgb(255, 239, 64)"
  }]
}, {
  type: "radial",
  coords: {
    r1: 100,
    r2: 10,
    x1: 0,
    y1: 0,
    x2: 20,
    y2: 20
  },
  colorStops: [{
    offset: 0,
    color: "#ffe47b"
  }, {
    offset: 0.5,
    color: "rgb(111,154,211)"
  }, {
    offset: 1,
    color: "rgb(166,111,213)"
  }]
}, {
  type: "radial",
  coords: {
    r1: 50,
    r2: 80,
    x1: 45,
    y1: 45,
    x2: 52,
    y2: 50
  },
  colorStops: [{
    offset: 0,
    color: "rgb(155, 237, 0)"
  }, {
    offset: 1,
    color: "rgba(0, 164, 128,0.4)"
  }]
}, {
  type: "linear",
  coords: {
    x1: -90,
    y1: -90,
    x2: 90,
    y2: 90
  },
  colorStops: [{
    offset: 0,
    color: "#9ecb2d"
  }, {
    offset: 0.5,
    color: "#72aa00"
  }, {
    offset: 1,
    color: "#bfd255"
  }]
}, {
  type: "radial",
  coords: {
    r1: 100,
    r2: 50,
    x1: 30,
    y1: 0,
    x2: 0,
    y2: 0
  },
  colorStops: [{
    offset: 0,
    color: "#aebcbf"
  }, {
    offset: 1,
    color: "#0a0809"
  }]
}, {
  type: "linear",
  coords: {
    x1: -80,
    y1: 0,
    x2: 80,
    y2: 0
  },
  colorStops: [{
    offset: 0,
    color: "#ffffff"
  }, {
    offset: 1,
    color: "#f6f6f6"
  }]
}, {
  type: "linear",
  coords: {
    x1: 0,
    y1: -120,
    x2: 0,
    y2: 120
  },
  colorStops: [{
    offset: 0,
    color: "#fefcea"
  }, {
    offset: 1,
    color: "#f1da36"
  }]
}, {
  type: "linear",
  coords: {
    x1: -90,
    y1: -90,
    x2: 90,
    y2: 90
  },
  colorStops: [{
    offset: 0,
    color: "rgb(166,111,213)"
  }, {
    offset: 0.5,
    color: "rgba(106, 72, 215, 0.5)"
  }, {
    offset: 1,
    color: "#ff1a00"
  }]
}, {
  type: "linear",
  coords: {
    x1: 0,
    y1: -120,
    x2: 0,
    y2: 120
  },
  colorStops: [{
    offset: 0,
    color: "#b7deed"
  }, {
    offset: 1,
    color: "#21b4e2"
  }]
}, {
  type: "linear",
  coords: {
    x1: -80,
    y1: 100,
    x2: 80,
    y2: -100
  },
  colorStops: [{
    offset: 0,
    color: "#ffe47b"
  }, {
    offset: 1,
    color: "rgb(111,154,211)"
  }]
}];
const TextureIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M19.51 3.08 3.08 19.51c.09.34.27.65.51.9.25.24.56.42.9.51L20.93 4.49c-.19-.69-.73-1.23-1.42-1.41zM11.88 3 3 11.88v2.83L14.71 3h-2.83zM5 3c-1.1 0-2 .9-2 2v2l4-4H5zm14 18c.55 0 1.05-.22 1.41-.59.37-.36.59-.86.59-1.41v-2l-4 4h2zm-9.71 0h2.83L21 12.12V9.29L9.29 21z"
}), "TextureOutlined");
const GradientIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M11 9h2v2h-2V9zm-2 2h2v2H9v-2zm4 0h2v2h-2v-2zm2-2h2v2h-2V9zM7 9h2v2H7V9zm12-6H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 18H7v-2h2v2zm4 0h-2v-2h2v2zm4 0h-2v-2h2v2zm2-7h-2v2h2v2h-2v-2h-2v2h-2v-2h-2v2H9v-2H7v2H5v-2h2v-2H5V5h14v6z"
}), "GradientOutlined");
const AddPhotoAlternateIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M18 20H4V6h9V4H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-9h-2v9zm-7.79-3.17-1.96-2.36L5.5 18h11l-3.54-4.71zM20 4V1h-2v3h-3c.01.01 0 2 0 2h3v2.99c.01.01 2 0 2 0V6h3V4h-3z"
}), "AddPhotoAlternateOutlined");
function ColorTabPanel({
  property
}) {
  const {
    formatMessage: formatMessage2
  } = useIntl();
  const currentColor = useStore$1((s2) => s2.objects.active.editableProps[property]);
  return /* @__PURE__ */ jsxs(Fragment, {
    children: [/* @__PURE__ */ jsx(ColorPickerButton, {
      size: "xs",
      "aria-label": formatMessage2({
        id: "uMhpKe",
        defaultMessage: [{
          "type": 0,
          "value": "Color"
        }]
      }),
      value: typeof currentColor === "string" ? currentColor : defaultObjectProps.fill,
      onChange: (newColor) => {
        tools().objects.setValues({
          [property]: newColor
        });
        state().setDirty(true);
      }
    }), /* @__PURE__ */ jsx(FillSelector, {
      type: "gradient",
      property
    }), /* @__PURE__ */ jsx(FillSelector, {
      type: "texture",
      property
    })]
  });
}
function FillSelector({
  type,
  property
}) {
  const startIcon = type === "texture" ? /* @__PURE__ */ jsx(TextureIcon, {}) : /* @__PURE__ */ jsx(GradientIcon, {});
  return /* @__PURE__ */ jsx(Fragment, {
    children: /* @__PURE__ */ jsxs(DialogTrigger, {
      type: "popover",
      children: [/* @__PURE__ */ jsx(Button, {
        id: `${type}-panel-trigger`,
        variant: "outline",
        size: "xs",
        startIcon,
        endIcon: /* @__PURE__ */ jsx(KeyboardArrowDownIcon, {}),
        children: /* @__PURE__ */ jsx("span", {
          className: "capitalize",
          children: type === "gradient" ? /* @__PURE__ */ jsx(FormattedMessage$1, {
            id: "y/FCma",
            defaultMessage: [{
              "type": 0,
              "value": "Gradient"
            }]
          }) : /* @__PURE__ */ jsx(FormattedMessage$1, {
            id: "ktqcD5",
            defaultMessage: [{
              "type": 0,
              "value": "Texture"
            }]
          })
        })
      }), (dialogState) => {
        return /* @__PURE__ */ jsx(Dialog, {
          children: /* @__PURE__ */ jsx("div", {
            className: "grid gap-8 grid-cols-5-min-content p-10 bg-paper rounded shadow-md",
            children: /* @__PURE__ */ jsx(PreviewButtons, {
              property,
              closeOverlay: dialogState.close,
              type
            })
          })
        });
      }]
    })
  });
}
function PreviewButtons({
  closeOverlay,
  type,
  property
}) {
  const iterator = Array.from(Array(type === "gradient" ? DEFAULT_GRADIENTS.length : 28).keys());
  const previewBtnClass = "w-56 h-56 bg border shadow-sm hover:scale-110";
  const previewBtns = iterator.map((index2) => {
    const previewUrl = assetUrl(`images/${type}s/${index2}.png`);
    return /* @__PURE__ */ jsx(ButtonBase, {
      radius: "rounded",
      className: previewBtnClass,
      style: {
        backgroundImage: `url(${previewUrl})`
      },
      "aria-label": `Select ${type} #${index2}`,
      onPress: async () => {
        closeOverlay();
        const value = type === "gradient" ? new fabric.fabric.Gradient(DEFAULT_GRADIENTS[index2]) : await patternFromUrlOrData(previewUrl);
        tools().objects.setValues({
          [property]: value
        });
        state().setDirty(true);
      }
    }, index2);
  });
  if (type === "texture") {
    previewBtns.unshift(/* @__PURE__ */ jsx(UploadButton, {
      property,
      closeOverlay,
      className: previewBtnClass
    }, "upload-btn"));
  }
  return /* @__PURE__ */ jsx(Fragment, {
    children: previewBtns
  });
}
function UploadButton({
  className,
  closeOverlay,
  property
}) {
  return /* @__PURE__ */ jsx(ButtonBase, {
    radius: "rounded",
    className,
    "aria-label": "Upload an image",
    onPress: async () => {
      const file = await tools().import.openUploadWindow();
      closeOverlay();
      if (file) {
        const pattern = await patternFromUrlOrData(await file.data);
        tools().objects.setValues({
          [property]: pattern
        });
      }
    },
    children: /* @__PURE__ */ jsx(AddPhotoAlternateIcon, {
      className: "icon-md"
    })
  });
}
function patternFromUrlOrData(data) {
  return new Promise((resolve) => {
    fabric.fabric.util.loadImage(data, (img) => {
      const pattern = new fabric.fabric.Pattern({
        source: img,
        repeat: "repeat"
      });
      resolve(pattern);
    });
  });
}
function OpacityTabPanel() {
  const opacity = useStore$1((s2) => s2.objects.active.editableProps.opacity);
  return /* @__PURE__ */ jsx(Slider, {
    className: "max-w-240",
    "aria-label": "Opacity",
    value: opacity,
    minValue: 0.1,
    step: 0.1,
    maxValue: 1,
    onChange: (newOpacity) => {
      tools().objects.setValues({
        opacity: newOpacity
      });
      state().setDirty(true);
    }
  });
}
function OutlineTabPanel() {
  const {
    formatMessage: formatMessage2
  } = useIntl();
  const outlineColor = useStore$1((s2) => s2.objects.active.editableProps.stroke);
  const outlineWidth = useStore$1((s2) => s2.objects.active.editableProps.strokeWidth);
  return /* @__PURE__ */ jsxs(Fragment, {
    children: [/* @__PURE__ */ jsx(ColorPickerButton, {
      size: "xs",
      value: outlineColor,
      "aria-label": formatMessage2({
        id: "k1rbG0",
        defaultMessage: [{
          "type": 0,
          "value": "Outline Color"
        }]
      }),
      onChange: (newColor) => {
        tools().objects.setValues({
          stroke: newColor
        });
        state().setDirty(true);
      }
    }), /* @__PURE__ */ jsx(Slider, {
      "aria-label": "Outline Width",
      className: "max-w-240",
      value: outlineWidth,
      onChange: (newWidth) => {
        tools().objects.setValues({
          strokeWidth: newWidth
        });
        state().setDirty(true);
      }
    })]
  });
}
const ImageIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-4.86 8.86-3 3.87L9 13.14 6 17h12l-3.86-5.14z"
}), "ImageOutlined");
function ImageTabPanel() {
  return /* @__PURE__ */ jsx("div", {
    children: /* @__PURE__ */ jsx(Button, {
      type: "button",
      variant: "outline",
      size: "xs",
      startIcon: /* @__PURE__ */ jsx(ImageIcon, {}),
      radius: "rounded-full",
      onPress: async () => {
        const file = await tools().import.openUploadWindow();
        if (file) {
          const active = tools().objects.getActive();
          if (active && "setSrc" in active) {
            const fileData = await file.data;
            active.setSrc(fileData, () => {
              fireObjModifiedEvent({
                src: fileData
              });
              tools().canvas.render();
            });
          }
        }
      },
      children: /* @__PURE__ */ jsx(FormattedMessage$1, {
        id: "cYfRr+",
        defaultMessage: [{
          "type": 0,
          "value": "Replace Image"
        }]
      })
    })
  });
}
const shadowDefaults = {
  color: "rgba(0, 0, 0, 0.6)",
  blur: 3,
  offsetX: -1,
  offsetY: 0
};
function ShadowTabPanel() {
  const {
    formatMessage: formatMessage2
  } = useIntl();
  const shadow = useStore$1((s2) => s2.objects.active.editableProps.shadow) || shadowDefaults;
  return /* @__PURE__ */ jsxs(Fragment, {
    children: [/* @__PURE__ */ jsx(ColorPickerButton, {
      value: shadow.color,
      size: "xs",
      "aria-label": formatMessage2({
        id: "cPxU+s",
        defaultMessage: [{
          "type": 0,
          "value": "Shadow Color"
        }]
      }),
      onChange: (color2) => {
        tools().objects.setValues({
          shadow: modifiedShadow({
            color: color2
          })
        });
        state().setDirty(true);
      }
    }), /* @__PURE__ */ jsx(Slider, {
      "aria-label": "Shadow Blur",
      className: "max-w-240",
      defaultValue: shadow.blur,
      onChange: (blur) => {
        tools().objects.setValues({
          shadow: modifiedShadow({
            blur
          })
        });
        state().setDirty(true);
      }
    })]
  });
}
function modifiedShadow(options) {
  var _a2;
  const current = (_a2 = tools().objects.getActive()) == null ? void 0 : _a2.shadow;
  if (current) {
    Object.entries(options).forEach(([key, val]) => {
      current[key] = val;
    });
    return current;
  }
  return new fabric.fabric.Shadow(__spreadValues(__spreadValues({}, shadowDefaults), options));
}
function ActiveObjectControls() {
  const active = useStore$1((s2) => s2.objects.active);
  return /* @__PURE__ */ jsxs(Tabs, {
    size: "sm",
    className: "pb-18 pt-6",
    children: [/* @__PURE__ */ jsxs(TabList, {
      children: [active.isText && /* @__PURE__ */ jsx($89e587cd0f107a73$export$6d08773d2e66f8f2, {
        children: /* @__PURE__ */ jsx(FormattedMessage$1, {
          id: "A3jj9z",
          defaultMessage: [{
            "type": 0,
            "value": "Font"
          }]
        })
      }, "font"), !active.isImage && /* @__PURE__ */ jsx($89e587cd0f107a73$export$6d08773d2e66f8f2, {
        children: /* @__PURE__ */ jsx(FormattedMessage$1, {
          id: "uMhpKe",
          defaultMessage: [{
            "type": 0,
            "value": "Color"
          }]
        })
      }, "fill"), !active.isImage && /* @__PURE__ */ jsx($89e587cd0f107a73$export$6d08773d2e66f8f2, {
        children: /* @__PURE__ */ jsx(FormattedMessage$1, {
          id: "XQZA8e",
          defaultMessage: [{
            "type": 0,
            "value": "Background"
          }]
        })
      }, "bgColor"), active.isImage && /* @__PURE__ */ jsx($89e587cd0f107a73$export$6d08773d2e66f8f2, {
        children: /* @__PURE__ */ jsx(FormattedMessage$1, {
          id: "+0zv6g",
          defaultMessage: [{
            "type": 0,
            "value": "Image"
          }]
        })
      }, "image"), /* @__PURE__ */ jsx($89e587cd0f107a73$export$6d08773d2e66f8f2, {
        children: /* @__PURE__ */ jsx(FormattedMessage$1, {
          id: "PHutSR",
          defaultMessage: [{
            "type": 0,
            "value": "Opacity"
          }]
        })
      }, "opacity"), /* @__PURE__ */ jsx($89e587cd0f107a73$export$6d08773d2e66f8f2, {
        children: /* @__PURE__ */ jsx(FormattedMessage$1, {
          id: "aEhjYg",
          defaultMessage: [{
            "type": 0,
            "value": "Outline"
          }]
        })
      }, "outline"), /* @__PURE__ */ jsx($89e587cd0f107a73$export$6d08773d2e66f8f2, {
        children: /* @__PURE__ */ jsx(FormattedMessage$1, {
          id: "u4jNiO",
          defaultMessage: [{
            "type": 0,
            "value": "Shadow"
          }]
        })
      }, "shadow")]
    }), /* @__PURE__ */ jsxs(TabPanels, {
      className: "flex items-center justify-center gap-10 pt-16 h-50 w-full",
      children: [/* @__PURE__ */ jsx($89e587cd0f107a73$export$6d08773d2e66f8f2, {
        children: /* @__PURE__ */ jsx(TextStyleTabPanel, {})
      }, "font"), /* @__PURE__ */ jsx($89e587cd0f107a73$export$6d08773d2e66f8f2, {
        children: /* @__PURE__ */ jsx(ColorTabPanel, {
          property: "fill"
        })
      }, "fill"), /* @__PURE__ */ jsx($89e587cd0f107a73$export$6d08773d2e66f8f2, {
        children: /* @__PURE__ */ jsx(ColorTabPanel, {
          property: "backgroundColor"
        })
      }, "bgColor"), /* @__PURE__ */ jsx($89e587cd0f107a73$export$6d08773d2e66f8f2, {
        children: /* @__PURE__ */ jsx(ImageTabPanel, {})
      }, "image"), /* @__PURE__ */ jsx($89e587cd0f107a73$export$6d08773d2e66f8f2, {
        children: /* @__PURE__ */ jsx(OpacityTabPanel, {})
      }, "opacity"), /* @__PURE__ */ jsx($89e587cd0f107a73$export$6d08773d2e66f8f2, {
        children: /* @__PURE__ */ jsx(OutlineTabPanel, {})
      }, "outline"), /* @__PURE__ */ jsx($89e587cd0f107a73$export$6d08773d2e66f8f2, {
        children: /* @__PURE__ */ jsx(ShadowTabPanel, {})
      }, "shadow")]
    })]
  });
}
function ActiveTextControls() {
  const isMobile = useIsMobileMediaQuery();
  const actionBtn = !isMobile && /* @__PURE__ */ jsx(Button, {
    size: "sm",
    color: "primary",
    variant: "outline",
    onPress: () => {
      tools().text.add();
      state().setDirty(true);
    },
    children: /* @__PURE__ */ jsx(FormattedMessage$1, {
      id: "kWzXGg",
      defaultMessage: [{
        "type": 0,
        "value": "New Text"
      }]
    })
  });
  return /* @__PURE__ */ jsx(ToolControlsOverlayWrapper, {
    actionBtn,
    children: /* @__PURE__ */ jsx(ActiveObjectControls, {})
  });
}
function ToolControlsOverlay() {
  const activeOverlay = useStore$1((s2) => s2.activeToolOverlay);
  const activeObjId = useStore$1((s2) => s2.objects.active.id);
  const overlayCmp = getOverlay(activeOverlay, activeObjId);
  return /* @__PURE__ */ jsx("div", {
    className: "relative z-tool-overlay text-sm",
    children: /* @__PURE__ */ jsx(AnimatePresence, {
      children: overlayCmp && /* @__PURE__ */ jsx(m$2.div, {
        initial: {
          y: 0,
          opacity: 0
        },
        animate: {
          y: "-100%",
          opacity: 1
        },
        exit: {
          y: 0,
          opacity: 0
        },
        transition: {
          type: "tween",
          duration: 0.15
        },
        className: "absolute inset-x-0 gap-16 px-5vw bg bg-opacity-95 border-t",
        children: overlayCmp
      }, "tool-controls-overlay")
    })
  });
}
function getOverlay(activeOverlay, activeObjId) {
  switch (activeOverlay) {
    case ActiveToolOverlay.Filter:
      return /* @__PURE__ */ jsx(FilterControls, {});
    case ActiveToolOverlay.Frame:
      return /* @__PURE__ */ jsx(ActiveFrameControls, {});
    case ActiveToolOverlay.Text:
      return activeObjId && /* @__PURE__ */ jsx(ActiveTextControls, {});
    case ActiveToolOverlay.ActiveObject:
      return activeObjId && /* @__PURE__ */ jsx(ActiveObjectControls, {});
    default:
      return null;
  }
}
const CancelIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm3.59-13L12 10.59 8.41 7 7 8.41 10.59 12 7 15.59 8.41 17 12 13.41 15.59 17 17 15.59 13.41 12 17 8.41z"
}), "CancelOutlined");
function FilterButton({
  filter: filter2
}) {
  const isActive = useStore$1((s2) => s2.filter.applied.includes(filter2));
  const hasOptions = tools().filter.hasOptions(filter2);
  const className = clsx("block flex-shrink-0 rounded", {
    "text-primary border-primary": isActive
  });
  const msg = filterNameMessages[filter2];
  const content = /* @__PURE__ */ jsxs(Fragment, {
    children: [/* @__PURE__ */ jsxs("div", {
      className: "relative",
      children: [/* @__PURE__ */ jsx(FilterImg, {
        filter: filter2
      }), isActive && /* @__PURE__ */ jsx(ActiveOverlay$1, {
        filter: filter2,
        hasOptions
      })]
    }), /* @__PURE__ */ jsx("div", {
      className: "mt-4 text-center text-xs capitalize",
      children: msg ? /* @__PURE__ */ jsx(FormattedMessage$1, __spreadValues({}, msg)) : filter2
    })]
  });
  if (isActive && hasOptions) {
    return /* @__PURE__ */ jsx("div", {
      className,
      children: content
    });
  }
  return /* @__PURE__ */ jsx(ButtonBase, {
    className,
    onPress: () => {
      if (isActive) {
        tools().filter.remove(filter2);
      } else {
        tools().filter.apply(filter2);
      }
    },
    children: content
  });
}
function FilterImg({
  filter: filter2
}) {
  const isSelected = useStore$1((s2) => s2.filter.selected === filter2);
  const className = clsx("m-auto w-96 h-56 border rounded object-cover", {
    shadow: isSelected
  });
  return /* @__PURE__ */ jsx("img", {
    src: assetUrl(`images/filter/${filter2}.jpg`),
    className,
    alt: ""
  });
}
function ActiveOverlay$1({
  filter: filter2,
  hasOptions
}) {
  const removeBtn = /* @__PURE__ */ jsx(IconButton, {
    color: "primary",
    size: "md",
    onPress: () => {
      tools().filter.remove(filter2);
    },
    children: /* @__PURE__ */ jsx(CancelIcon, {})
  });
  return /* @__PURE__ */ jsxs("div", {
    className: "flex items-center justify-center bg-background/70 absolute inset-0 border-2 border-primary rounded",
    children: [hasOptions ? removeBtn : /* @__PURE__ */ jsx(CancelIcon, {
      className: "svg-icon icon-md"
    }), hasOptions && /* @__PURE__ */ jsx(ToggleSettingsButton, {
      filter: filter2,
      hasOptions
    })]
  });
}
function ToggleSettingsButton({
  filter: filter2,
  hasOptions
}) {
  return /* @__PURE__ */ jsx(IconButton, {
    color: "primary",
    size: "md",
    onPress: () => {
      if (state().activeToolOverlay === ActiveToolOverlay.Filter && state().filter.selected === filter2) {
        state().setActiveTool(state().activeTool, null);
      } else {
        state().filter.select(filter2, hasOptions);
      }
    },
    children: /* @__PURE__ */ jsx(TuneIcon, {})
  });
}
const ScrollableView = forwardRef(({
  children,
  className,
  gap
}, ref) => {
  const extendedChildren = React__default.Children.map(children, (child, i2) => {
    if (React__default.isValidElement(child)) {
      return React__default.cloneElement(child, {
        isFirst: i2 === 0,
        isLast: React__default.Children.count(children) === i2 + 1
      });
    }
    return child;
  });
  return /* @__PURE__ */ jsx("div", {
    ref,
    className: `tiny-scrollbar pb-4 overflow-x-auto relative flex items-center ${gap || "gap-10"} ${className}`,
    children: extendedChildren
  });
});
function ScrollableViewItem({
  isFirst,
  isLast,
  children,
  className
}) {
  const mergedClass = clsx(className, "flex-shrink-0", {
    "ml-auto": isFirst,
    "mr-auto": isLast
  });
  return /* @__PURE__ */ jsx("div", {
    className: mergedClass,
    children
  });
}
function FilterNav() {
  const filters = useStore$1((s2) => {
    var _a2, _b;
    return (_b = (_a2 = s2.config.tools) == null ? void 0 : _a2.filter) == null ? void 0 : _b.items;
  }) || [];
  useEffect(() => {
    tools().filter.syncState();
  }, []);
  const filterBtns = filters.map((filter2) => /* @__PURE__ */ jsx(ScrollableViewItem, {
    children: /* @__PURE__ */ jsx(FilterButton, {
      filter: filter2
    })
  }, filter2));
  return /* @__PURE__ */ jsx(ScrollableView, {
    children: filterBtns
  });
}
function $parcel$export$4(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $5ff2beda28820a2f$exports = {};
$parcel$export$4($5ff2beda28820a2f$exports, "useToggleState", () => $5ff2beda28820a2f$export$8042c6c013fd5226);
function $5ff2beda28820a2f$export$8042c6c013fd5226(props2 = {}) {
  let { isReadOnly } = props2;
  let [isSelected, setSelected] = $bfee1151ccb0650f$export$40bfa8c7b0832715(props2.isSelected, props2.defaultSelected || false, props2.onChange);
  function updateSelected(value) {
    if (!isReadOnly)
      setSelected(value);
  }
  function toggleState() {
    if (!isReadOnly)
      setSelected(!isSelected);
  }
  return {
    isSelected,
    setSelected: updateSelected,
    toggle: toggleState
  };
}
function $parcel$export$3(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $9f08aaca62c37bf3$exports = {};
$parcel$export$3($9f08aaca62c37bf3$exports, "useToggle", () => $9f08aaca62c37bf3$export$cbe85ee05b554577);
function $9f08aaca62c37bf3$export$cbe85ee05b554577(props2, state2, ref) {
  let { isDisabled = false, isRequired, isReadOnly, value, name, children, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledby, validationState = "valid" } = props2;
  let onChange = (e2) => {
    e2.stopPropagation();
    state2.setSelected(e2.target.checked);
  };
  let hasChildren = children != null;
  let hasAriaLabel = ariaLabel != null || ariaLabelledby != null;
  if (!hasChildren && !hasAriaLabel)
    console.warn("If you do not provide children, you must specify an aria-label for accessibility");
  let { pressProps } = $f6c31cce2adf654f$export$45712eceda6fad21({
    isDisabled
  });
  let { focusableProps } = $391c6482f25a1991$export$4c014de7c8940b4c(props2, ref);
  let interactions = $3ef42575df84b30b$export$9d1611c77c2fe928(pressProps, focusableProps);
  let domProps = $65484d02dcb7eb3e$export$457c3d6518dd4c6f(props2, {
    labelable: true
  });
  return {
    inputProps: $3ef42575df84b30b$export$9d1611c77c2fe928(domProps, __spreadValues({
      "aria-invalid": validationState === "invalid" || void 0,
      "aria-errormessage": props2["aria-errormessage"],
      "aria-controls": props2["aria-controls"],
      "aria-readonly": isReadOnly || void 0,
      "aria-required": isRequired || void 0,
      onChange,
      disabled: isDisabled,
      value,
      name,
      type: "checkbox"
    }, interactions))
  };
}
function $parcel$export$2(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $fea2f35efc29884c$exports = {};
$parcel$export$2($fea2f35efc29884c$exports, "useCheckbox", () => $fea2f35efc29884c$export$e375f10ce42261c5);
function $fea2f35efc29884c$export$e375f10ce42261c5(props2, state2, inputRef) {
  let { inputProps } = $9f08aaca62c37bf3$export$cbe85ee05b554577(props2, state2, inputRef);
  let { isSelected } = state2;
  let { isIndeterminate } = props2;
  useEffect(() => {
    if (inputRef.current)
      inputRef.current.indeterminate = isIndeterminate;
  });
  return {
    inputProps: __spreadProps(__spreadValues({}, inputProps), {
      checked: isSelected,
      "aria-checked": isIndeterminate ? "mixed" : isSelected
    })
  };
}
var $ec288cd435d5d49a$exports = {};
$parcel$export$2($ec288cd435d5d49a$exports, "useCheckboxGroup", () => $ec288cd435d5d49a$export$49ff6f28c54f1cbe);
const $61350709ee325005$export$31440636951aa68c = /* @__PURE__ */ new WeakMap();
function $ec288cd435d5d49a$export$49ff6f28c54f1cbe(props2, state2) {
  let { isDisabled, name } = props2;
  let { labelProps, fieldProps } = $6f8f5e0de5a77844$export$8467354a121f1b9f(__spreadProps(__spreadValues({}, props2), {
    labelElementType: "span"
  }));
  let domProps = $65484d02dcb7eb3e$export$457c3d6518dd4c6f(props2, {
    labelable: true
  });
  $61350709ee325005$export$31440636951aa68c.set(state2, name);
  return {
    groupProps: $3ef42575df84b30b$export$9d1611c77c2fe928(domProps, __spreadValues({
      role: "group",
      "aria-disabled": isDisabled || void 0
    }, fieldProps)),
    labelProps
  };
}
var $a84307d0769c22d8$exports = {};
$parcel$export$2($a84307d0769c22d8$exports, "useCheckboxGroupItem", () => $a84307d0769c22d8$export$353b32fc6898d37d);
function $a84307d0769c22d8$export$353b32fc6898d37d(props2, state2, inputRef) {
  const toggleState = $5ff2beda28820a2f$export$8042c6c013fd5226({
    isReadOnly: props2.isReadOnly || state2.isReadOnly,
    isSelected: state2.isSelected(props2.value),
    onChange(isSelected) {
      if (isSelected)
        state2.addValue(props2.value);
      else
        state2.removeValue(props2.value);
      if (props2.onChange)
        props2.onChange(isSelected);
    }
  });
  let { inputProps } = $fea2f35efc29884c$export$e375f10ce42261c5(__spreadProps(__spreadValues({}, props2), {
    isReadOnly: props2.isReadOnly || state2.isReadOnly,
    isDisabled: props2.isDisabled || state2.isDisabled,
    name: props2.name || $61350709ee325005$export$31440636951aa68c.get(state2)
  }), toggleState, inputRef);
  return {
    inputProps
  };
}
const CheckBoxOutlineBlankIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"
}), "CheckBoxOutlineBlankOutlined");
const CheckboxFilledIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M19 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.11 0 2-.9 2-2V5c0-1.1-.89-2-2-2zm-9 14-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"
}), "CheckBox");
const CheckboxGroupContext = React__default.createContext(null);
function Checkbox(props2) {
  const {
    children,
    className,
    icon,
    checkedIcon,
    isDisabled,
    value
  } = props2;
  const style2 = inputFieldStyle(__spreadProps(__spreadValues({}, props2), {
    label: children
  }));
  const Icon = icon || CheckBoxOutlineBlankIcon;
  const CheckedIcon = checkedIcon || CheckboxFilledIcon;
  const ref = useRef(null);
  const {
    isFocusVisible,
    focusProps
  } = $e63d024ca16f2165$export$4e328f61c538687f();
  const groupState = useContext(CheckboxGroupContext);
  const {
    inputProps
  } = groupState ? $a84307d0769c22d8$export$353b32fc6898d37d(__spreadProps(__spreadValues({}, props2), {
    value
  }), groupState, ref) : $fea2f35efc29884c$export$e375f10ce42261c5(props2, $5ff2beda28820a2f$export$8042c6c013fd5226(props2), ref);
  const mergedClassName = clsx("flex items-center rounded", className, {
    "outline outline-offset-2": isFocusVisible
  });
  const disabledStyle = isDisabled && "text-disabled";
  return /* @__PURE__ */ jsxs("label", {
    className: mergedClassName,
    children: [/* @__PURE__ */ jsx($5c3e21d68f1c4674$export$439d29a4e110a164, {
      children: /* @__PURE__ */ jsx("input", __spreadProps(__spreadValues(__spreadValues({}, inputProps), focusProps), {
        ref
      }))
    }), inputProps.checked ? /* @__PURE__ */ jsx(CheckedIcon, {
      className: clsx(disabledStyle || "text-primary", style2.adornment)
    }) : /* @__PURE__ */ jsx(Icon, {
      className: clsx(disabledStyle || "text-muted", style2.adornment)
    }), children && /* @__PURE__ */ jsx("div", {
      className: clsx("block capitalize ml-6", style2.size.font),
      children
    })]
  });
}
const LockIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zM9 6c0-1.66 1.34-3 3-3s3 1.34 3 3v2H9V6zm9 14H6V10h12v10zm-6-3c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2z"
}), "LockOutlined");
const LockOpenIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6h2c0-1.66 1.34-3 3-3s3 1.34 3 3v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm0 12H6V10h12v10zm-6-3c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2z"
}), "LockOpenOutlined");
function ResizeNav() {
  const {
    formatMessage: formatMessage2
  } = useIntl();
  const {
    minWidth = 50,
    minHeight = 50,
    maxHeight = 2400,
    maxWidth = 2400
  } = useStore$1((s2) => {
    var _a2;
    return (_a2 = s2.config.tools) == null ? void 0 : _a2.resize;
  }) || {};
  const originalSize = useStore$1((s2) => s2.original);
  const formVal = useStore$1((s2) => s2.resize.formValue);
  useEffect(() => {
    state().resize.setFormValue(__spreadValues({}, originalSize));
  }, [originalSize]);
  useEffect(() => {
    state().setDirty(true);
  }, []);
  const onWidthChange = (newWidth) => {
    const newVal = __spreadProps(__spreadValues({}, formVal), {
      width: newWidth
    });
    if (formVal.maintainAspect) {
      newVal.height = aspectToHeight(newWidth, formVal.usePercentages);
    }
    state().resize.setFormValue(newVal);
  };
  const onHeightChange = (newHeight) => {
    const newVal = __spreadProps(__spreadValues({}, formVal), {
      height: newHeight
    });
    if (newHeight && formVal.maintainAspect) {
      newVal.width = aspectToWidth(newHeight, formVal.usePercentages);
    }
    state().resize.setFormValue(newVal);
  };
  const onAspectChange = (isChecked) => {
    const newVal = __spreadProps(__spreadValues({}, formVal), {
      maintainAspect: isChecked
    });
    if (isChecked) {
      newVal.height = aspectToHeight(newVal.width, newVal.usePercentages);
    }
    state().resize.setFormValue(newVal);
  };
  const onSubmit = (e2) => {
    e2.preventDefault();
    state().applyChanges();
  };
  return /* @__PURE__ */ jsxs("form", {
    className: "flex items-center justify-center gap-16 w-full",
    onSubmit,
    children: [/* @__PURE__ */ jsx(NumberField, {
      minValue: minWidth,
      maxValue: maxWidth,
      size: "sm",
      className: "max-w-112",
      label: "Width",
      value: formVal.width,
      onChange: onWidthChange,
      formatOptions: {
        useGrouping: false
      }
    }), /* @__PURE__ */ jsx("div", {
      className: "mt-24",
      children: /* @__PURE__ */ jsx(Checkbox, {
        size: "md",
        isSelected: formVal.maintainAspect,
        onChange: onAspectChange,
        "aria-label": formatMessage2({
          id: "qfw+KX",
          defaultMessage: [{
            "type": 0,
            "value": "Maintain aspect ratio"
          }]
        }),
        checkedIcon: LockIcon,
        icon: LockOpenIcon
      })
    }), /* @__PURE__ */ jsx(NumberField, {
      minValue: minHeight,
      maxValue: maxHeight,
      size: "sm",
      className: "max-w-112",
      label: "Height",
      value: formVal.height,
      onChange: onHeightChange,
      formatOptions: {
        useGrouping: false
      }
    }), /* @__PURE__ */ jsx("button", {
      type: "submit",
      className: "hidden",
      children: /* @__PURE__ */ jsx(FormattedMessage$1, {
        id: "4dL9o7",
        defaultMessage: [{
          "type": 0,
          "value": "Resize"
        }]
      })
    })]
  });
}
function CropPresetBtns() {
  var _a2;
  const presets = useStore$1((s2) => {
    var _a3, _b;
    return (_b = (_a3 = s2.config.tools) == null ? void 0 : _a3.crop) == null ? void 0 : _b.presets;
  }) || [];
  const selectedRatio = useStore$1((s2) => s2.crop.selectedAspectRatio);
  const allowCustomRatio = (_a2 = useStore$1((s2) => {
    var _a3, _b;
    return (_b = (_a3 = s2.config.tools) == null ? void 0 : _a3.crop) == null ? void 0 : _b.allowCustomRatio;
  })) != null ? _a2 : true;
  const btns = presets.filter((preset) => {
    return preset.ratio || !preset.ratio && allowCustomRatio;
  }).map((preset) => /* @__PURE__ */ jsx(ScrollableViewItem, {
    children: /* @__PURE__ */ jsxs(ButtonBase, {
      onPress: () => tools().crop.resetCropzone(preset.ratio),
      className: "flex flex-col items-center justify-between cursor-pointer h-56",
      children: [/* @__PURE__ */ jsx(PresetPreview, {
        preset,
        selectedRatio
      }), /* @__PURE__ */ jsx(PresetName, {
        preset,
        selectedRatio
      })]
    })
  }, preset.ratio || preset.name));
  return /* @__PURE__ */ jsx(ScrollableView, {
    gap: "gap-18",
    children: btns
  });
}
function PresetPreview({
  preset,
  selectedRatio
}) {
  let width = 40;
  let height = 30;
  if (preset.ratio) {
    const ratio = aspectRatioFromStr(preset.ratio);
    ({
      width,
      height
    } = calcNewSizeFromAspectRatio(ratio, width, height));
  }
  const className = clsx("border-2", {
    "border-dotted": preset.ratio === null,
    "border-primary": selectedRatio === preset.ratio
  });
  return /* @__PURE__ */ jsx("div", {
    style: {
      width: `${width}px`,
      height: `${height}px`
    },
    className
  });
}
function PresetName({
  preset,
  selectedRatio
}) {
  const className = clsx("mt-4 text-center text-xs", {
    "text-primary": selectedRatio === preset.ratio
  });
  return /* @__PURE__ */ jsx("div", {
    className,
    children: preset.name || preset.ratio
  });
}
const FlipIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M15 21h2v-2h-2v2zm4-12h2V7h-2v2zM3 5v14c0 1.1.9 2 2 2h4v-2H5V5h4V3H5c-1.1 0-2 .9-2 2zm16-2v2h2c0-1.1-.9-2-2-2zm-8 20h2V1h-2v22zm8-6h2v-2h-2v2zM15 5h2V3h-2v2zm4 8h2v-2h-2v2zm0 8c1.1 0 2-.9 2-2h-2v2z"
}), "FlipOutlined");
function FlipBtns() {
  return /* @__PURE__ */ jsxs("div", {
    children: [/* @__PURE__ */ jsx(IconButton, {
      size: "sm",
      onPress: () => {
        tools().transform.flip("vertical");
        state().setDirty(true);
      },
      children: /* @__PURE__ */ jsx(FlipIcon, {})
    }), /* @__PURE__ */ jsx(IconButton, {
      size: "sm",
      onPress: () => {
        tools().transform.flip("horizontal");
        state().setDirty(true);
      },
      children: /* @__PURE__ */ jsx(FlipIcon, {
        className: "rotate-90"
      })
    })]
  });
}
const RotateLeftIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M7.11 8.53 5.7 7.11C4.8 8.27 4.24 9.61 4.07 11h2.02c.14-.87.49-1.72 1.02-2.47zM6.09 13H4.07c.17 1.39.72 2.73 1.62 3.89l1.41-1.42c-.52-.75-.87-1.59-1.01-2.47zm1.01 5.32c1.16.9 2.51 1.44 3.9 1.61V17.9c-.87-.15-1.71-.49-2.46-1.03L7.1 18.32zM13 4.07V1L8.45 5.55 13 10V6.09c2.84.48 5 2.94 5 5.91s-2.16 5.43-5 5.91v2.02c3.95-.49 7-3.85 7-7.93s-3.05-7.44-7-7.93z"
}), "RotateLeftOutlined");
const RotateRightIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M15.55 5.55 11 1v3.07C7.06 4.56 4 7.92 4 12s3.05 7.44 7 7.93v-2.02c-2.84-.48-5-2.94-5-5.91s2.16-5.43 5-5.91V10l4.55-4.45zM19.93 11c-.17-1.39-.72-2.73-1.62-3.89l-1.42 1.42c.54.75.88 1.6 1.02 2.47h2.02zM13 17.9v2.02c1.39-.17 2.74-.71 3.9-1.61l-1.44-1.44c-.75.54-1.59.89-2.46 1.03zm3.89-2.42 1.42 1.41c.9-1.16 1.45-2.5 1.62-3.89h-2.02c-.14.87-.48 1.72-1.02 2.48z"
}), "RotateRightOutlined");
function RotateBtns() {
  return /* @__PURE__ */ jsxs("div", {
    children: [/* @__PURE__ */ jsx(IconButton, {
      size: "sm",
      onPress: () => {
        tools().transform.rotateLeft();
        state().setDirty(true);
      },
      children: /* @__PURE__ */ jsx(RotateLeftIcon, {})
    }), /* @__PURE__ */ jsx(IconButton, {
      size: "sm",
      onPress: () => {
        tools().transform.rotateRight();
        state().setDirty(true);
      },
      children: /* @__PURE__ */ jsx(RotateRightIcon, {})
    })]
  });
}
function TransformWidget() {
  return /* @__PURE__ */ jsxs("div", {
    className: "flex items-center justify-center gap-16",
    children: [/* @__PURE__ */ jsx(FlipBtns, {}), /* @__PURE__ */ jsx(StraightenSlider, {}), /* @__PURE__ */ jsx(RotateBtns, {})]
  });
}
function StraightenSlider() {
  const numberFormatter = $a916eb452884faea$export$b7a616150fdb9f44();
  const trackRef = useRef(null);
  const svgRef = useRef(null);
  const sliderStateOptions = {
    minValue: -45,
    maxValue: 45,
    step: 1,
    label: "Straighten",
    numberFormatter,
    defaultValue: [state().crop.straightenAngle],
    onChange: (val) => {
      const newValue = val[0];
      tools().transform.straighten(newValue);
      state().crop.setTransformAngle(newValue);
      state().setDirty(true);
      svgRef.current.style.transform = `translateX(${newValue}px)`;
    }
  };
  const sliderState = $8f011f344c0ccbcc$export$e5fda3247f5d67f9(sliderStateOptions);
  const {
    groupProps,
    trackProps,
    outputProps
  } = $330dff91662306eb$export$56b2c08e277f365(sliderStateOptions, sliderState, trackRef);
  return /* @__PURE__ */ jsx("div", __spreadProps(__spreadValues({}, groupProps), {
    className: "flex-auto flex-shrink-0 max-w-320 touch-none isolate",
    children: /* @__PURE__ */ jsxs("div", __spreadProps(__spreadValues({}, trackProps), {
      ref: trackRef,
      className: "h-36 relative",
      children: [/* @__PURE__ */ jsxs("output", __spreadProps(__spreadValues({}, outputProps), {
        className: "absolute left-1/2 top-1/2 w-40 text-center bg -translate-x-1/2 -translate-y-1/2 z-10",
        children: [sliderState.getThumbValueLabel(0), "\xB0"]
      })), /* @__PURE__ */ jsx(FreeTransformTrack, {
        ref: svgRef
      })]
    }))
  }));
}
const FreeTransformTrack = React__default.forwardRef((props2, ref) => {
  const numberOfDots = [...Array(80).keys()];
  const circles = numberOfDots.map((index2) => {
    return /* @__PURE__ */ jsx("circle", {
      cx: 2 + index2 * 10,
      cy: "20",
      r: !(index2 % 5) ? 2 : 0.75
    }, index2);
  });
  return /* @__PURE__ */ jsx("div", {
    className: "relative h-full cursor-pointer overflow-hidden",
    children: /* @__PURE__ */ jsx("svg", {
      ref,
      style: {
        width: numberOfDots.length * 10
      },
      className: "absolute -left-80 h-full fill-current",
      xmlns: "http://www.w3.org/2000/svg",
      "aria-hidden": "true",
      focusable: "false",
      children: circles
    })
  });
});
function CropNav() {
  useEffect(() => {
    state().setDirty(true);
    tools().frame.active.hide();
    return () => {
      tools().frame.active.show();
    };
  }, []);
  return /* @__PURE__ */ jsxs("div", {
    className: "pb-16",
    children: [/* @__PURE__ */ jsx("div", {
      className: "mb-10",
      children: /* @__PURE__ */ jsx(TransformWidget, {})
    }), /* @__PURE__ */ jsx(CropPresetBtns, {})]
  });
}
const CustomEllipseIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M 16 6 C 12.484375 6 9.273438 7.070313 6.90625 8.84375 C 4.539063 10.617188 3 13.15625 3 16 C 3 18.84375 4.539063 21.382813 6.90625 23.15625 C 9.273438 24.929688 12.484375 26 16 26 C 19.515625 26 22.726563 24.929688 25.09375 23.15625 C 27.460938 21.382813 29 18.84375 29 16 C 29 13.15625 27.460938 10.617188 25.09375 8.84375 C 22.726563 7.070313 19.515625 6 16 6 Z M 16 8 C 19.109375 8 21.898438 8.957031 23.875 10.4375 C 25.851563 11.917969 27 13.875 27 16 C 27 18.125 25.851563 20.082031 23.875 21.5625 C 21.898438 23.042969 19.109375 24 16 24 C 12.890625 24 10.101563 23.042969 8.125 21.5625 C 6.148438 20.082031 5 18.125 5 16 C 5 13.875 6.148438 11.917969 8.125 10.4375 C 10.101563 8.957031 12.890625 8 16 8 Z "
}));
const CustomCircleIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M 16 4 C 9.382813 4 4 9.382813 4 16 C 4 22.617188 9.382813 28 16 28 C 22.617188 28 28 22.617188 28 16 C 28 9.382813 22.617188 4 16 4 Z M 16 6 C 21.535156 6 26 10.464844 26 16 C 26 21.535156 21.535156 26 16 26 C 10.464844 26 6 21.535156 6 16 C 6 10.464844 10.464844 6 16 6 Z "
}));
const CustomSquareIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M 3 6 L 3 26 L 29 26 L 29 6 Z M 5 8 L 27 8 L 27 24 L 5 24 Z "
}));
const CustomTriangleIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M 16 4.90625 L 15.125 6.40625 L 4.71875 24.5 L 3.875 26 L 28.125 26 L 27.28125 24.5 L 16.875 6.40625 Z M 16 8.9375 L 24.65625 24 L 7.34375 24 Z "
}));
function ShapeNav() {
  const shapes = useStore$1((s2) => {
    var _a2, _b;
    return (_b = (_a2 = s2.config.tools) == null ? void 0 : _a2.shapes) == null ? void 0 : _b.items;
  }) || [];
  const shapeBtns = shapes.map((shape) => {
    return /* @__PURE__ */ jsx(ScrollableViewItem, {
      children: /* @__PURE__ */ jsx(IconButton, {
        variant: "outline",
        radius: "rounded-2xl",
        size: "xl",
        onPress: () => {
          tools().shape.addBasicShape(shape.name);
          state().setDirty(true);
        },
        children: /* @__PURE__ */ jsx(ShapeIcon, {
          shape
        })
      })
    }, shape.name);
  });
  return /* @__PURE__ */ jsx(ScrollableView, {
    children: shapeBtns
  });
}
function ShapeIcon({
  shape
}) {
  var _a2;
  if (shape.type === "Path") {
    return /* @__PURE__ */ jsx("svg", {
      className: "m-auto w-36 h-36",
      xmlns: "http://www.w3.org/2000/svg",
      viewBox: "0 -100 512 700",
      children: /* @__PURE__ */ jsx("path", {
        className: "fill-transparent stroke-current",
        d: (_a2 = shape.options) == null ? void 0 : _a2.path,
        strokeWidth: 25
      })
    });
  }
  return React__default.cloneElement(shapeIconMap[shape.name], {
    className: "w-30 h-30"
  });
}
const shapeIconMap = {
  circle: /* @__PURE__ */ jsx(CustomCircleIcon, {
    viewBox: "0 0 32 32"
  }),
  square: /* @__PURE__ */ jsx(CustomSquareIcon, {
    viewBox: "0 0 32 32"
  }),
  triangle: /* @__PURE__ */ jsx(CustomTriangleIcon, {
    viewBox: "0 0 32 32"
  }),
  ellipse: /* @__PURE__ */ jsx(CustomEllipseIcon, {
    viewBox: "0 0 32 32"
  })
};
function _extends() {
  _extends = Object.assign || function(target) {
    for (var i2 = 1; i2 < arguments.length; i2++) {
      var source = arguments[i2];
      for (var key in source) {
        if (Object.prototype.hasOwnProperty.call(source, key)) {
          target[key] = source[key];
        }
      }
    }
    return target;
  };
  return _extends.apply(this, arguments);
}
function _objectWithoutPropertiesLoose(source, excluded) {
  if (source == null)
    return {};
  var target = {};
  var sourceKeys = Object.keys(source);
  var key, i2;
  for (i2 = 0; i2 < sourceKeys.length; i2++) {
    key = sourceKeys[i2];
    if (excluded.indexOf(key) >= 0)
      continue;
    target[key] = source[key];
  }
  return target;
}
var props = ["bottom", "height", "left", "right", "top", "width"];
var rectChanged = function rectChanged2(a2, b2) {
  if (a2 === void 0) {
    a2 = {};
  }
  if (b2 === void 0) {
    b2 = {};
  }
  return props.some(function(prop) {
    return a2[prop] !== b2[prop];
  });
};
var observedNodes = /* @__PURE__ */ new Map();
var rafId;
var run = function run2() {
  var changedStates = [];
  observedNodes.forEach(function(state2, node) {
    var newRect = node.getBoundingClientRect();
    if (rectChanged(newRect, state2.rect)) {
      state2.rect = newRect;
      changedStates.push(state2);
    }
  });
  changedStates.forEach(function(state2) {
    state2.callbacks.forEach(function(cb2) {
      return cb2(state2.rect);
    });
  });
  rafId = window.requestAnimationFrame(run2);
};
function observeRect(node, cb2) {
  return {
    observe: function observe2() {
      var wasEmpty = observedNodes.size === 0;
      if (observedNodes.has(node)) {
        observedNodes.get(node).callbacks.push(cb2);
      } else {
        observedNodes.set(node, {
          rect: void 0,
          hasRectChanged: false,
          callbacks: [cb2]
        });
      }
      if (wasEmpty)
        run();
    },
    unobserve: function unobserve() {
      var state2 = observedNodes.get(node);
      if (state2) {
        var index2 = state2.callbacks.indexOf(cb2);
        if (index2 >= 0)
          state2.callbacks.splice(index2, 1);
        if (!state2.callbacks.length)
          observedNodes["delete"](node);
        if (!observedNodes.size)
          cancelAnimationFrame(rafId);
      }
    }
  };
}
var useIsomorphicLayoutEffect = typeof window !== "undefined" ? React__default.useLayoutEffect : React__default.useEffect;
function useRect(nodeRef, initialRect) {
  if (initialRect === void 0) {
    initialRect = {
      width: 0,
      height: 0
    };
  }
  var _React$useState = React__default.useState(nodeRef.current), element = _React$useState[0], setElement = _React$useState[1];
  var _React$useReducer = React__default.useReducer(rectReducer, initialRect), rect = _React$useReducer[0], dispatch3 = _React$useReducer[1];
  var initialRectSet = React__default.useRef(false);
  useIsomorphicLayoutEffect(function() {
    if (nodeRef.current !== element) {
      setElement(nodeRef.current);
    }
  });
  useIsomorphicLayoutEffect(function() {
    if (element && !initialRectSet.current) {
      initialRectSet.current = true;
      var _rect = element.getBoundingClientRect();
      dispatch3({
        rect: _rect
      });
    }
  }, [element]);
  React__default.useEffect(function() {
    if (!element) {
      return;
    }
    var observer = observeRect(element, function(rect2) {
      dispatch3({
        rect: rect2
      });
    });
    observer.observe();
    return function() {
      observer.unobserve();
    };
  }, [element]);
  return rect;
}
function rectReducer(state2, action) {
  var rect = action.rect;
  if (state2.height !== rect.height || state2.width !== rect.width) {
    return rect;
  }
  return state2;
}
var defaultEstimateSize = function defaultEstimateSize2() {
  return 50;
};
var defaultKeyExtractor = function defaultKeyExtractor2(index2) {
  return index2;
};
var defaultMeasureSize = function defaultMeasureSize2(el, horizontal) {
  var key = horizontal ? "offsetWidth" : "offsetHeight";
  return el[key];
};
var defaultRangeExtractor = function defaultRangeExtractor2(range) {
  var start = Math.max(range.start - range.overscan, 0);
  var end = Math.min(range.end + range.overscan, range.size - 1);
  var arr = [];
  for (var i2 = start; i2 <= end; i2++) {
    arr.push(i2);
  }
  return arr;
};
function useVirtual(_ref) {
  var _measurements;
  var _ref$size = _ref.size, size = _ref$size === void 0 ? 0 : _ref$size, _ref$estimateSize = _ref.estimateSize, estimateSize = _ref$estimateSize === void 0 ? defaultEstimateSize : _ref$estimateSize, _ref$overscan = _ref.overscan, overscan = _ref$overscan === void 0 ? 1 : _ref$overscan, _ref$paddingStart = _ref.paddingStart, paddingStart = _ref$paddingStart === void 0 ? 0 : _ref$paddingStart, _ref$paddingEnd = _ref.paddingEnd, paddingEnd = _ref$paddingEnd === void 0 ? 0 : _ref$paddingEnd, parentRef = _ref.parentRef, horizontal = _ref.horizontal, scrollToFn = _ref.scrollToFn, useObserver = _ref.useObserver, initialRect = _ref.initialRect, onScrollElement = _ref.onScrollElement, scrollOffsetFn = _ref.scrollOffsetFn, _ref$keyExtractor = _ref.keyExtractor, keyExtractor = _ref$keyExtractor === void 0 ? defaultKeyExtractor : _ref$keyExtractor, _ref$measureSize = _ref.measureSize, measureSize = _ref$measureSize === void 0 ? defaultMeasureSize : _ref$measureSize, _ref$rangeExtractor = _ref.rangeExtractor, rangeExtractor = _ref$rangeExtractor === void 0 ? defaultRangeExtractor : _ref$rangeExtractor;
  var sizeKey = horizontal ? "width" : "height";
  var scrollKey = horizontal ? "scrollLeft" : "scrollTop";
  var latestRef = React__default.useRef({
    scrollOffset: 0,
    measurements: []
  });
  var _React$useState = React__default.useState(0), scrollOffset = _React$useState[0], setScrollOffset = _React$useState[1];
  latestRef.current.scrollOffset = scrollOffset;
  var useMeasureParent = useObserver || useRect;
  var _useMeasureParent = useMeasureParent(parentRef, initialRect), outerSize = _useMeasureParent[sizeKey];
  latestRef.current.outerSize = outerSize;
  var defaultScrollToFn = React__default.useCallback(function(offset2) {
    if (parentRef.current) {
      parentRef.current[scrollKey] = offset2;
    }
  }, [parentRef, scrollKey]);
  var resolvedScrollToFn = scrollToFn || defaultScrollToFn;
  scrollToFn = React__default.useCallback(function(offset2) {
    resolvedScrollToFn(offset2, defaultScrollToFn);
  }, [defaultScrollToFn, resolvedScrollToFn]);
  var _React$useState2 = React__default.useState({}), measuredCache = _React$useState2[0], setMeasuredCache = _React$useState2[1];
  var measure = React__default.useCallback(function() {
    return setMeasuredCache({});
  }, []);
  var pendingMeasuredCacheIndexesRef = React__default.useRef([]);
  var measurements = React__default.useMemo(function() {
    var min = pendingMeasuredCacheIndexesRef.current.length > 0 ? Math.min.apply(Math, pendingMeasuredCacheIndexesRef.current) : 0;
    pendingMeasuredCacheIndexesRef.current = [];
    var measurements2 = latestRef.current.measurements.slice(0, min);
    for (var i2 = min; i2 < size; i2++) {
      var key = keyExtractor(i2);
      var measuredSize = measuredCache[key];
      var _start = measurements2[i2 - 1] ? measurements2[i2 - 1].end : paddingStart;
      var _size = typeof measuredSize === "number" ? measuredSize : estimateSize(i2);
      var _end = _start + _size;
      measurements2[i2] = {
        index: i2,
        start: _start,
        size: _size,
        end: _end,
        key
      };
    }
    return measurements2;
  }, [estimateSize, measuredCache, paddingStart, size, keyExtractor]);
  var totalSize = (((_measurements = measurements[size - 1]) == null ? void 0 : _measurements.end) || paddingStart) + paddingEnd;
  latestRef.current.measurements = measurements;
  latestRef.current.totalSize = totalSize;
  var element = onScrollElement ? onScrollElement.current : parentRef.current;
  var scrollOffsetFnRef = React__default.useRef(scrollOffsetFn);
  scrollOffsetFnRef.current = scrollOffsetFn;
  useIsomorphicLayoutEffect(function() {
    if (!element) {
      setScrollOffset(0);
      return;
    }
    var onScroll = function onScroll2(event) {
      var offset2 = scrollOffsetFnRef.current ? scrollOffsetFnRef.current(event) : element[scrollKey];
      setScrollOffset(offset2);
    };
    onScroll();
    element.addEventListener("scroll", onScroll, {
      capture: false,
      passive: true
    });
    return function() {
      element.removeEventListener("scroll", onScroll);
    };
  }, [element, scrollKey]);
  var _calculateRange = calculateRange(latestRef.current), start = _calculateRange.start, end = _calculateRange.end;
  var indexes = React__default.useMemo(function() {
    return rangeExtractor({
      start,
      end,
      overscan,
      size: measurements.length
    });
  }, [start, end, overscan, measurements.length, rangeExtractor]);
  var measureSizeRef = React__default.useRef(measureSize);
  measureSizeRef.current = measureSize;
  var virtualItems = React__default.useMemo(function() {
    var virtualItems2 = [];
    var _loop = function _loop2(k3, len2) {
      var i2 = indexes[k3];
      var measurement = measurements[i2];
      var item = _extends(_extends({}, measurement), {}, {
        measureRef: function measureRef(el) {
          if (el) {
            var measuredSize = measureSizeRef.current(el, horizontal);
            if (measuredSize !== item.size) {
              var _scrollOffset = latestRef.current.scrollOffset;
              if (item.start < _scrollOffset) {
                defaultScrollToFn(_scrollOffset + (measuredSize - item.size));
              }
              pendingMeasuredCacheIndexesRef.current.push(i2);
              setMeasuredCache(function(old) {
                var _extends2;
                return _extends(_extends({}, old), {}, (_extends2 = {}, _extends2[item.key] = measuredSize, _extends2));
              });
            }
          }
        }
      });
      virtualItems2.push(item);
    };
    for (var k2 = 0, len = indexes.length; k2 < len; k2++) {
      _loop(k2);
    }
    return virtualItems2;
  }, [indexes, defaultScrollToFn, horizontal, measurements]);
  var mountedRef = React__default.useRef(false);
  useIsomorphicLayoutEffect(function() {
    if (mountedRef.current) {
      setMeasuredCache({});
    }
    mountedRef.current = true;
  }, [estimateSize]);
  var scrollToOffset = React__default.useCallback(function(toOffset, _temp) {
    var _ref2 = _temp === void 0 ? {} : _temp, _ref2$align = _ref2.align, align = _ref2$align === void 0 ? "start" : _ref2$align;
    var _latestRef$current = latestRef.current, scrollOffset2 = _latestRef$current.scrollOffset, outerSize2 = _latestRef$current.outerSize;
    if (align === "auto") {
      if (toOffset <= scrollOffset2) {
        align = "start";
      } else if (toOffset >= scrollOffset2 + outerSize2) {
        align = "end";
      } else {
        align = "start";
      }
    }
    if (align === "start") {
      scrollToFn(toOffset);
    } else if (align === "end") {
      scrollToFn(toOffset - outerSize2);
    } else if (align === "center") {
      scrollToFn(toOffset - outerSize2 / 2);
    }
  }, [scrollToFn]);
  var tryScrollToIndex = React__default.useCallback(function(index2, _temp2) {
    var _ref3 = _temp2 === void 0 ? {} : _temp2, _ref3$align = _ref3.align, align = _ref3$align === void 0 ? "auto" : _ref3$align, rest = _objectWithoutPropertiesLoose(_ref3, ["align"]);
    var _latestRef$current2 = latestRef.current, measurements2 = _latestRef$current2.measurements, scrollOffset2 = _latestRef$current2.scrollOffset, outerSize2 = _latestRef$current2.outerSize;
    var measurement = measurements2[Math.max(0, Math.min(index2, size - 1))];
    if (!measurement) {
      return;
    }
    if (align === "auto") {
      if (measurement.end >= scrollOffset2 + outerSize2) {
        align = "end";
      } else if (measurement.start <= scrollOffset2) {
        align = "start";
      } else {
        return;
      }
    }
    var toOffset = align === "center" ? measurement.start + measurement.size / 2 : align === "end" ? measurement.end : measurement.start;
    scrollToOffset(toOffset, _extends({
      align
    }, rest));
  }, [scrollToOffset, size]);
  var scrollToIndex = React__default.useCallback(function() {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    tryScrollToIndex.apply(void 0, args);
    requestAnimationFrame(function() {
      tryScrollToIndex.apply(void 0, args);
    });
  }, [tryScrollToIndex]);
  return {
    virtualItems,
    totalSize,
    scrollToOffset,
    scrollToIndex,
    measure
  };
}
var findNearestBinarySearch = function findNearestBinarySearch2(low, high, getCurrentValue, value) {
  while (low <= high) {
    var middle = (low + high) / 2 | 0;
    var currentValue = getCurrentValue(middle);
    if (currentValue < value) {
      low = middle + 1;
    } else if (currentValue > value) {
      high = middle - 1;
    } else {
      return middle;
    }
  }
  if (low > 0) {
    return low - 1;
  } else {
    return 0;
  }
};
function calculateRange(_ref4) {
  var measurements = _ref4.measurements, outerSize = _ref4.outerSize, scrollOffset = _ref4.scrollOffset;
  var size = measurements.length - 1;
  var getOffset = function getOffset2(index2) {
    return measurements[index2].start;
  };
  var start = findNearestBinarySearch(0, size, getOffset, scrollOffset);
  var end = start;
  while (end < size && measurements[end].end < scrollOffset + outerSize) {
    end++;
  }
  return {
    start,
    end
  };
}
function StickerList({
  category
}) {
  const activeTheme = useActiveTheme();
  const name = category.name;
  const iterable = category.list ? category.list : Array.from(Array(category.items).keys());
  const parentRef = useRef(null);
  const virtualizer = useVirtual({
    horizontal: true,
    size: iterable.length,
    parentRef,
    estimateSize: useCallback(() => 52, []),
    overscan: 5
  });
  useEffect(() => {
    virtualizer.scrollToIndex(0);
  }, [name]);
  return /* @__PURE__ */ jsx(Fragment, {
    children: /* @__PURE__ */ jsx("div", {
      ref: parentRef,
      className: "tiny-scrollbar overflow-x-auto overflow-y-hidden",
      style: {
        height: `52px`
      },
      children: /* @__PURE__ */ jsx("div", {
        className: "h-full relative mx-auto",
        style: {
          width: `${virtualizer.totalSize}px`
        },
        children: virtualizer.virtualItems.map((virtualColumn) => {
          const stickerName = `${iterable[virtualColumn.index]}`;
          return /* @__PURE__ */ jsx("div", {
            className: "absolute top-0 left-0 h-full",
            style: {
              width: `${virtualColumn.size}px`,
              transform: `translateX(${virtualColumn.start}px)`
            },
            children: /* @__PURE__ */ jsx(Button, {
              variant: "outline",
              radius: "rounded-xl",
              size: "md",
              equalWidth: true,
              onPress: async () => {
                await tools().shape.addSticker(category.name, stickerName);
                state().setDirty(true);
              },
              children: /* @__PURE__ */ jsx("img", {
                className: clsx("m-auto m-auto w-28 h-28", category.invertPreview && (activeTheme == null ? void 0 : activeTheme.isDark) && "invert"),
                src: stickerUrl(category, stickerName),
                alt: stickerName
              })
            })
          }, virtualColumn.index);
        })
      })
    })
  });
}
function StickerNav() {
  const categories = useStore$1((s2) => {
    var _a2, _b;
    return (_b = (_a2 = s2.config.tools) == null ? void 0 : _a2.stickers) == null ? void 0 : _b.items;
  }) || [];
  const [selectedCategory, setSelectedCategory] = useState(categories[0]);
  const categoryBtns = categories.map((category) => {
    const isSelected = selectedCategory === category;
    const msg = StickerCategoryMessages[category.name];
    return /* @__PURE__ */ jsx(Button, {
      size: "xs",
      color: isSelected ? "primary" : null,
      value: category,
      children: /* @__PURE__ */ jsx("span", {
        className: "capitalize",
        children: msg ? /* @__PURE__ */ jsx(FormattedMessage$1, __spreadValues({}, msg)) : category.name
      })
    }, category.name);
  });
  return /* @__PURE__ */ jsxs("div", {
    className: "h-92",
    children: [/* @__PURE__ */ jsx(ButtonGroup, {
      value: selectedCategory,
      onChange: (newCategory) => setSelectedCategory(newCategory),
      className: "mb-10 w-full justify-center",
      variant: "outline",
      radius: "rounded-full",
      children: categoryBtns
    }), selectedCategory && /* @__PURE__ */ jsx(StickerList, {
      category: selectedCategory
    })]
  });
}
function FrameNav() {
  const frames = useStore$1((s2) => {
    var _a2, _b;
    return (_b = (_a2 = s2.config.tools) == null ? void 0 : _a2.frame) == null ? void 0 : _b.items;
  }) || [];
  const activeFrame = useStore$1((s2) => s2.frame.active);
  useEffect(() => {
    if (state().frame.active) {
      state().frame.showOptionsPanel();
    }
  }, []);
  const frameItems = frames.map((frame2) => {
    const src = assetUrl(`images/frames/${frame2.name}/thumbnail.png`);
    const isActive = (activeFrame == null ? void 0 : activeFrame.name) === frame2.name;
    const activeClass = isActive ? "border-primary" : "";
    return /* @__PURE__ */ jsx(ScrollableViewItem, {
      children: /* @__PURE__ */ jsxs("button", {
        type: "button",
        className: `border-2 overflow-hidden relative rounded border cursor-pointer ${activeClass}`,
        onClick: () => {
          state().setDirty(true);
          if (isActive) {
            tools().frame.remove();
          } else {
            tools().frame.add(frame2.name);
          }
        },
        children: [isActive && /* @__PURE__ */ jsx(ActiveOverlay, {}), /* @__PURE__ */ jsx("img", {
          draggable: "false",
          className: "w-64 h-64",
          src,
          alt: frame2.name
        })]
      })
    }, frame2.name);
  });
  return /* @__PURE__ */ jsx(ScrollableView, {
    children: frameItems
  });
}
function ActiveOverlay() {
  return /* @__PURE__ */ jsx("span", {
    className: "bg-background/70 absolute inset-0 text-primary",
    children: /* @__PURE__ */ jsx(CancelIcon, {
      className: "svg-icon icon-md absolute inset-0 block m-auto"
    })
  });
}
function TextNav() {
  const fonts = useStore$1((s2) => {
    var _a2, _b;
    return (_b = (_a2 = s2.config.tools) == null ? void 0 : _a2.text) == null ? void 0 : _b.items;
  });
  useEffect(() => {
    if (fonts) {
      loadFonts(fonts);
    }
  }, [fonts]);
  useEffect(() => {
    if (!state().objects.active.isText) {
      tools().text.add();
      state().setDirty(true);
    }
  }, []);
  const fontButtons = (fonts || []).map((fontConfig) => {
    return /* @__PURE__ */ jsx(ScrollableViewItem, {
      children: /* @__PURE__ */ jsx(FontButton, {
        fontConfig
      })
    }, fontConfig.family);
  });
  return /* @__PURE__ */ jsx(ScrollableView, {
    className: "pt-6",
    children: fontButtons
  });
}
function FontButton({
  fontConfig
}) {
  var _a2;
  const selectedFont = useStore$1((s2) => s2.objects.active.editableProps.fontFamily);
  const className = clsx("block px-6 w-110 h-68 text-sm bg border rounded-2xl", {
    "border-primary": selectedFont === fontConfig.family,
    "text-primary": selectedFont === fontConfig.family
  });
  return /* @__PURE__ */ jsx("button", {
    type: "button",
    className,
    style: {
      fontFamily: fontConfig.family,
      fontWeight: ((_a2 = fontConfig.descriptors) == null ? void 0 : _a2.weight) || "normal"
    },
    onClick: async () => {
      state().setDirty(true);
      tools().objects.setValues({
        fontFamily: fontConfig.family
      });
    },
    children: fontConfig.family
  });
}
function DrawNav() {
  useEffect(() => {
    tools().draw.enable();
    return () => {
      tools().draw.disable();
    };
  }, []);
  return /* @__PURE__ */ jsxs(ScrollableView, {
    gap: "gap-16",
    className: "justify-center",
    children: [/* @__PURE__ */ jsx(ScrollableViewItem, {
      children: /* @__PURE__ */ jsx(ColorPickerButton, {
        size: "sm",
        label: /* @__PURE__ */ jsx(FormattedMessage$1, {
          id: "i/W1yW",
          defaultMessage: [{
            "type": 0,
            "value": "Brush Color"
          }]
        }),
        value: tools().draw.currentBrush.color,
        onChange: (newColor) => {
          tools().draw.setBrushColor(newColor);
        }
      })
    }), /* @__PURE__ */ jsx(ScrollableViewItem, {
      children: /* @__PURE__ */ jsx(TypeSelect, {})
    }), /* @__PURE__ */ jsx(ScrollableViewItem, {
      children: /* @__PURE__ */ jsx(SizeSelect, {})
    })]
  });
}
function SizeSelect() {
  const sizes = useStore$1((s2) => {
    var _a2, _b;
    return (_b = (_a2 = s2.config.tools) == null ? void 0 : _a2.draw) == null ? void 0 : _b.brushSizes;
  }) || [];
  const [selectedSize, setSelectedSize] = useState(tools().draw.currentBrush.width);
  const items = sizes.map((size) => {
    return {
      key: size,
      value: size
    };
  });
  return /* @__PURE__ */ jsx(Picker, {
    items,
    value: selectedSize,
    onChange: (newValue) => {
      setSelectedSize(newValue);
      tools().draw.setBrushSize(newValue);
    },
    size: "sm",
    label: "Brush Size",
    children: (item) => /* @__PURE__ */ jsx($89e587cd0f107a73$export$6d08773d2e66f8f2, {
      textValue: `${item.key}`,
      children: /* @__PURE__ */ jsxs("div", {
        className: "flex items-center",
        children: [/* @__PURE__ */ jsx("div", {
          className: "flex-shrink-0 mr-8 border-[3px] rounded-full",
          style: {
            width: `${item.key}px`,
            height: `${item.key}px`
          }
        }), item.key]
      })
    })
  });
}
function TypeSelect() {
  const types2 = useStore$1((s2) => {
    var _a2, _b;
    return (_b = (_a2 = s2.config.tools) == null ? void 0 : _a2.draw) == null ? void 0 : _b.brushTypes;
  }) || [];
  const activeTheme = useActiveTheme();
  const [selectedType, setSelectedType] = useState(tools().draw.currentBrush.type);
  return /* @__PURE__ */ jsx(Picker, {
    value: selectedType,
    onChange: (value) => {
      setSelectedType(value);
      tools().draw.setBrushType(value);
    },
    size: "sm",
    label: "Brush Type",
    children: types2.map((type) => /* @__PURE__ */ jsx($89e587cd0f107a73$export$6d08773d2e66f8f2, {
      textValue: type,
      children: /* @__PURE__ */ jsxs("div", {
        className: "flex items-center",
        children: [/* @__PURE__ */ jsx("img", {
          className: "flex-shrink-0 mr-8 w-24 h-24",
          src: getBrushPreview(type, activeTheme == null ? void 0 : activeTheme.isDark),
          alt: ""
        }), type]
      })
    }, type))
  });
}
function getBrushPreview(type, isDarkMode = false) {
  const name = type.replace("Brush", "").toLowerCase();
  const dir = isDarkMode ? "white" : "black";
  return assetUrl(`images/brushes/${dir}/${name}.png`);
}
function CornersNav() {
  const intl = useIntl();
  const radius = useStore$1((s2) => s2.corners.radius);
  useEffect(() => {
    state().setDirty(true);
    tools().corners.showPreview();
    return () => tools().corners.hidePreview();
  }, []);
  return /* @__PURE__ */ jsx("div", {
    className: "max-w-320 mx-auto",
    children: /* @__PURE__ */ jsx(Slider, {
      minValue: 1,
      maxValue: 300,
      label: intl.formatMessage({
        id: "nDRMt4",
        defaultMessage: [{
          "type": 0,
          "value": "Radius"
        }]
      }),
      getValueLabel: (value) => {
        return `${value}px`;
      },
      onChange: (val) => {
        tools().corners.updatePreview(val);
        state().corners.setRadius(val);
      },
      value: radius
    })
  });
}
const navbarAnimation = {
  initial: {
    y: "130%",
    opacity: 0
  },
  animate: {
    y: 0,
    opacity: 1
  },
  exit: {
    y: "130%",
    opacity: 0,
    left: "16px",
    position: "absolute",
    overflowY: "hidden"
  },
  transition: {
    type: "tween",
    duration: 0.15
  }
};
function ToolControls({
  activeTool
}) {
  const toolNav = getToolNav(activeTool);
  return /* @__PURE__ */ jsx(m$2.div, __spreadProps(__spreadValues({
    className: "relative h-full w-full text-sm bg select-none overflow-hidden"
  }, navbarAnimation), {
    children: toolNav
  }));
}
function getToolNav(activeTool) {
  switch (activeTool) {
    case ToolName.FILTER:
      return /* @__PURE__ */ jsx(FilterNav, {});
    case ToolName.RESIZE:
      return /* @__PURE__ */ jsx(ResizeNav, {});
    case ToolName.CROP:
      return /* @__PURE__ */ jsx(CropNav, {});
    case ToolName.DRAW:
      return /* @__PURE__ */ jsx(DrawNav, {});
    case ToolName.TEXT:
      return /* @__PURE__ */ jsx(TextNav, {});
    case ToolName.SHAPES:
      return /* @__PURE__ */ jsx(ShapeNav, {});
    case ToolName.STICKERS:
      return /* @__PURE__ */ jsx(StickerNav, {});
    case ToolName.FRAME:
      return /* @__PURE__ */ jsx(FrameNav, {});
    case ToolName.CORNERS:
      return /* @__PURE__ */ jsx(CornersNav, {});
    default:
      return null;
  }
}
function Navbar() {
  const activeTool = useStore$1((s2) => s2.activeTool);
  return /* @__PURE__ */ jsx("nav", {
    className: "z-navbar min-h-86 flex-shrink-0 px-16 relative overflow-hidden",
    children: /* @__PURE__ */ jsx(AnimatePresence, {
      initial: false,
      children: activeTool ? /* @__PURE__ */ jsx(ToolControls, {
        activeTool
      }, "tool-controls") : /* @__PURE__ */ jsx(NavItems, {}, "nav-items")
    })
  });
}
function NavItems() {
  const navItems = useStore$1((s2) => {
    var _a2, _b;
    return (_b = (_a2 = s2.config.ui) == null ? void 0 : _a2.nav) == null ? void 0 : _b.items;
  }) || [];
  return /* @__PURE__ */ jsx(m$2.div, __spreadProps(__spreadValues({
    className: "w-full h-full"
  }, navbarAnimation), {
    children: /* @__PURE__ */ jsx(ScrollableView, {
      children: navItems.map((item) => /* @__PURE__ */ jsx(ScrollableViewItem, {
        children: /* @__PURE__ */ jsx(ToolButton, {
          item
        })
      }, item.name))
    })
  }));
}
function ToolButton({
  item
}) {
  const clickHandler = () => {
    if (typeof item.action === "string") {
      setActiveTool(item.action);
    } else if (typeof item.action === "function") {
      item.action(state().editor);
    }
  };
  const msg = navItemMessages[item.name];
  return /* @__PURE__ */ jsxs(ButtonBase, {
    variant: "outline",
    color: "paper",
    className: "flex-col flex-shrink-0 w-68 h-68",
    radius: "rounded-2xl",
    onPress: clickHandler,
    children: [/* @__PURE__ */ jsx("div", {
      className: "mb-1",
      children: /* @__PURE__ */ jsx(MixedIcon, {
        className: "icon-md",
        icon: item.icon
      })
    }), /* @__PURE__ */ jsx("div", {
      className: "mt-6 text-xs capitalize",
      children: msg ? /* @__PURE__ */ jsx(FormattedMessage$1, __spreadValues({}, msg)) : item.name
    })]
  });
}
function HistoryPanel() {
  const items = useStore$1((s2) => s2.history.items);
  const pointer = useStore$1((s2) => s2.history.pointer);
  return /* @__PURE__ */ jsxs(m$2.div, __spreadProps(__spreadValues({}, PopoverAnimation), {
    className: `absolute bottom-20 right-20 w-224 max-w-[calc(100%-40px)] max-h-[calc(100%-40px)] ${popoverStyle}`,
    children: [/* @__PURE__ */ jsxs("div", {
      className: "p-8 mb-4 bg-alt dark:bg-paper font-medium text-sm border-b flex items-center",
      children: [/* @__PURE__ */ jsx(FormattedMessage$1, {
        id: "djJp6c",
        defaultMessage: [{
          "type": 0,
          "value": "History"
        }]
      }), /* @__PURE__ */ jsx(IconButton, {
        className: "ml-auto flex-shrink-0",
        onPress: () => {
          state().togglePanel("history", false);
        },
        children: /* @__PURE__ */ jsx(CloseIcon, {})
      })]
    }), /* @__PURE__ */ jsx("div", {
      className: "p-8",
      children: items.map((item) => {
        const isActive = item.id === items[pointer].id;
        const displayName = HISTORY_DISPLAY_NAMES[item.name];
        const startIcon = displayName.icon && React__default.createElement(displayName.icon, {
          className: "icon-sm"
        });
        return /* @__PURE__ */ jsx(Button, {
          onPress: () => {
            if (isActive)
              return;
            tools().history.load(item);
          },
          variant: "outline",
          color: isActive ? "primary" : null,
          size: "sm",
          className: clsx("w-full mb-8", isActive && "pointer-events-none"),
          justify: "justify-start",
          startIcon,
          children: /* @__PURE__ */ jsx(FormattedMessage$1, __spreadValues({}, displayName.name))
        }, item.id);
      })
    })]
  }));
}
function DialogBody({
  children,
  className
}) {
  return /* @__PURE__ */ jsx("div", {
    className,
    children
  });
}
function NewImageDialogTrigger() {
  const isOpen = useStore$1((s2) => s2.openPanels.newImage);
  return /* @__PURE__ */ jsx(DialogTrigger, {
    isOpen,
    disableInitialTransition: true,
    type: "modal",
    isDismissable: false,
    children: /* @__PURE__ */ jsx(NewImageDialog, {})
  });
}
function NewImageDialog() {
  const [activePanel, setActivePanel] = useState("default");
  return /* @__PURE__ */ jsxs(Dialog, {
    className: "p-20 text-center max-w-max",
    children: [/* @__PURE__ */ jsx(DialogHeader, {
      className: "pb-20",
      children: /* @__PURE__ */ jsx(FormattedMessage$1, {
        id: "xdfcf6",
        defaultMessage: [{
          "type": 0,
          "value": "Open a photo or design to get started"
        }]
      })
    }), /* @__PURE__ */ jsx(DialogBody, {
      children: activePanel === "default" ? /* @__PURE__ */ jsx(DefaultPanel, {
        setActivePanel
      }) : /* @__PURE__ */ jsx(NewCanvasPanel, {
        setActivePanel
      })
    })]
  });
}
function DefaultPanel({
  setActivePanel
}) {
  return /* @__PURE__ */ jsxs(Fragment, {
    children: [/* @__PURE__ */ jsx(Button, {
      className: "mr-20",
      size: "sm",
      variant: "raised",
      color: "primary",
      onPress: () => {
        tools().import.uploadAndReplaceMainImage();
      },
      children: /* @__PURE__ */ jsx(FormattedMessage$1, {
        id: "7M1lRT",
        defaultMessage: [{
          "type": 0,
          "value": "Open Photo"
        }]
      })
    }), /* @__PURE__ */ jsx(Button, {
      variant: "outline",
      size: "sm",
      color: "primary",
      onPress: () => {
        setActivePanel("newCanvas");
      },
      children: /* @__PURE__ */ jsx(FormattedMessage$1, {
        id: "CVm3PB",
        defaultMessage: [{
          "type": 0,
          "value": "Create New"
        }]
      })
    }), /* @__PURE__ */ jsx(SampleImagesPanel, {})]
  });
}
function SampleImagesPanel() {
  const sampleImages = useStore$1((s2) => {
    var _a2, _b;
    return (_b = (_a2 = s2.config.ui) == null ? void 0 : _a2.openImageDialog) == null ? void 0 : _b.sampleImages;
  });
  if (!(sampleImages == null ? void 0 : sampleImages.length))
    return null;
  return /* @__PURE__ */ jsxs(Fragment, {
    children: [/* @__PURE__ */ jsxs("div", {
      className: "relative py-20",
      children: [/* @__PURE__ */ jsx("hr", {
        className: "absolute h-1 border-none bg-divider w-full top inset-0 m-auto"
      }), /* @__PURE__ */ jsx("span", {
        className: "text-sm bg-paper px-6 relative",
        children: /* @__PURE__ */ jsx(FormattedMessage$1, {
          id: "LaQ6Iq",
          defaultMessage: [{
            "type": 0,
            "value": "or use sample"
          }]
        })
      })]
    }), /* @__PURE__ */ jsx("ul", {
      className: "flex items-center gap-16",
      children: sampleImages.map((img) => /* @__PURE__ */ jsx("li", {
        className: "shrink-0",
        children: /* @__PURE__ */ jsx("button", {
          type: "button",
          onClick: async () => {
            if (typeof img.action === "function") {
              img.action();
            } else if (img.url.endsWith(".json")) {
              await fetchStateJsonFromUrl(assetUrl(img.url));
              state().togglePanel("newImage", false);
            } else {
              await tools().import.openBackgroundImage(assetUrl(img.url));
              state().togglePanel("newImage", false);
            }
          },
          children: /* @__PURE__ */ jsx("img", {
            className: "w-80 h-80 rounded overflow-hidden transition-shadow hover:shadow-md",
            src: assetUrl(img.thumbnail),
            alt: ""
          })
        })
      }, img.url || img.thumbnail))
    })]
  });
}
function NewCanvasPanel({
  setActivePanel
}) {
  const [formVal, setFormVal] = useState({
    width: 800,
    height: 600,
    bgColor: "transparent"
  });
  return /* @__PURE__ */ jsxs("form", {
    onSubmit: (e2) => {
      e2.preventDefault();
      const {
        width,
        height,
        bgColor
      } = formVal;
      if (width && height) {
        state().setConfig({
          blankCanvasSize: {
            width,
            height
          }
        });
        tools().canvas.openNew(width, height, bgColor);
        state().togglePanel("newImage", false);
        tools().history.addInitial();
      }
    },
    children: [/* @__PURE__ */ jsx(NumberField, {
      label: /* @__PURE__ */ jsx(FormattedMessage$1, {
        id: "5IP7AP",
        defaultMessage: [{
          "type": 0,
          "value": "Width"
        }]
      }),
      value: formVal.width,
      minValue: 1,
      isRequired: true,
      className: "mb-16",
      onChange: (width) => {
        setFormVal(__spreadProps(__spreadValues({}, formVal), {
          width
        }));
      }
    }), /* @__PURE__ */ jsx(NumberField, {
      label: /* @__PURE__ */ jsx(FormattedMessage$1, {
        id: "teLZyZ",
        defaultMessage: [{
          "type": 0,
          "value": "Height"
        }]
      }),
      value: formVal.height,
      minValue: 1,
      isRequired: true,
      className: "mb-16",
      onChange: (height) => {
        setFormVal(__spreadProps(__spreadValues({}, formVal), {
          height
        }));
      }
    }), /* @__PURE__ */ jsx(ColorPickerButton, {
      onChange: (newColor) => {
        setFormVal(__spreadProps(__spreadValues({}, formVal), {
          bgColor: newColor
        }));
      },
      className: "mb-16",
      value: formVal.bgColor,
      label: /* @__PURE__ */ jsx(FormattedMessage$1, {
        id: "CMansq",
        defaultMessage: [{
          "type": 0,
          "value": "Background color"
        }]
      })
    }), /* @__PURE__ */ jsxs("div", {
      className: "text-right",
      children: [/* @__PURE__ */ jsx(Button, {
        size: "sm",
        variant: "text",
        className: "mr-10",
        onPress: () => {
          setActivePanel("default");
        },
        children: /* @__PURE__ */ jsx(FormattedMessage$1, {
          id: "47FYwb",
          defaultMessage: [{
            "type": 0,
            "value": "Cancel"
          }]
        })
      }), /* @__PURE__ */ jsx(Button, {
        size: "sm",
        type: "submit",
        variant: "raised",
        color: "primary",
        children: /* @__PURE__ */ jsx(FormattedMessage$1, {
          id: "VzzYJk",
          defaultMessage: [{
            "type": 0,
            "value": "Create"
          }]
        })
      })]
    })]
  });
}
const TextField = forwardRef((props2, ref) => {
  const style2 = inputFieldStyle(props2);
  const inputRef = useRef(null);
  const {
    labelProps,
    inputProps,
    descriptionProps,
    errorMessageProps
  } = $13fe50aacf882d03$export$712718f7aec83d5(props2, inputRef);
  const {
    label,
    startAdornment,
    endAdornment
  } = props2;
  return /* @__PURE__ */ jsxs("div", {
    className: style2.wrapper,
    ref,
    children: [label && /* @__PURE__ */ jsx("label", __spreadProps(__spreadValues({
      className: style2.label
    }, labelProps), {
      children: label
    })), /* @__PURE__ */ jsxs("div", {
      className: "relative",
      children: [/* @__PURE__ */ jsx(Adornment, {
        direction: "start",
        children: startAdornment
      }), /* @__PURE__ */ jsx("input", __spreadValues({
        className: style2.input
      }, inputProps)), /* @__PURE__ */ jsx(Adornment, {
        direction: "end",
        children: endAdornment
      })]
    })]
  });
});
function $parcel$export$1(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $7641130e45ddf243$exports = {};
$parcel$export$1($7641130e45ddf243$exports, "useRadioGroupState", () => $7641130e45ddf243$export$bca9d026f8e704eb);
let $7641130e45ddf243$var$instance = Math.round(Math.random() * 1e10);
let $7641130e45ddf243$var$i = 0;
function $7641130e45ddf243$export$bca9d026f8e704eb(props2) {
  let name = useMemo(() => props2.name || `radio-group-${$7641130e45ddf243$var$instance}-${++$7641130e45ddf243$var$i}`, [
    props2.name
  ]);
  let [selectedValue, setSelected] = $bfee1151ccb0650f$export$40bfa8c7b0832715(props2.value, props2.defaultValue, props2.onChange);
  let [lastFocusedValue, setLastFocusedValue] = useState(null);
  let setSelectedValue = (value) => {
    if (!props2.isReadOnly && !props2.isDisabled)
      setSelected(value);
  };
  return {
    name,
    selectedValue,
    setSelectedValue,
    lastFocusedValue,
    setLastFocusedValue,
    isDisabled: props2.isDisabled || false,
    isReadOnly: props2.isReadOnly || false
  };
}
function $parcel$export(e2, n2, v2, s2) {
  Object.defineProperty(e2, n2, { get: v2, set: s2, enumerable: true, configurable: true });
}
var $2cd2cc131ce1e951$exports = {};
$parcel$export($2cd2cc131ce1e951$exports, "useRadio", () => $2cd2cc131ce1e951$export$37b0961d2f4751e2);
const $a249568f27a21ba9$export$3b7b268d09480394 = /* @__PURE__ */ new WeakMap();
function $2cd2cc131ce1e951$export$37b0961d2f4751e2(props2, state2, ref) {
  let { value, children, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledby } = props2;
  const isDisabled = props2.isDisabled || state2.isDisabled;
  let hasChildren = children != null;
  let hasAriaLabel = ariaLabel != null || ariaLabelledby != null;
  if (!hasChildren && !hasAriaLabel)
    console.warn("If you do not provide children, you must specify an aria-label for accessibility");
  let checked = state2.selectedValue === value;
  let onChange = (e2) => {
    e2.stopPropagation();
    state2.setSelectedValue(value);
  };
  let { pressProps } = $f6c31cce2adf654f$export$45712eceda6fad21({
    isDisabled
  });
  let { focusableProps } = $391c6482f25a1991$export$4c014de7c8940b4c($3ef42575df84b30b$export$9d1611c77c2fe928(props2, {
    onFocus: () => state2.setLastFocusedValue(value)
  }), ref);
  let interactions = $3ef42575df84b30b$export$9d1611c77c2fe928(pressProps, focusableProps);
  let domProps = $65484d02dcb7eb3e$export$457c3d6518dd4c6f(props2, {
    labelable: true
  });
  let tabIndex = state2.lastFocusedValue === value || state2.lastFocusedValue == null ? 0 : -1;
  if (isDisabled)
    tabIndex = void 0;
  return {
    inputProps: $3ef42575df84b30b$export$9d1611c77c2fe928(domProps, __spreadProps(__spreadValues({}, interactions), {
      type: "radio",
      name: $a249568f27a21ba9$export$3b7b268d09480394.get(state2),
      tabIndex,
      disabled: isDisabled,
      checked,
      value,
      onChange
    }))
  };
}
var $b5bb90da5b40a472$exports = {};
$parcel$export($b5bb90da5b40a472$exports, "useRadioGroup", () => $b5bb90da5b40a472$export$62b9571f283ff5c2);
function $b5bb90da5b40a472$export$62b9571f283ff5c2(props2, state2) {
  let { name, validationState, isReadOnly, isRequired, isDisabled, orientation = "vertical" } = props2;
  let { direction } = $18f2051aff69b9bf$export$43bb16f9c6d9e3f7();
  let { labelProps, fieldProps } = $6f8f5e0de5a77844$export$8467354a121f1b9f(__spreadProps(__spreadValues({}, props2), {
    labelElementType: "span"
  }));
  let domProps = $65484d02dcb7eb3e$export$457c3d6518dd4c6f(props2, {
    labelable: true
  });
  let { focusWithinProps } = $9ab94262bd0047c7$export$420e68273165f4ec({
    onBlurWithin() {
      if (!state2.selectedValue)
        state2.setLastFocusedValue(null);
    }
  });
  let onKeyDown = (e2) => {
    let nextDir;
    switch (e2.key) {
      case "ArrowRight":
        if (direction === "rtl" && orientation !== "vertical")
          nextDir = "prev";
        else
          nextDir = "next";
        break;
      case "ArrowLeft":
        if (direction === "rtl" && orientation !== "vertical")
          nextDir = "next";
        else
          nextDir = "prev";
        break;
      case "ArrowDown":
        nextDir = "next";
        break;
      case "ArrowUp":
        nextDir = "prev";
        break;
      default:
        return;
    }
    e2.preventDefault();
    let walker = $14e5c84cbc2e6e2e$export$2d6ec8fc375ceafa(e2.currentTarget, {
      from: e2.target
    });
    let nextElem;
    if (nextDir === "next") {
      nextElem = walker.nextNode();
      if (!nextElem) {
        walker.currentNode = e2.currentTarget;
        nextElem = walker.firstChild();
      }
    } else {
      nextElem = walker.previousNode();
      if (!nextElem) {
        walker.currentNode = e2.currentTarget;
        nextElem = walker.lastChild();
      }
    }
    if (nextElem) {
      nextElem.focus();
      state2.setSelectedValue(nextElem.value);
    }
  };
  let groupName = $bdb11010cef70236$export$f680877a34711e37(name);
  $a249568f27a21ba9$export$3b7b268d09480394.set(state2, groupName);
  return {
    radioGroupProps: $3ef42575df84b30b$export$9d1611c77c2fe928(domProps, __spreadValues(__spreadValues({
      role: "radiogroup",
      onKeyDown,
      "aria-invalid": validationState === "invalid" || void 0,
      "aria-errormessage": props2["aria-errormessage"],
      "aria-readonly": isReadOnly || void 0,
      "aria-required": isRequired || void 0,
      "aria-disabled": isDisabled || void 0,
      "aria-orientation": orientation
    }, fieldProps), focusWithinProps)),
    labelProps
  };
}
const RadioContext = React__default.createContext(null);
function useRadioProvider() {
  return useContext(RadioContext);
}
const RadioGroup = forwardRef((props2, ref) => {
  const style2 = inputFieldStyle(props2);
  const {
    label,
    children,
    size,
    className,
    orientation = "horizontal"
  } = props2;
  const state2 = $7641130e45ddf243$export$bca9d026f8e704eb(props2);
  const {
    radioGroupProps,
    labelProps
  } = $b5bb90da5b40a472$export$62b9571f283ff5c2(props2, state2);
  return /* @__PURE__ */ jsxs("div", __spreadProps(__spreadValues({
    className: clsx("text-left", className)
  }, radioGroupProps), {
    ref,
    children: [label && /* @__PURE__ */ jsx("span", __spreadProps(__spreadValues({
      className: style2.label
    }, labelProps), {
      children: label
    })), /* @__PURE__ */ jsx("div", {
      className: clsx("flex", orientation === "vertical" ? "flex-col gap-10" : "flex-row gap-16"),
      children: /* @__PURE__ */ jsx(RadioContext.Provider, {
        value: {
          state: state2,
          size
        },
        children
      })
    })]
  }));
});
function Radio(props2) {
  const {
    isDisabled,
    children,
    autoFocus,
    value
  } = props2;
  const {
    hoverProps,
    isHovered
  } = $6179b936705e76d3$export$ae780daf29e6d456({
    isDisabled
  });
  const {
    isFocusVisible,
    focusProps
  } = $e63d024ca16f2165$export$4e328f61c538687f(props2);
  const inputRef = useRef(null);
  const radioGroupProps = useRadioProvider();
  const {
    state: state2,
    size
  } = radioGroupProps;
  const isSelected = state2.selectedValue === value;
  const {
    inputProps
  } = $2cd2cc131ce1e951$export$37b0961d2f4751e2(__spreadProps(__spreadValues(__spreadValues({}, props2), radioGroupProps), {
    isDisabled
  }), state2, inputRef);
  return /* @__PURE__ */ jsxs("label", __spreadProps(__spreadValues({
    className: clsx("inline-flex gap-8 cursor-pointer select-none items-center whitespace-nowrap align-middle", isDisabled && "text-disabled pointer-events-none")
  }, hoverProps), {
    children: [/* @__PURE__ */ jsx($5c3e21d68f1c4674$export$439d29a4e110a164, {
      children: /* @__PURE__ */ jsx("input", __spreadProps(__spreadValues({}, $3ef42575df84b30b$export$9d1611c77c2fe928(inputProps, focusProps)), {
        ref: inputRef
      }))
    }), /* @__PURE__ */ jsxs("span", {
      className: clsx("block relative shrink-0", circleSize(size), isFocusVisible && "outline outline-offset-2 rounded-full"),
      children: [/* @__PURE__ */ jsx("span", {
        className: clsx("absolute left-0 top-o w-full h-full block transition-colors duration-200 border-2 rounded-full", circleColor(isSelected, isHovered, isDisabled))
      }), /* @__PURE__ */ jsx(AnimatePresence, {
        children: isSelected && /* @__PURE__ */ jsx(m$2.span, {
          className: clsx("rounded-full w-full h-full block left-0 top-o absolute", isHovered ? "bg-primary-dark" : "bg-primary"),
          initial: {
            scale: 0.01
          },
          animate: {
            scale: 0.5
          },
          exit: {
            scale: 0.01
          },
          transition: {
            type: "tween",
            duration: 0.2
          }
        }, "radio-inner")
      })]
    }), children && /* @__PURE__ */ jsx("span", {
      children
    })]
  }));
}
function circleSize(size) {
  switch (size) {
    case "xs":
      return "h-12 w-12";
    case "sm":
      return "h-16 w-16";
    case "lg":
      return "h-24 w-24";
    case "xl":
      return "h-36 w-36";
    default:
      return "h-20 w-20";
  }
}
function circleColor(isSelected, isHovered, isDisabled) {
  if (isDisabled) {
    return "border-disabled-fg";
  }
  if (isSelected) {
    return isHovered ? "border-primary-dark" : "border-primary";
  }
  return isHovered ? "border-text-main" : "border-text-muted ";
}
function ExportDialogTrigger() {
  const isOpen = useStore$1((s2) => s2.openPanels.export);
  return /* @__PURE__ */ jsx(DialogTrigger, {
    isOpen,
    onClose: () => {
      state().togglePanel("export", false);
    },
    type: "modal",
    children: /* @__PURE__ */ jsx(ExportDialog, {})
  });
}
function ExportDialog() {
  const [formVal, setFormVal] = useState(() => {
    var _a2, _b, _c, _d, _e2, _f2;
    return {
      filename: ((_b = (_a2 = state().config.tools) == null ? void 0 : _a2.export) == null ? void 0 : _b.defaultName) || "image",
      format: ((_d = (_c = state().config.tools) == null ? void 0 : _c.export) == null ? void 0 : _d.defaultFormat) || "jpeg",
      quality: ((_f2 = (_e2 = state().config.tools) == null ? void 0 : _e2.export) == null ? void 0 : _f2.defaultQuality) || 0.8
    };
  });
  return /* @__PURE__ */ jsx(Dialog, {
    className: "p-20 text-center max-w-max",
    children: /* @__PURE__ */ jsx(DialogBody, {
      children: /* @__PURE__ */ jsxs("form", {
        onSubmit: (e2) => {
          e2.preventDefault();
          tools().export.save(formVal.filename, formVal.format, formVal.quality);
          state().togglePanel("export", false);
        },
        children: [/* @__PURE__ */ jsx(TextField, {
          isRequired: true,
          size: "sm",
          label: /* @__PURE__ */ jsx(FormattedMessage$1, {
            id: "/XPfp1",
            defaultMessage: [{
              "type": 0,
              "value": "Save As"
            }]
          }),
          value: formVal.filename,
          onChange: (filename) => {
            setFormVal(__spreadProps(__spreadValues({}, formVal), {
              filename
            }));
          }
        }), /* @__PURE__ */ jsxs(RadioGroup, {
          size: "sm",
          className: "my-20",
          "aria-label": "Image format",
          value: formVal.format,
          onChange: (format) => {
            setFormVal(__spreadProps(__spreadValues({}, formVal), {
              format
            }));
          },
          children: [/* @__PURE__ */ jsx(Radio, {
            value: "jpeg",
            children: "JPEG"
          }), /* @__PURE__ */ jsx(Radio, {
            value: "png",
            children: "PNG"
          }), /* @__PURE__ */ jsx(Radio, {
            value: "json",
            children: "JSON"
          })]
        }), /* @__PURE__ */ jsx(Slider, {
          size: "sm",
          minValue: 0.1,
          step: 0.1,
          maxValue: 1,
          value: formVal.quality,
          onChange: (quality) => {
            setFormVal(__spreadProps(__spreadValues({}, formVal), {
              quality
            }));
          },
          formatOptions: {
            style: "percent"
          },
          label: /* @__PURE__ */ jsx(FormattedMessage$1, {
            id: "y+7ihJ",
            defaultMessage: [{
              "type": 0,
              "value": "Quality"
            }]
          })
        }), /* @__PURE__ */ jsx(Button, {
          variant: "raised",
          color: "primary",
          type: "submit",
          className: "mt-20 w-full",
          size: "sm",
          children: /* @__PURE__ */ jsx(FormattedMessage$1, {
            id: "jvo0vs",
            defaultMessage: [{
              "type": 0,
              "value": "Save"
            }]
          })
        })]
      })
    })
  });
}
function ObjListPanel() {
  const objects = useStore$1((s2) => s2.objects.all);
  const activeId = useStore$1((s2) => s2.objects.active.id);
  return /* @__PURE__ */ jsxs(m$2.div, __spreadProps(__spreadValues({}, PopoverAnimation), {
    className: `absolute bottom-20 right-20 w-224 max-w-[calc(100%-40px)] max-h-[calc(100%-40px)] ${popoverStyle}`,
    children: [/* @__PURE__ */ jsxs("div", {
      className: "p-8 mb-4 bg-alt dark:bg-paper font-medium text-sm border-b flex items-center",
      children: [/* @__PURE__ */ jsx(FormattedMessage$1, {
        id: "sWVioT",
        defaultMessage: [{
          "type": 0,
          "value": "Objects"
        }]
      }), /* @__PURE__ */ jsx(IconButton, {
        className: "ml-auto flex-shrink-0",
        onPress: () => {
          state().togglePanel("objects", false);
        },
        children: /* @__PURE__ */ jsx(CloseIcon, {})
      })]
    }), /* @__PURE__ */ jsx("div", {
      className: "p-8",
      children: objects.map((obj) => {
        const isActive = obj.id === activeId;
        const objName = obj.name;
        const displayName = OBJ_DISPLAY_NAMES[objName];
        const startIcon = displayName.icon && React__default.createElement(displayName.icon, {
          className: "icon-sm"
        });
        return /* @__PURE__ */ jsx(Button, {
          onPress: () => {
            if (isActive || !obj.selectable)
              return;
            tools().objects.select(obj.id);
          },
          variant: "outline",
          color: isActive ? "primary" : null,
          size: "sm",
          className: clsx("w-full mb-8", (isActive || !obj.selectable) && "pointer-events-none"),
          justify: "justify-start",
          startIcon,
          children: /* @__PURE__ */ jsx(FormattedMessage$1, __spreadValues({}, displayName.name))
        }, obj.id);
      })
    })]
  }));
}
function OverlayPanelContainer() {
  const historyVisible = useStore$1((s2) => s2.openPanels.history);
  const objectsVisible = useStore$1((s2) => s2.openPanels.objects);
  return /* @__PURE__ */ jsxs("div", {
    className: "z-modal",
    children: [/* @__PURE__ */ jsxs(AnimatePresence, {
      children: [historyVisible && /* @__PURE__ */ jsx(HistoryPanel, {}, "historyPanel"), objectsVisible && /* @__PURE__ */ jsx(ObjListPanel, {}, "objListPanel")]
    }), /* @__PURE__ */ jsx(NewImageDialogTrigger, {}), /* @__PURE__ */ jsx(ExportDialogTrigger, {})]
  });
}
const ErrorOutlineIcon = createSvgIcon(/* @__PURE__ */ jsx("path", {
  d: "M11 15h2v2h-2v-2zm0-8h2v6h-2V7zm.99-5C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"
}), "ErrorOutlineOutlined");
function ToastContainer() {
  const {
    toasts,
    handlers: handlers2
  } = useToaster({
    position: "bottom-center"
  });
  const {
    startPause,
    endPause
  } = handlers2;
  return /* @__PURE__ */ jsx("div", {
    className: "absolute bottom-10 left-0 right-0 z-toast m-auto px-10",
    onMouseEnter: startPause,
    onMouseLeave: endPause,
    children: /* @__PURE__ */ jsx(AnimatePresence, {
      initial: false,
      children: toasts.filter((t2) => t2.visible).map((t2) => {
        return /* @__PURE__ */ jsxs(m$2.div, __spreadProps(__spreadValues({
          initial: {
            opacity: 0,
            y: 50,
            scale: 0.3
          },
          animate: {
            opacity: 1,
            y: 0,
            scale: 1
          },
          exit: {
            opacity: 0,
            scale: 0.5,
            transition: {
              duration: 0.2
            }
          },
          className: "relative my-8 mx-auto h-[46px] flex items-center shadow-lg text-base w-min whitespace-nowrap bg-error text-on-error rounded-lg p-10"
        }, t2.ariaProps), {
          children: [t2.type === "error" && /* @__PURE__ */ jsx(ErrorOutlineIcon, {
            className: "svg-icon mr-12 icon-md"
          }), typeof t2.message === "string" ? t2.message : /* @__PURE__ */ jsx(FormattedMessage$1, __spreadValues({}, t2.message)), /* @__PURE__ */ jsx(IconButton, {
            onPress: () => {
              toast.dismiss(t2.id);
            },
            size: "sm",
            className: "ml-12",
            children: /* @__PURE__ */ jsx(CloseIcon, {})
          })]
        }), t2.id);
      })
    })
  });
}
var Key = /* @__PURE__ */ ((Key2) => {
  Key2["ENTER"] = "Enter";
  Key2["SPACE"] = "Space";
  Key2["ESCAPE"] = "Escape";
  Key2["DELETE"] = "Delete";
  Key2["ARROW_UP"] = "ArrowUp";
  Key2["ARROW_RIGHT"] = "ArrowRight";
  Key2["ARROW_DOWN"] = "ArrowDown";
  Key2["ARROW_LEFT"] = "ArrowLeft";
  Key2["PAGE_UP"] = "PageUp";
  Key2["PAGE_DOWN"] = "PageDown";
  Key2["HOME"] = "Home";
  Key2["END"] = "End";
  Key2["BACKSPACE"] = "Backspace";
  Key2["TAB"] = "Tab";
  Key2["S"] = "s";
  Key2["N"] = "n";
  Key2["A"] = "a";
  Key2["T"] = "t";
  Key2["B"] = "b";
  Key2["C"] = "c";
  Key2["O"] = "o";
  Key2["P"] = "p";
  Key2["R"] = "r";
  Key2["F"] = "f";
  Key2["Y"] = "y";
  Key2["Z"] = "z";
  return Key2;
})(Key || {});
function isCtrlKeyPressed(e2) {
  if ($c87311424ea30a05$export$9ac100e40613ea10()) {
    return e2.metaKey;
  }
  return e2.ctrlKey;
}
function handleCanvasKeydown(e2) {
  switch (e2.key) {
    case Key.Z:
      if (isCtrlKeyPressed(e2)) {
        e2.preventDefault();
        e2.stopPropagation();
        if (e2.shiftKey) {
          tools().history.redo();
        } else {
          tools().history.undo();
        }
      }
      break;
    case Key.ARROW_UP:
      e2.preventDefault();
      e2.stopPropagation();
      tools().objects.move("up");
      break;
    case Key.ARROW_RIGHT:
      e2.preventDefault();
      e2.stopPropagation();
      tools().objects.move("right");
      break;
    case Key.ARROW_DOWN:
      e2.preventDefault();
      e2.stopPropagation();
      tools().objects.move("down");
      break;
    case Key.ARROW_LEFT:
      e2.preventDefault();
      e2.stopPropagation();
      tools().objects.move("left");
      break;
    case Key.DELETE:
      e2.preventDefault();
      e2.stopPropagation();
      tools().objects.delete();
      break;
  }
}
function ImageEditor() {
  var _a2, _b, _c, _d;
  const activeLang = useStore$1((s2) => s2.config.activeLanguage) || "en";
  const languages = useStore$1((s2) => s2.config.languages);
  const isVisible = (_a2 = useStore$1((s2) => {
    var _a3;
    return (_a3 = s2.config.ui) == null ? void 0 : _a3.visible;
  })) != null ? _a2 : true;
  const navPosition = (_b = useStore$1((s2) => {
    var _a3, _b2;
    return (_b2 = (_a3 = s2.config.ui) == null ? void 0 : _a3.nav) == null ? void 0 : _b2.position;
  })) != null ? _b : "bottom";
  const menuPosition = (_c = useStore$1((s2) => {
    var _a3, _b2;
    return (_b2 = (_a3 = s2.config.ui) == null ? void 0 : _a3.menubar) == null ? void 0 : _b2.position;
  })) != null ? _c : "top";
  const allowEditorClose = (_d = useStore$1((s2) => {
    var _a3;
    return (_a3 = s2.config.ui) == null ? void 0 : _a3.allowEditorClose;
  })) != null ? _d : true;
  const messages2 = (languages == null ? void 0 : languages[activeLang]) || {};
  const activeTheme = useActiveTheme();
  const rootEl = useRef(null);
  const canvasRef = useRef(null);
  const {
    isModal,
    isMobile
  } = useEditorMode();
  const onDrop = useCallback((files2) => {
    var _a3, _b2, _c2;
    if (state().activeTool || state().dirty || !files2.length)
      return;
    const uploadedFile = new UploadedFile(files2[0]);
    if ((_c2 = (_b2 = (_a3 = state().config.tools) == null ? void 0 : _a3.import) == null ? void 0 : _b2.openDroppedImageAsBackground) != null ? _c2 : false) {
      tools().import.openBackgroundImage(uploadedFile);
    } else {
      tools().import.openUploadedFile(uploadedFile);
    }
  }, []);
  const {
    getRootProps,
    getInputProps,
    rootRef: stageRef
  } = useDropzone({
    onDrop,
    accept: buildUploadInputAccept(__spreadValues(__spreadValues({}, imgContentTypes()), stateContentType))
  });
  useEffect(() => {
    var _a3, _b2;
    if (state().fabric)
      return;
    initTools(canvasRef.current);
    if ((_a3 = state().config.ui) == null ? void 0 : _a3.defaultTool) {
      state().setActiveTool((_b2 = state().config.ui) == null ? void 0 : _b2.defaultTool, null);
    }
    tools().canvas.loadInitialContent().then(() => {
      var _a4, _b3;
      (_b3 = (_a4 = state().config).onLoad) == null ? void 0 : _b3.call(_a4, state().editor);
    });
    const unobserveStage = observeSize(stageRef.current, () => {
      state().setStageSize(getBoundingClientRect(stageRef.current));
    });
    const unobserveCanvas = observeSize(canvasRef.current, () => {
      state().setCanvasSize(getBoundingClientRect(canvasRef.current));
    });
    return () => {
      unobserveStage();
      unobserveCanvas();
    };
  }, [stageRef]);
  $f0a04ccd8dbdd83b$export$e5c5a5f917a5871c(() => {
    initThemes(rootEl.current, activeTheme);
  }, [activeTheme]);
  const variants = {
    visible: {
      opacity: 1,
      scale: 1,
      display: "flex"
    },
    hidden: {
      opacity: 0,
      transitionEnd: {
        display: "none"
      }
    }
  };
  const rootClassName = clsx("pixie-root flex flex-col overflow-hidden bg-background text-main no-tap-highlight w-full h-full", {
    relative: !isModal,
    "fixed inset-0 w-full h-full z-20": isModal,
    "shadow-lg border rounded-md m-auto max-h-[calc(100vh-90px)] max-w-[calc(100vw-90px)]": isModal && !isMobile
  });
  const showCloseIcon = isModal && isVisible && !isMobile && allowEditorClose;
  const showUnderlay = isModal && isVisible;
  return /* @__PURE__ */ jsxs(LazyMotion, {
    features: domAnimation,
    strict: true,
    children: [showCloseIcon && /* @__PURE__ */ jsx(IconButton, {
      className: "z-20 fixed right-2 top-2 text-white",
      size: "lg",
      onPress: () => {
        state().editor.close();
      },
      children: /* @__PURE__ */ jsx(CloseIcon, {})
    }), showUnderlay && /* @__PURE__ */ jsx(Underlay, {
      position: "fixed",
      disableInitialTransition: true
    }), /* @__PURE__ */ jsx(m$2.div, {
      ref: rootEl,
      initial: false,
      variants,
      animate: isVisible ? "visible" : "hidden",
      className: rootClassName,
      children: /* @__PURE__ */ jsx(OverlayPositionContext.Provider, {
        value: {
          boundary: rootEl,
          portalContainer: rootEl,
          shouldFlip: false,
          placement: navPosition === "bottom" ? "top" : "bottom",
          maxHeight: "400px"
        },
        children: /* @__PURE__ */ jsxs(IntlProvider$1, {
          locale: activeLang,
          defaultLocale: "en",
          messages: messages2,
          children: [menuPosition === "top" && /* @__PURE__ */ jsx(ToolbarContainer, {}), navPosition === "top" && /* @__PURE__ */ jsx(Navbar, {}), /* @__PURE__ */ jsxs("main", __spreadProps(__spreadValues({
            className: "relative flex-auto my-20 overflow-hidden outline-none"
          }, getRootProps({
            onKeyDownCapture: handleCanvasKeydown
          })), {
            children: [/* @__PURE__ */ jsx($5c3e21d68f1c4674$export$439d29a4e110a164, {
              children: /* @__PURE__ */ jsx("input", __spreadValues({}, getInputProps))
            }), /* @__PURE__ */ jsx(LoadingIndicator, {}), /* @__PURE__ */ jsx(CanvasWrapper, {
              ref: canvasRef
            })]
          })), /* @__PURE__ */ jsx(ToolControlsOverlay, {}), navPosition === "bottom" && /* @__PURE__ */ jsx(Navbar, {}), menuPosition === "bottom" && /* @__PURE__ */ jsx(ToolbarContainer, {}), /* @__PURE__ */ jsx(OverlayPanelContainer, {}), /* @__PURE__ */ jsx(ToastContainer, {})]
        })
      })
    })]
  });
}
var css = '/*! tailwindcss v3.0.23 | MIT License | https://tailwindcss.com*/.pi *,.pi :after,.pi :before{border:0 solid rgb(var(--be-foreground-base)/var(--be-divider-opacity));box-sizing:border-box}.pi :after,.pi :before{--tw-content:""}.pi hr{border-top-width:1px;color:inherit;height:0}.pi abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}.pi h1,.pi h2,.pi h3,.pi h4,.pi h5,.pi h6{font-size:inherit;font-weight:inherit}.pi a{color:inherit;text-decoration:inherit}.pi b,.pi strong{font-weight:bolder}.pi code,.pi kbd,.pi pre,.pi samp{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-size:1em}.pi small{font-size:80%}.pi sub,.pi sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}.pi sub{bottom:-.25em}.pi sup{top:-.5em}.pi table{border-collapse:collapse;border-color:inherit;text-indent:0}.pi button,.pi input,.pi optgroup,.pi select,.pi textarea{color:inherit;font-family:inherit;font-size:100%;line-height:inherit;margin:0;padding:0}.pi button,.pi select{text-transform:none}.pi [type=button],.pi [type=reset],.pi [type=submit],.pi button{-webkit-appearance:button;background-color:transparent;background-image:none}.pi :-moz-focusring{outline:auto}.pi :-moz-ui-invalid{box-shadow:none}.pi progress{vertical-align:baseline}.pi ::-webkit-inner-spin-button,.pi ::-webkit-outer-spin-button{height:auto}.pi [type=search]{-webkit-appearance:textfield;outline-offset:-2px}.pi ::-webkit-search-decoration{-webkit-appearance:none}.pi ::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}.pi summary{display:list-item}.pi blockquote,.pi dd,.pi dl,.pi figure,.pi h1,.pi h2,.pi h3,.pi h4,.pi h5,.pi h6,.pi hr,.pi p,.pi pre{margin:0}.pi fieldset{margin:0;padding:0}.pi legend{padding:0}.pi menu,.pi ol,.pi ul{list-style:none;margin:0;padding:0}.pi textarea{resize:vertical}.pi input::-moz-placeholder,.pi textarea::-moz-placeholder{color:#9ca3af;opacity:1}.pi input:-ms-input-placeholder,.pi textarea:-ms-input-placeholder{color:#9ca3af;opacity:1}.pi input::placeholder,.pi textarea::placeholder{color:#9ca3af;opacity:1}.pi [role=button],.pi button{cursor:pointer}.pi :disabled{cursor:default}.pi audio,.pi canvas,.pi embed,.pi iframe,.pi img,.pi object,.pi svg,.pi video{display:block;vertical-align:middle}.pi img,.pi video{height:auto;max-width:100%}.pi [hidden]{display:none}.pi *,.pi :after,.pi :before{--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(147,197,253,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }.pi .container{width:100%}.pi .\\!container{width:100%!important}@media (min-width:640px){.pi .container{max-width:640px}.pi .\\!container{max-width:640px!important}}@media (min-width:768px){.pi .container{max-width:768px}.pi .\\!container{max-width:768px!important}}@media (min-width:1024px){.pi .container{max-width:1024px}.pi .\\!container{max-width:1024px!important}}@media (min-width:1280px){.pi .container{max-width:1280px}.pi .\\!container{max-width:1280px!important}}@media (min-width:1536px){.pi .container{max-width:1536px}.pi .\\!container{max-width:1536px!important}}.pi .pointer-events-none{pointer-events:none}.pi .visible{visibility:visible}.pi .static{position:static}.pi .fixed{position:fixed}.pi .absolute{position:absolute}.pi .relative{position:relative}.pi .inset-0{bottom:0;top:0}.pi .inset-0,.pi .inset-x-0{left:0;right:0}.pi .right-2{right:2px}.pi .top-2{top:2px}.pi .left-0{left:0}.pi .-left-5{left:-5px}.pi .top-0{top:0}.pi .-top-5{top:-5px}.pi .bottom-0{bottom:0}.pi .-bottom-5{bottom:-5px}.pi .right-0{right:0}.pi .-right-5{right:-5px}.pi .bottom-20{bottom:20px}.pi .right-20{right:20px}.pi .bottom-10{bottom:10px}.pi .-bottom-20{bottom:-20px}.pi .left-1\\/2{left:50%}.pi .-bottom-10{bottom:-10px}.pi .-left-8{left:-8px}.pi .top-1\\/2{top:50%}.pi .-left-80{left:-80px}.pi .left-12{left:12px}.pi .right-12{right:12px}.pi .isolate{isolation:isolate}.pi .z-20{z-index:20}.pi .z-modal{z-index:120}.pi .z-obj-box{z-index:20}.pi .z-navbar{z-index:40}.pi .z-tool-overlay{z-index:30}.pi .z-loading-indicator{z-index:50}.pi .z-10{z-index:10}.pi .z-popover{z-index:140}.pi .z-tray{z-index:130}.pi .z-toast{z-index:150}.pi .z-cropzone{z-index:10}.pi .m-auto{margin:auto}.pi .my-20{margin-bottom:20px;margin-top:20px}.pi .mx-auto{margin-left:auto;margin-right:auto}.pi .my-8{margin-bottom:8px;margin-top:8px}.pi .my-auto{margin-bottom:auto;margin-top:auto}.pi .mr-5{margin-right:5px}.pi .ml-auto{margin-left:auto}.pi .mr-20{margin-right:20px}.pi .mb-16{margin-bottom:16px}.pi .mr-10{margin-right:10px}.pi .mb-4{margin-bottom:4px}.pi .mb-8{margin-bottom:8px}.pi .mt-20{margin-top:20px}.pi .mb-1{margin-bottom:1px}.pi .mt-6{margin-top:6px}.pi .mr-auto{margin-right:auto}.pi .ml-10{margin-left:10px}.pi .-ml-1{margin-left:-1px}.pi .-ml-4{margin-left:-4px}.pi .mr-8{margin-right:8px}.pi .-mr-4{margin-right:-4px}.pi .ml-8{margin-left:8px}.pi .mt-26{margin-top:26px}.pi .mr-12{margin-right:12px}.pi .ml-12{margin-left:12px}.pi .mt-4{margin-top:4px}.pi .mt-24{margin-top:24px}.pi .ml-6{margin-left:6px}.pi .mr-16{margin-right:16px}.pi .mb-10{margin-bottom:10px}.pi .block{display:block}.pi .inline-block{display:inline-block}.pi .inline{display:inline}.pi .flex{display:flex}.pi .inline-flex{display:inline-flex}.pi .grid{display:grid}.pi .contents{display:contents}.pi .hidden{display:none}.pi .aspect-square{aspect-ratio:1/1}.pi .h-2\\/4{height:50%}.pi .h-full{height:100%}.pi .h-font{height:1em}.pi .h-1{height:1px}.pi .h-80{height:80px}.pi .h-24{height:24px}.pi .h-20{height:20px}.pi .h-30{height:30px}.pi .h-84{height:84px}.pi .h-68{height:68px}.pi .h-32{height:32px}.pi .h-\\[54px\\]{height:54px}.pi .h-36{height:36px}.pi .h-50{height:50px}.pi .h-60{height:60px}.pi .h-42{height:42px}.pi .h-26{height:26px}.pi .h-8{height:8px}.pi .h-48{height:48px}.pi .h-5{height:5px}.pi .h-3{height:3px}.pi .h-64{height:64px}.pi .h-2{height:2px}.pi .h-\\[46px\\]{height:46px}.pi .h-56{height:56px}.pi .h-18{height:18px}.pi .h-12{height:12px}.pi .h-16{height:16px}.pi .h-4{height:4px}.pi .h-px{height:1px}.pi .h-28{height:28px}.pi .h-92{height:92px}.pi .max-h-\\[calc\\(100vh-90px\\)\\]{max-height:calc(100vh - 90px)}.pi .max-h-\\[calc\\(100\\%-40px\\)\\]{max-height:calc(100% - 40px)}.pi .max-h-inherit{max-height:inherit}.pi .min-h-86{min-height:86px}.pi .w-full{width:100%}.pi .w-font{width:1em}.pi .w-80{width:80px}.pi .w-24{width:24px}.pi .w-20{width:20px}.pi .w-30{width:30px}.pi .w-224{width:224px}.pi .w-68{width:68px}.pi .w-96{width:96px}.pi .w-144{width:144px}.pi .w-36{width:36px}.pi .w-50{width:50px}.pi .w-60{width:60px}.pi .w-42{width:42px}.pi .\\!w-auto{width:auto!important}.pi .w-26{width:26px}.pi .w-8{width:8px}.pi .w-1\\/2{width:50%}.pi .w-64{width:64px}.pi .w-32{width:32px}.pi .w-min{width:-webkit-min-content;width:-moz-min-content;width:min-content}.pi .w-56{width:56px}.pi .w-2{width:2px}.pi .w-18{width:18px}.pi .w-110{width:110px}.pi .w-40{width:40px}.pi .w-\\[4ch\\]{width:4ch}.pi .w-12{width:12px}.pi .w-16{width:16px}.pi .w-auto{width:auto}.pi .w-px{width:1px}.pi .w-28{width:28px}.pi .max-w-\\[calc\\(100vw-90px\\)\\]{max-width:calc(100vw - 90px)}.pi .max-w-max{max-width:-webkit-max-content;max-width:-moz-max-content;max-width:max-content}.pi .max-w-\\[calc\\(100\\%-40px\\)\\]{max-width:calc(100% - 40px)}.pi .max-w-384{max-width:384px}.pi .max-w-375{max-width:375px}.pi .max-w-full{max-width:100%}.pi .max-w-240{max-width:240px}.pi .max-w-320{max-width:320px}.pi .max-w-288{max-width:288px}.pi .max-w-112{max-width:112px}.pi .flex-auto{flex:1 1 auto}.pi .flex-shrink-0,.pi .shrink-0{flex-shrink:0}.pi .origin-\\[100\\%\\]{transform-origin:100%}.pi .translate-y-1{--tw-translate-y:1px}.pi .-translate-x-1\\/2,.pi .translate-y-1{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.pi .-translate-x-1\\/2{--tw-translate-x:-50%}.pi .-translate-y-1\\/2{--tw-translate-y:-50%}.pi .-translate-y-1\\/2,.pi .rotate-180{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.pi .rotate-180{--tw-rotate:180deg}.pi .rotate-0{--tw-rotate:0deg}.pi .rotate-0,.pi .rotate-90{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.pi .rotate-90{--tw-rotate:90deg}.pi .-rotate-90{--tw-rotate:-90deg}.pi .-rotate-90,.pi .transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.pi .cursor-nwse-resize{cursor:nwse-resize}.pi .cursor-nesw-resize{cursor:nesw-resize}.pi .cursor-se-resize{cursor:se-resize}.pi .cursor-sw-resize{cursor:sw-resize}.pi .cursor-pointer{cursor:pointer}.pi .cursor-default{cursor:default}.pi .cursor-move{cursor:move}.pi .touch-none{touch-action:none}.pi .select-none{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.pi .resize{resize:both}.pi .appearance-none{-webkit-appearance:none;-moz-appearance:none;appearance:none}.pi .grid-cols-5-min-content{grid-template-columns:repeat(5,-webkit-min-content);grid-template-columns:repeat(5,min-content)}.pi .flex-row{flex-direction:row}.pi .flex-col{flex-direction:column}.pi .flex-nowrap{flex-wrap:nowrap}.pi .items-center{align-items:center}.pi .justify-start{justify-content:flex-start}.pi .justify-center{justify-content:center}.pi .justify-between{justify-content:space-between}.pi .gap-16{gap:16px}.pi .gap-10{gap:10px}.pi .gap-8{gap:8px}.pi .gap-32{gap:32px}.pi .gap-6{gap:6px}.pi .gap-20{gap:20px}.pi .gap-12{gap:12px}.pi .gap-18{gap:18px}.pi .overflow-auto{overflow:auto}.pi .overflow-hidden{overflow:hidden}.pi .overflow-x-auto{overflow-x:auto}.pi .overflow-y-auto{overflow-y:auto}.pi .overflow-y-hidden{overflow-y:hidden}.pi .truncate{overflow:hidden;text-overflow:ellipsis}.pi .truncate,.pi .whitespace-nowrap{white-space:nowrap}.pi .rounded{border-radius:4px}.pi .rounded-md{border-radius:6px}.pi .rounded-none{border-radius:0}.pi .rounded-2xl{border-radius:16px}.pi .rounded-full{border-radius:9999px}.pi .rounded-sm{border-radius:2px}.pi .rounded-lg{border-radius:8px}.pi .rounded-xl{border-radius:12px}.pi .rounded-\\[16px\\]{border-radius:16px}.pi .rounded-\\[64px\\]{border-radius:64px}.pi .rounded-\\[32px\\]{border-radius:32px}.pi .rounded-tr-none{border-top-right-radius:0}.pi .rounded-br-none{border-bottom-right-radius:0}.pi .rounded-tl-none{border-top-left-radius:0}.pi .rounded-bl-none{border-bottom-left-radius:0}.pi .border{border-width:1px}.pi .border-4{border-width:4px}.pi .border-2{border-width:2px}.pi .border-\\[3px\\]{border-width:3px}.pi .border-l-4{border-left-width:4px}.pi .border-t-4{border-top-width:4px}.pi .border-r-4{border-right-width:4px}.pi .border-b-4{border-bottom-width:4px}.pi .border-b{border-bottom-width:1px}.pi .border-t{border-top-width:1px}.pi .border-l{border-left-width:1px}.pi .border-dotted{border-style:dotted}.pi .border-none{border-style:none}.pi .border-divider{border-color:rgb(var(--be-foreground-base)/var(--be-divider-opacity))}.pi .border-white{--tw-border-opacity:1;border-color:rgb(255 255 255/var(--tw-border-opacity))}.pi .border-primary\\/50{border-color:rgb(var(--be-primary)/.5)}.pi .border-error\\/50{border-color:rgb(var(--be-error)/.5)}.pi .border-transparent{border-color:transparent}.pi .border-primary{--tw-border-opacity:1;border-color:rgb(var(--be-primary)/var(--tw-border-opacity))}.pi .border-error{--tw-border-opacity:1;border-color:rgb(var(--be-error)/var(--tw-border-opacity))}.pi .border-background{--tw-border-opacity:1;border-color:rgb(var(--be-background)/var(--tw-border-opacity))}.pi .border-disabled-fg{border-color:rgb(var(--be-foreground-base)/var(--be-disabled-fg-opacity))}.pi .border-primary-dark{--tw-border-opacity:1;border-color:rgb(var(--be-primary-dark)/var(--tw-border-opacity))}.pi .border-text-main{border-color:rgb(var(--be-foreground-base)/var(--be-text-main-opacity))}.pi .border-text-muted{border-color:rgb(var(--be-foreground-base)/var(--be-text-muted-opacity))}.pi .border-white\\/50{border-color:hsla(0,0%,100%,.5)}.pi .border-r-transparent{border-right-color:transparent}.pi .bg-background{--tw-bg-opacity:1;background-color:rgb(var(--be-background)/var(--tw-bg-opacity))}.pi .bg-divider{background-color:rgb(var(--be-foreground-base)/var(--be-divider-opacity))}.pi .bg-paper{--tw-bg-opacity:1;background-color:rgb(var(--be-paper)/var(--tw-bg-opacity))}.pi .bg-controls{--tw-bg-opacity:1;background-color:rgb(50 50 50/var(--tw-bg-opacity))}.pi .bg-alt{--tw-bg-opacity:1;background-color:rgb(var(--be-background-alt)/var(--tw-bg-opacity))}.pi .bg{--tw-bg-opacity:1;background-color:rgb(var(--be-background)/var(--tw-bg-opacity))}.pi .bg-hover{background-color:rgb(var(--be-foreground-base)/var(--be-hover-opacity))}.pi .bg-transparent{background-color:transparent}.pi .bg-primary{--tw-bg-opacity:1;background-color:rgb(var(--be-primary)/var(--tw-bg-opacity))}.pi .bg-error{--tw-bg-opacity:1;background-color:rgb(var(--be-error)/var(--tw-bg-opacity))}.pi .bg-white{--tw-bg-opacity:1;background-color:rgb(255 255 255/var(--tw-bg-opacity))}.pi .bg-primary-light{--tw-bg-opacity:1;background-color:rgb(var(--be-primary-light)/var(--tw-bg-opacity))}.pi .bg-background\\/70{background-color:rgb(var(--be-background)/.7)}.pi .bg-primary\\/focus{background-color:rgb(var(--be-primary)/var(--be-focus-opacity))}.pi .bg-primary\\/selected{background-color:rgb(var(--be-primary)/var(--be-selected-opacity))}.pi .bg-focus{background-color:rgb(var(--be-foreground-base)/var(--be-focus-opacity))}.pi .bg-primary-dark{--tw-bg-opacity:1;background-color:rgb(var(--be-primary-dark)/var(--tw-bg-opacity))}.pi .bg-disabled{background-color:rgb(var(--be-foreground-base)/var(--be-disabled-bg-opacity))}.pi .bg-disabled-fg{background-color:rgb(var(--be-foreground-base)/var(--be-disabled-fg-opacity))}.pi .bg-slider-disabled{--tw-bg-opacity:1;background-color:rgb(189 189 189/var(--tw-bg-opacity))}.pi .bg-black\\/30{background-color:rgba(0,0,0,.3)}.pi .bg-white\\/50{background-color:hsla(0,0%,100%,.5)}.pi .bg-black\\/50{background-color:rgba(0,0,0,.5)}.pi .bg-opacity-95{--tw-bg-opacity:0.95}.pi .fill-current{fill:currentColor}.pi .fill-transparent{fill:transparent}.pi .fill-background{fill:rgb(var(--be-background))}.pi .stroke-current{stroke:currentColor}.pi .object-cover{-o-object-fit:cover;object-fit:cover}.pi .p-20{padding:20px}.pi .p-8{padding:8px}.pi .p-6{padding:6px}.pi .p-44{padding:44px}.pi .p-12{padding:12px}.pi .p-10{padding:10px}.pi .p-4{padding:4px}.pi .py-20{padding-bottom:20px;padding-top:20px}.pi .px-6{padding-left:6px;padding-right:6px}.pi .px-16{padding-left:16px;padding-right:16px}.pi .px-5vw{padding-left:5vw;padding-right:5vw}.pi .px-12{padding-left:12px;padding-right:12px}.pi .py-\\[9px\\]{padding-bottom:9px;padding-top:9px}.pi .px-8{padding-left:8px;padding-right:8px}.pi .py-4{padding-bottom:4px;padding-top:4px}.pi .px-14{padding-left:14px;padding-right:14px}.pi .px-18{padding-left:18px;padding-right:18px}.pi .px-26{padding-left:26px;padding-right:26px}.pi .px-32{padding-left:32px;padding-right:32px}.pi .px-22{padding-left:22px;padding-right:22px}.pi .py-28{padding-bottom:28px;padding-top:28px}.pi .px-24{padding-left:24px;padding-right:24px}.pi .px-10{padding-left:10px;padding-right:10px}.pi .px-2{padding-left:2px;padding-right:2px}.pi .py-8{padding-bottom:8px;padding-top:8px}.pi .px-20{padding-left:20px;padding-right:20px}.pi .py-14{padding-bottom:14px;padding-top:14px}.pi .pb-20{padding-bottom:20px}.pi .pb-4{padding-bottom:4px}.pi .pb-safe-area{padding-bottom:env(safe-area-inset-bottom)}.pi .pb-18{padding-bottom:18px}.pi .pt-6{padding-top:6px}.pi .pt-16{padding-top:16px}.pi .pb-10{padding-bottom:10px}.pi .pt-10{padding-top:10px}.pi .pl-12{padding-left:12px}.pi .pr-10{padding-right:10px}.pi .pl-10{padding-left:10px}.pi .pr-12{padding-right:12px}.pi .pl-36{padding-left:36px}.pi .pr-36{padding-right:36px}.pi .pb-16{padding-bottom:16px}.pi .text-left{text-align:left}.pi .text-center{text-align:center}.pi .text-right{text-align:right}.pi .align-middle{vertical-align:middle}.pi .text-sm{font-size:14px;line-height:20px}.pi .text-xs{font-size:12px;line-height:16px}.pi .text-base{font-size:16px;line-height:24px}.pi .text-lg{font-size:18px;line-height:28px}.pi .text-xl{font-size:20px;line-height:28px}.pi .font-medium{font-weight:500}.pi .font-semibold{font-weight:600}.pi .font-bold{font-weight:700}.pi .uppercase{text-transform:uppercase}.pi .capitalize{text-transform:capitalize}.pi .italic{font-style:italic}.pi .leading-none{line-height:1}.pi .tracking-wide{letter-spacing:.025em}.pi .text,.pi .text-main{color:rgb(var(--be-foreground-base)/var(--be-text-main-opacity))}.pi .text-white{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity))}.pi .\\!text{color:rgb(var(--be-foreground-base)/var(--be-text-main-opacity))!important}.pi .text-disabled{color:rgb(var(--be-foreground-base)/var(--be-disabled-fg-opacity))}.pi .text-muted{color:rgb(var(--be-foreground-base)/var(--be-text-muted-opacity))}.pi .text-primary{--tw-text-opacity:1;color:rgb(var(--be-primary)/var(--tw-text-opacity))}.pi .text-error{--tw-text-opacity:1;color:rgb(var(--be-error)/var(--tw-text-opacity))}.pi .text-current{color:currentColor}.pi .text-on-primary{--tw-text-opacity:1;color:rgb(var(--be-on-primary)/var(--tw-text-opacity))}.pi .text-on-error{--tw-text-opacity:1;color:rgb(var(--be-on-error)/var(--tw-text-opacity))}.pi .underline{-webkit-text-decoration-line:underline;text-decoration-line:underline}.pi .no-underline{-webkit-text-decoration-line:none;text-decoration-line:none}.pi .opacity-0{opacity:0}.pi .opacity-100{opacity:1}.pi .shadow{--tw-shadow:0 1px 3px 0 rgba(0,0,0,.1),0 1px 2px -1px rgba(0,0,0,.1);--tw-shadow-colored:0 1px 3px 0 var(--tw-shadow-color),0 1px 2px -1px var(--tw-shadow-color)}.pi .shadow,.pi .shadow-lg{box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.pi .shadow-lg{--tw-shadow:0 10px 15px -3px rgba(0,0,0,.1),0 4px 6px -4px rgba(0,0,0,.1);--tw-shadow-colored:0 10px 15px -3px var(--tw-shadow-color),0 4px 6px -4px var(--tw-shadow-color)}.pi .shadow-md{--tw-shadow:0 4px 6px -1px rgba(0,0,0,.1),0 2px 4px -2px rgba(0,0,0,.1);--tw-shadow-colored:0 4px 6px -1px var(--tw-shadow-color),0 2px 4px -2px var(--tw-shadow-color)}.pi .shadow-md,.pi .shadow-sm{box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.pi .shadow-sm{--tw-shadow:0 1px 2px 0 rgba(0,0,0,.05);--tw-shadow-colored:0 1px 2px 0 var(--tw-shadow-color)}.pi .outline-none{outline:2px solid transparent;outline-offset:2px}.pi .outline{outline-style:solid;outline-width:2px}.pi .outline-offset-2{outline-offset:2px}.pi .outline,.pi .outline-primary-light{outline-color:rgb(var(--be-primary-light))}.pi .ring-2{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color)}.pi .ring,.pi .ring-2{box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}.pi .ring{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color)}.pi .ring-1{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}.pi .ring-inset{--tw-ring-inset:inset}.pi .ring-primary-light{--tw-ring-opacity:1;--tw-ring-color:rgb(var(--be-primary-light)/var(--tw-ring-opacity))}.pi .ring-black{--tw-ring-opacity:1;--tw-ring-color:rgb(0 0 0/var(--tw-ring-opacity))}.pi .ring-opacity-5{--tw-ring-opacity:0.05}.pi .blur{--tw-blur:blur(8px)}.pi .blur,.pi .grayscale{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.pi .grayscale{--tw-grayscale:grayscale(100%)}.pi .invert{--tw-invert:invert(100%)}.pi .invert,.pi .sepia{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.pi .sepia{--tw-sepia:sepia(100%)}.pi .filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.pi .transition-transform{transition-duration:.15s;transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1)}.pi .transition-shadow{transition-duration:.15s;transition-property:box-shadow;transition-timing-function:cubic-bezier(.4,0,.2,1)}.pi .transition-opacity{transition-duration:.15s;transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1)}.pi .transition{transition-duration:.15s;transition-property:color,background-color,border-color,fill,stroke,opacity,box-shadow,transform,filter,-webkit-text-decoration-color,-webkit-backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter,-webkit-text-decoration-color,-webkit-backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1)}.pi .transition-button{transition-duration:.15s;transition-property:background-color,box-shadow,border-color,color;transition-timing-function:cubic-bezier(.4,0,.2,1)}.pi .transition-width{transition-duration:.15s;transition-property:width;transition-timing-function:cubic-bezier(.4,0,.2,1)}.pi .transition-all{transition-duration:.15s;transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1)}.pi .transition-colors{transition-duration:.15s;transition-property:color,background-color,border-color,fill,stroke,-webkit-text-decoration-color;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,-webkit-text-decoration-color;transition-timing-function:cubic-bezier(.4,0,.2,1)}.pi .duration-200{transition-duration:.2s}.pi .duration-300{transition-duration:.3s}.pi .icon-xs{font-size:1rem}.pi .icon-sm{font-size:1.25rem}.pi .icon-md{font-size:1.5rem}.pi .icon-lg{font-size:2.1875rem}.pi .icon-xl{font-size:2.6875rem}.pi .no-tap-highlight{-webkit-tap-highlight-color:transparent}@media only screen and (min-device-width:768px){.pi .tiny-scrollbar{scrollbar-color:rgba(0,0,0,.2) transparent;scrollbar-width:thin}.pi .tiny-scrollbar::-webkit-scrollbar{background-color:transparent;height:6px;width:6px}.pi .tiny-scrollbar::-webkit-scrollbar-thumb{background-color:rgb(var(--be-foreground-base)/.2);border-radius:10px}.pi .tiny-scrollbar::-webkit-scrollbar-track-piece:start{background:transparent}.pi .tiny-scrollbar::-webkit-scrollbar-track-piece:end{background:transparent}}.pi .hide-scrollbar{scrollbar-width:none}.pi .hide-scrollbar::-webkit-scrollbar{background:transparent;height:0;width:0}.pi .svg-icon{fill:currentColor;display:inline-block;flex-shrink:0;transition-duration:.15s;transition-property:transform,fill;transition-timing-function:cubic-bezier(.4,0,.2,1);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.pi .cropzone:not(.moving) .cropzone-transition{transition-duration:.15s;transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1)}.pi .hover\\:scale-110:hover{--tw-scale-x:1.1;--tw-scale-y:1.1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.pi .hover\\:border-primary:hover{--tw-border-opacity:1;border-color:rgb(var(--be-primary)/var(--tw-border-opacity))}.pi .hover\\:border-error:hover{--tw-border-opacity:1;border-color:rgb(var(--be-error)/var(--tw-border-opacity))}.pi .hover\\:border-primary-dark:hover{--tw-border-opacity:1;border-color:rgb(var(--be-primary-dark)/var(--tw-border-opacity))}.pi .hover\\:border-error\\/90:hover{border-color:rgb(var(--be-error)/.9)}.pi .hover\\:bg-white\\/hover:hover{background-color:rgb(255 255 255/var(--be-hover-opacity))}.pi .hover\\:bg-primary\\/hover:hover{background-color:rgb(var(--be-primary)/var(--be-hover-opacity))}.pi .hover\\:bg-error\\/4:hover{background-color:rgb(var(--be-error)/4%)}.pi .hover\\:bg-hover:hover{background-color:rgb(var(--be-foreground-base)/var(--be-hover-opacity))}.pi .hover\\:bg-primary\\/4:hover{background-color:rgb(var(--be-primary)/4%)}.pi .hover\\:bg-primary-dark:hover{--tw-bg-opacity:1;background-color:rgb(var(--be-primary-dark)/var(--tw-bg-opacity))}.pi .hover\\:bg-error\\/90:hover{background-color:rgb(var(--be-error)/.9)}.pi .hover\\:shadow-md:hover{--tw-shadow:0 4px 6px -1px rgba(0,0,0,.1),0 2px 4px -2px rgba(0,0,0,.1);--tw-shadow-colored:0 4px 6px -1px var(--tw-shadow-color),0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.pi .focus\\:border-primary\\/60:focus{border-color:rgb(var(--be-primary)/.6)}.pi .focus\\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.pi .focus\\:ring:focus{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}.pi .focus\\:ring-primary\\/focus:focus{--tw-ring-color:rgb(var(--be-primary)/var(--be-focus-opacity))}.pi .disabled\\:pointer-events-none:disabled{pointer-events:none}.pi .disabled\\:cursor-default:disabled{cursor:default}.pi .disabled\\:border-disabled-bg:disabled{border-color:rgb(var(--be-foreground-base)/var(--be-disabled-bg-opacity))}.pi .disabled\\:border-transparent:disabled{border-color:transparent}.pi .disabled\\:border-r-transparent:disabled{border-right-color:transparent}.pi .disabled\\:bg-transparent:disabled{background-color:transparent}.pi .disabled\\:bg-disabled:disabled{background-color:rgb(var(--be-foreground-base)/var(--be-disabled-bg-opacity))}.pi .disabled\\:text-disabled:disabled{color:rgb(var(--be-foreground-base)/var(--be-disabled-fg-opacity))}.pi .disabled\\:shadow-none:disabled{--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.pi .dark .dark\\:bg-paper{--tw-bg-opacity:1;background-color:rgb(var(--be-paper)/var(--tw-bg-opacity))}@media (min-width:640px){.pi .sm\\:text-sm{font-size:14px;line-height:20px}}';
index$1.enableBoundaryChecking(false);
class Pixie {
  constructor(config) {
    __publicField(this, "tools", {});
    __publicField(this, "fabric", null);
    if (config.sentryDsn) {
      init({
        dsn: config.sentryDsn,
        integrations: [new BrowserTracing()],
        tracesSampleRate: 1
      });
    }
    this.setConfig(config);
    {
      styleInject(css);
    }
    if (!config.selector) {
      throw new Error('Pixie required "selector" option.');
    }
    const container = document.querySelector(config.selector);
    if (!container) {
      return;
    }
    container.classList.add("pi");
    useStore$1.setState({
      editor: this
    });
    $icz4I$reactdom.render(/* @__PURE__ */ jsx(React__default.StrictMode, {
      children: /* @__PURE__ */ jsx(ImageEditor, {})
    }), container);
  }
  get state() {
    return state();
  }
  get version() {
    return PIXIE_VERSION;
  }
  get defaultConfig() {
    return DEFAULT_CONFIG;
  }
  open(config = {}) {
    var _a2;
    if ((_a2 = state().config.ui) == null ? void 0 : _a2.visible)
      return;
    this.setConfig(cjs(config, {
      ui: {
        visible: true
      }
    }));
    requestAnimationFrame(() => {
      var _a3, _b, _c, _d;
      tools().zoom.fitToScreen();
      tools().history.addInitial();
      if (canvasIsEmpty() && ((_b = (_a3 = state().config.ui) == null ? void 0 : _a3.openImageDialog) == null ? void 0 : _b.show)) {
        this.togglePanel("newImage", true);
      }
      (_d = (_c = state().config).onOpen) == null ? void 0 : _d.call(_c);
    });
  }
  close() {
    var _a2, _b, _c;
    if (!((_a2 = state().config.ui) == null ? void 0 : _a2.visible))
      return;
    this.setConfig({
      ui: {
        visible: false
      }
    });
    (_c = (_b = state().config).onClose) == null ? void 0 : _c.call(_b);
  }
  setConfig(config) {
    state().setConfig(config);
  }
  uploadAndAddImage() {
    return tools().import.uploadAndAddImage();
  }
  uploadAndReplaceMainImage() {
    return tools().import.uploadAndReplaceMainImage();
  }
  uploadAndOpenStateFile() {
    return tools().import.uploadAndOpenStateFile();
  }
  newCanvas(width, height, bgColor) {
    return tools().canvas.openNew(width, height, bgColor);
  }
  getState(customProps) {
    return JSON.stringify(getCurrentCanvasState(customProps));
  }
  setState(data) {
    return tools().import.loadState(data);
  }
  async setStateFromUrl(url) {
    const stateObj = await fetchStateJsonFromUrl(url);
    return tools().import.loadState(stateObj);
  }
  openTool(name) {
    setActiveTool(name);
  }
  applyChanges() {
    state().applyChanges();
  }
  cancelChanges() {
    state().cancelChanges();
  }
  async resetEditor(config) {
    await resetEditor(config);
    await tools().canvas.loadInitialContent();
  }
  togglePanel(name, isOpen) {
    state().togglePanel(name, isOpen);
  }
  on(event, handler) {
    var _a2;
    (_a2 = this.fabric) == null ? void 0 : _a2.on(event, handler);
  }
  isDirty() {
    return state().dirty;
  }
  get(name) {
    return this.tools[name];
  }
  notify(message) {
    return showToast(message);
  }
  static init(config) {
    return new Promise((resolve) => {
      const userOnLoad = config.onLoad;
      config.onLoad = (instance) => {
        userOnLoad == null ? void 0 : userOnLoad(instance);
        resolve(instance);
      };
      (() => new this(config))();
    });
  }
}
export { Pixie };
//# sourceMappingURL=pixie.es.js.map