UNPKG

reactdesk-core

Version:

A powerful React-based desktop environment library for creating Windows 11-like desktop interfaces with window management, taskbar, themes, and more

5,855 lines 216 kB
import require$$0, { jsx, jsxs } from "react/jsx-runtime";
import React__default, { memo, useCallback, useMemo, PureComponent, createElement, useRef, useEffect, useState, useLayoutEffect } from "react";
import { a6 as reactIsExports, a7 as getAugmentedNamespace, a8 as getDefaultExportFromCjs, $ as useContext, a9 as pxToNum, aa as viewWidth, ab as viewHeight, ac as WIN_TASKBAR_HEIGHT, ad as commonjsGlobal, ae as useContext$1, _ as useContext$2, af as useContext$3, ag as calcInitialPosition, ah as getElementSize, ai as DEFAULT_WINDOW_SIZE, a0 as useContext$4, aj as useContext$5, ak as TRANSITIONS_IN_MILLISECONDS, al as FOCUSABLE_ELEMENT, am as haltEvent, an as PREVENT_SCROLL, Y as m, X as defaultStyles, ao as Button, ap as useContext$6, aq as LONG_PRESS_DELAY_MS, a3 as Icon, a5 as label, Z as TRANSITIONS_IN_SECONDS, ar as DEFAULT_SCROLLBAR_WIDTH, as as Provider } from "./index-CGa3ZYCK.js";
import require$$2, { flushSync } from "react-dom";
import styled, { useTheme, keyframes, css } from "styled-components";
import { b as useWindowActions, a as useTitlebarContextMenu } from "./useTitlebarContextMenu-DjUJ9T4Z.js";
import { M as MinimizeIcon, a as MaximizedIcon, b as MaximizeIcon, C as CloseIcon } from "./WindowActionIcons-DaxmM-cO.js";
var cjs = { exports: {} };
var Draggable$2 = {};
var propTypes = { exports: {} };
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
var objectAssign;
var hasRequiredObjectAssign;
function requireObjectAssign() {
  if (hasRequiredObjectAssign) return objectAssign;
  hasRequiredObjectAssign = 1;
  var getOwnPropertySymbols = Object.getOwnPropertySymbols;
  var hasOwnProperty = 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 i = 0; i < 10; i++) {
        test2["_" + String.fromCharCode(i)] = i;
      }
      var order2 = Object.getOwnPropertyNames(test2).map(function(n) {
        return test2[n];
      });
      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;
    }
  }
  objectAssign = shouldUseNative() ? Object.assign : function(target, source) {
    var from;
    var to = toObject(target);
    var symbols;
    for (var s = 1; s < arguments.length; s++) {
      from = Object(arguments[s]);
      for (var key in from) {
        if (hasOwnProperty.call(from, key)) {
          to[key] = from[key];
        }
      }
      if (getOwnPropertySymbols) {
        symbols = getOwnPropertySymbols(from);
        for (var i = 0; i < symbols.length; i++) {
          if (propIsEnumerable.call(from, symbols[i])) {
            to[symbols[i]] = from[symbols[i]];
          }
        }
      }
    }
    return to;
  };
  return objectAssign;
}
var ReactPropTypesSecret_1;
var hasRequiredReactPropTypesSecret;
function requireReactPropTypesSecret() {
  if (hasRequiredReactPropTypesSecret) return ReactPropTypesSecret_1;
  hasRequiredReactPropTypesSecret = 1;
  var ReactPropTypesSecret = "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";
  ReactPropTypesSecret_1 = ReactPropTypesSecret;
  return ReactPropTypesSecret_1;
}
var has;
var hasRequiredHas;
function requireHas() {
  if (hasRequiredHas) return has;
  hasRequiredHas = 1;
  has = Function.call.bind(Object.prototype.hasOwnProperty);
  return has;
}
var checkPropTypes_1;
var hasRequiredCheckPropTypes;
function requireCheckPropTypes() {
  if (hasRequiredCheckPropTypes) return checkPropTypes_1;
  hasRequiredCheckPropTypes = 1;
  var printWarning = function() {
  };
  if (process.env.NODE_ENV !== "production") {
    var ReactPropTypesSecret = requireReactPropTypesSecret();
    var loggedTypeFailures = {};
    var has2 = requireHas();
    printWarning = function(text) {
      var message = "Warning: " + text;
      if (typeof console !== "undefined") {
        console.error(message);
      }
      try {
        throw new Error(message);
      } catch (x) {
      }
    };
  }
  function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
    if (process.env.NODE_ENV !== "production") {
      for (var typeSpecName in typeSpecs) {
        if (has2(typeSpecs, typeSpecName)) {
          var error;
          try {
            if (typeof typeSpecs[typeSpecName] !== "function") {
              var err = Error(
                (componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`."
              );
              err.name = "Invariant Violation";
              throw err;
            }
            error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
          } catch (ex) {
            error = ex;
          }
          if (error && !(error instanceof Error)) {
            printWarning(
              (componentName || "React class") + ": type specification of " + location + " `" + typeSpecName + "` is invalid; the type checker function must return `null` or an `Error` but returned a " + typeof error + ". You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument)."
            );
          }
          if (error instanceof Error && !(error.message in loggedTypeFailures)) {
            loggedTypeFailures[error.message] = true;
            var stack = getStack ? getStack() : "";
            printWarning(
              "Failed " + location + " type: " + error.message + (stack != null ? stack : "")
            );
          }
        }
      }
    }
  }
  checkPropTypes.resetWarningCache = function() {
    if (process.env.NODE_ENV !== "production") {
      loggedTypeFailures = {};
    }
  };
  checkPropTypes_1 = checkPropTypes;
  return checkPropTypes_1;
}
var factoryWithTypeCheckers;
var hasRequiredFactoryWithTypeCheckers;
function requireFactoryWithTypeCheckers() {
  if (hasRequiredFactoryWithTypeCheckers) return factoryWithTypeCheckers;
  hasRequiredFactoryWithTypeCheckers = 1;
  var ReactIs = reactIsExports;
  var assign = requireObjectAssign();
  var ReactPropTypesSecret = requireReactPropTypesSecret();
  var has2 = requireHas();
  var checkPropTypes = requireCheckPropTypes();
  var printWarning = function() {
  };
  if (process.env.NODE_ENV !== "production") {
    printWarning = function(text) {
      var message = "Warning: " + text;
      if (typeof console !== "undefined") {
        console.error(message);
      }
      try {
        throw new Error(message);
      } catch (x) {
      }
    };
  }
  function emptyFunctionThatReturnsNull() {
    return null;
  }
  factoryWithTypeCheckers = function(isValidElement, throwOnDirectAccess) {
    var ITERATOR_SYMBOL = typeof Symbol === "function" && Symbol.iterator;
    var FAUX_ITERATOR_SYMBOL = "@@iterator";
    function getIteratorFn(maybeIterable) {
      var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
      if (typeof iteratorFn === "function") {
        return iteratorFn;
      }
    }
    var ANONYMOUS = "<<anonymous>>";
    var ReactPropTypes = {
      array: createPrimitiveTypeChecker("array"),
      bigint: createPrimitiveTypeChecker("bigint"),
      bool: createPrimitiveTypeChecker("boolean"),
      func: createPrimitiveTypeChecker("function"),
      number: createPrimitiveTypeChecker("number"),
      object: createPrimitiveTypeChecker("object"),
      string: createPrimitiveTypeChecker("string"),
      symbol: createPrimitiveTypeChecker("symbol"),
      any: createAnyTypeChecker(),
      arrayOf: createArrayOfTypeChecker,
      element: createElementTypeChecker(),
      elementType: createElementTypeTypeChecker(),
      instanceOf: createInstanceTypeChecker,
      node: createNodeChecker(),
      objectOf: createObjectOfTypeChecker,
      oneOf: createEnumTypeChecker,
      oneOfType: createUnionTypeChecker,
      shape: createShapeTypeChecker,
      exact: createStrictShapeTypeChecker
    };
    function is(x, y) {
      if (x === y) {
        return x !== 0 || 1 / x === 1 / y;
      } else {
        return x !== x && y !== y;
      }
    }
    function PropTypeError(message, data) {
      this.message = message;
      this.data = data && typeof data === "object" ? data : {};
      this.stack = "";
    }
    PropTypeError.prototype = Error.prototype;
    function createChainableTypeChecker(validate) {
      if (process.env.NODE_ENV !== "production") {
        var manualPropTypeCallCache = {};
        var manualPropTypeWarningCount = 0;
      }
      function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
        componentName = componentName || ANONYMOUS;
        propFullName = propFullName || propName;
        if (secret !== ReactPropTypesSecret) {
          if (throwOnDirectAccess) {
            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;
          } else if (process.env.NODE_ENV !== "production" && typeof console !== "undefined") {
            var cacheKey = componentName + ":" + propName;
            if (!manualPropTypeCallCache[cacheKey] && // Avoid spamming the console because they are often not actionable except for lib authors
            manualPropTypeWarningCount < 3) {
              printWarning(
                "You are manually calling a React.PropTypes validation function for the `" + propFullName + "` prop on `" + componentName + "`. This is deprecated and will throw in the standalone `prop-types` package. You may be seeing this warning due to a third-party PropTypes library. See https://fb.me/react-warning-dont-call-proptypes for details."
              );
              manualPropTypeCallCache[cacheKey] = true;
              manualPropTypeWarningCount++;
            }
          }
        }
        if (props[propName] == null) {
          if (isRequired) {
            if (props[propName] === null) {
              return new PropTypeError("The " + location + " `" + propFullName + "` is marked as required " + ("in `" + componentName + "`, but its value is `null`."));
            }
            return new PropTypeError("The " + location + " `" + propFullName + "` is marked as required in " + ("`" + componentName + "`, but its value is `undefined`."));
          }
          return null;
        } else {
          return validate(props, propName, componentName, location, propFullName);
        }
      }
      var chainedCheckType = checkType.bind(null, false);
      chainedCheckType.isRequired = checkType.bind(null, true);
      return chainedCheckType;
    }
    function createPrimitiveTypeChecker(expectedType) {
      function validate(props, propName, componentName, location, propFullName, secret) {
        var propValue = props[propName];
        var propType = getPropType(propValue);
        if (propType !== expectedType) {
          var preciseType = getPreciseType(propValue);
          return new PropTypeError(
            "Invalid " + location + " `" + propFullName + "` of type " + ("`" + preciseType + "` supplied to `" + componentName + "`, expected ") + ("`" + expectedType + "`."),
            { expectedType }
          );
        }
        return null;
      }
      return createChainableTypeChecker(validate);
    }
    function createAnyTypeChecker() {
      return createChainableTypeChecker(emptyFunctionThatReturnsNull);
    }
    function createArrayOfTypeChecker(typeChecker) {
      function validate(props, propName, componentName, location, propFullName) {
        if (typeof typeChecker !== "function") {
          return new PropTypeError("Property `" + propFullName + "` of component `" + componentName + "` has invalid PropType notation inside arrayOf.");
        }
        var propValue = props[propName];
        if (!Array.isArray(propValue)) {
          var propType = getPropType(propValue);
          return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected an array."));
        }
        for (var i = 0; i < propValue.length; i++) {
          var error = typeChecker(propValue, i, componentName, location, propFullName + "[" + i + "]", ReactPropTypesSecret);
          if (error instanceof Error) {
            return error;
          }
        }
        return null;
      }
      return createChainableTypeChecker(validate);
    }
    function createElementTypeChecker() {
      function validate(props, propName, componentName, location, propFullName) {
        var propValue = props[propName];
        if (!isValidElement(propValue)) {
          var propType = getPropType(propValue);
          return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected a single ReactElement."));
        }
        return null;
      }
      return createChainableTypeChecker(validate);
    }
    function createElementTypeTypeChecker() {
      function validate(props, propName, componentName, location, propFullName) {
        var propValue = props[propName];
        if (!ReactIs.isValidElementType(propValue)) {
          var propType = getPropType(propValue);
          return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected a single ReactElement type."));
        }
        return null;
      }
      return createChainableTypeChecker(validate);
    }
    function createInstanceTypeChecker(expectedClass) {
      function validate(props, propName, componentName, location, propFullName) {
        if (!(props[propName] instanceof expectedClass)) {
          var expectedClassName = expectedClass.name || ANONYMOUS;
          var actualClassName = getClassName(props[propName]);
          return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + actualClassName + "` supplied to `" + componentName + "`, expected ") + ("instance of `" + expectedClassName + "`."));
        }
        return null;
      }
      return createChainableTypeChecker(validate);
    }
    function createEnumTypeChecker(expectedValues) {
      if (!Array.isArray(expectedValues)) {
        if (process.env.NODE_ENV !== "production") {
          if (arguments.length > 1) {
            printWarning(
              "Invalid arguments supplied to oneOf, expected an array, got " + arguments.length + " arguments. A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z])."
            );
          } else {
            printWarning("Invalid argument supplied to oneOf, expected an array.");
          }
        }
        return emptyFunctionThatReturnsNull;
      }
      function validate(props, propName, componentName, location, propFullName) {
        var propValue = props[propName];
        for (var i = 0; i < expectedValues.length; i++) {
          if (is(propValue, expectedValues[i])) {
            return null;
          }
        }
        var valuesString = JSON.stringify(expectedValues, function replacer(key, value) {
          var type = getPreciseType(value);
          if (type === "symbol") {
            return String(value);
          }
          return value;
        });
        return new PropTypeError("Invalid " + location + " `" + propFullName + "` of value `" + String(propValue) + "` " + ("supplied to `" + componentName + "`, expected one of " + valuesString + "."));
      }
      return createChainableTypeChecker(validate);
    }
    function createObjectOfTypeChecker(typeChecker) {
      function validate(props, propName, componentName, location, propFullName) {
        if (typeof typeChecker !== "function") {
          return new PropTypeError("Property `" + propFullName + "` of component `" + componentName + "` has invalid PropType notation inside objectOf.");
        }
        var propValue = props[propName];
        var propType = getPropType(propValue);
        if (propType !== "object") {
          return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected an object."));
        }
        for (var key in propValue) {
          if (has2(propValue, key)) {
            var error = typeChecker(propValue, key, componentName, location, propFullName + "." + key, ReactPropTypesSecret);
            if (error instanceof Error) {
              return error;
            }
          }
        }
        return null;
      }
      return createChainableTypeChecker(validate);
    }
    function createUnionTypeChecker(arrayOfTypeCheckers) {
      if (!Array.isArray(arrayOfTypeCheckers)) {
        process.env.NODE_ENV !== "production" ? printWarning("Invalid argument supplied to oneOfType, expected an instance of array.") : void 0;
        return emptyFunctionThatReturnsNull;
      }
      for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
        var checker = arrayOfTypeCheckers[i];
        if (typeof checker !== "function") {
          printWarning(
            "Invalid argument supplied to oneOfType. Expected an array of check functions, but received " + getPostfixForTypeWarning(checker) + " at index " + i + "."
          );
          return emptyFunctionThatReturnsNull;
        }
      }
      function validate(props, propName, componentName, location, propFullName) {
        var expectedTypes = [];
        for (var i2 = 0; i2 < arrayOfTypeCheckers.length; i2++) {
          var checker2 = arrayOfTypeCheckers[i2];
          var checkerResult = checker2(props, propName, componentName, location, propFullName, ReactPropTypesSecret);
          if (checkerResult == null) {
            return null;
          }
          if (checkerResult.data && has2(checkerResult.data, "expectedType")) {
            expectedTypes.push(checkerResult.data.expectedType);
          }
        }
        var expectedTypesMessage = expectedTypes.length > 0 ? ", expected one of type [" + expectedTypes.join(", ") + "]" : "";
        return new PropTypeError("Invalid " + location + " `" + propFullName + "` supplied to " + ("`" + componentName + "`" + expectedTypesMessage + "."));
      }
      return createChainableTypeChecker(validate);
    }
    function createNodeChecker() {
      function validate(props, propName, componentName, location, propFullName) {
        if (!isNode(props[propName])) {
          return new PropTypeError("Invalid " + location + " `" + propFullName + "` supplied to " + ("`" + componentName + "`, expected a ReactNode."));
        }
        return null;
      }
      return createChainableTypeChecker(validate);
    }
    function invalidValidatorError(componentName, location, propFullName, key, type) {
      return new PropTypeError(
        (componentName || "React class") + ": " + location + " type `" + propFullName + "." + key + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + type + "`."
      );
    }
    function createShapeTypeChecker(shapeTypes) {
      function validate(props, propName, componentName, location, propFullName) {
        var propValue = props[propName];
        var propType = getPropType(propValue);
        if (propType !== "object") {
          return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type `" + propType + "` " + ("supplied to `" + componentName + "`, expected `object`."));
        }
        for (var key in shapeTypes) {
          var checker = shapeTypes[key];
          if (typeof checker !== "function") {
            return invalidValidatorError(componentName, location, propFullName, key, getPreciseType(checker));
          }
          var error = checker(propValue, key, componentName, location, propFullName + "." + key, ReactPropTypesSecret);
          if (error) {
            return error;
          }
        }
        return null;
      }
      return createChainableTypeChecker(validate);
    }
    function createStrictShapeTypeChecker(shapeTypes) {
      function validate(props, propName, componentName, location, propFullName) {
        var propValue = props[propName];
        var propType = getPropType(propValue);
        if (propType !== "object") {
          return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type `" + propType + "` " + ("supplied to `" + componentName + "`, expected `object`."));
        }
        var allKeys = assign({}, props[propName], shapeTypes);
        for (var key in allKeys) {
          var checker = shapeTypes[key];
          if (has2(shapeTypes, key) && typeof checker !== "function") {
            return invalidValidatorError(componentName, location, propFullName, key, getPreciseType(checker));
          }
          if (!checker) {
            return new PropTypeError(
              "Invalid " + location + " `" + propFullName + "` key `" + key + "` supplied to `" + componentName + "`.\nBad object: " + JSON.stringify(props[propName], null, "  ") + "\nValid keys: " + JSON.stringify(Object.keys(shapeTypes), null, "  ")
            );
          }
          var error = checker(propValue, key, componentName, location, propFullName + "." + key, ReactPropTypesSecret);
          if (error) {
            return error;
          }
        }
        return null;
      }
      return createChainableTypeChecker(validate);
    }
    function isNode(propValue) {
      switch (typeof propValue) {
        case "number":
        case "string":
        case "undefined":
          return true;
        case "boolean":
          return !propValue;
        case "object":
          if (Array.isArray(propValue)) {
            return propValue.every(isNode);
          }
          if (propValue === null || isValidElement(propValue)) {
            return true;
          }
          var iteratorFn = getIteratorFn(propValue);
          if (iteratorFn) {
            var iterator = iteratorFn.call(propValue);
            var step;
            if (iteratorFn !== propValue.entries) {
              while (!(step = iterator.next()).done) {
                if (!isNode(step.value)) {
                  return false;
                }
              }
            } else {
              while (!(step = iterator.next()).done) {
                var entry = step.value;
                if (entry) {
                  if (!isNode(entry[1])) {
                    return false;
                  }
                }
              }
            }
          } else {
            return false;
          }
          return true;
        default:
          return false;
      }
    }
    function isSymbol2(propType, propValue) {
      if (propType === "symbol") {
        return true;
      }
      if (!propValue) {
        return false;
      }
      if (propValue["@@toStringTag"] === "Symbol") {
        return true;
      }
      if (typeof Symbol === "function" && propValue instanceof Symbol) {
        return true;
      }
      return false;
    }
    function getPropType(propValue) {
      var propType = typeof propValue;
      if (Array.isArray(propValue)) {
        return "array";
      }
      if (propValue instanceof RegExp) {
        return "object";
      }
      if (isSymbol2(propType, propValue)) {
        return "symbol";
      }
      return propType;
    }
    function getPreciseType(propValue) {
      if (typeof propValue === "undefined" || propValue === null) {
        return "" + propValue;
      }
      var propType = getPropType(propValue);
      if (propType === "object") {
        if (propValue instanceof Date) {
          return "date";
        } else if (propValue instanceof RegExp) {
          return "regexp";
        }
      }
      return propType;
    }
    function getPostfixForTypeWarning(value) {
      var type = getPreciseType(value);
      switch (type) {
        case "array":
        case "object":
          return "an " + type;
        case "boolean":
        case "date":
        case "regexp":
          return "a " + type;
        default:
          return type;
      }
    }
    function getClassName(propValue) {
      if (!propValue.constructor || !propValue.constructor.name) {
        return ANONYMOUS;
      }
      return propValue.constructor.name;
    }
    ReactPropTypes.checkPropTypes = checkPropTypes;
    ReactPropTypes.resetWarningCache = checkPropTypes.resetWarningCache;
    ReactPropTypes.PropTypes = ReactPropTypes;
    return ReactPropTypes;
  };
  return factoryWithTypeCheckers;
}
var factoryWithThrowingShims;
var hasRequiredFactoryWithThrowingShims;
function requireFactoryWithThrowingShims() {
  if (hasRequiredFactoryWithThrowingShims) return factoryWithThrowingShims;
  hasRequiredFactoryWithThrowingShims = 1;
  var ReactPropTypesSecret = requireReactPropTypesSecret();
  function emptyFunction() {
  }
  function emptyFunctionWithReset() {
  }
  emptyFunctionWithReset.resetWarningCache = emptyFunction;
  factoryWithThrowingShims = function() {
    function shim(props, propName, componentName, location, 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;
  };
  return factoryWithThrowingShims;
}
if (process.env.NODE_ENV !== "production") {
  var ReactIs = reactIsExports;
  var throwOnDirectAccess = true;
  propTypes.exports = requireFactoryWithTypeCheckers()(ReactIs.isElement, throwOnDirectAccess);
} else {
  propTypes.exports = requireFactoryWithThrowingShims()();
}
var propTypesExports = propTypes.exports;
function r(e) {
  var t, f, n = "";
  if ("string" == typeof e || "number" == typeof e) n += e;
  else if ("object" == typeof e) if (Array.isArray(e)) for (t = 0; t < e.length; t++) e[t] && (f = r(e[t])) && (n && (n += " "), n += f);
  else for (t in e) e[t] && (n && (n += " "), n += t);
  return n;
}
function clsx() {
  for (var e, t, f = 0, n = ""; f < arguments.length; ) (e = arguments[f++]) && (t = r(e)) && (n && (n += " "), n += t);
  return n;
}
const clsx_m = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  clsx,
  default: clsx
}, Symbol.toStringTag, { value: "Module" }));
const require$$3 = /* @__PURE__ */ getAugmentedNamespace(clsx_m);
var domFns = {};
var shims = {};
Object.defineProperty(shims, "__esModule", {
  value: true
});
shims.dontSetMe = dontSetMe;
shims.findInArray = findInArray;
shims.int = int;
shims.isFunction = isFunction;
shims.isNum = isNum;
function findInArray(array, callback) {
  for (let i = 0, length = array.length; i < length; i++) {
    if (callback.apply(callback, [array[i], i, array])) return array[i];
  }
}
function isFunction(func) {
  return typeof func === "function" || Object.prototype.toString.call(func) === "[object Function]";
}
function isNum(num) {
  return typeof num === "number" && !isNaN(num);
}
function int(a) {
  return parseInt(a, 10);
}
function dontSetMe(props, propName, componentName) {
  if (props[propName]) {
    return new Error("Invalid prop ".concat(propName, " passed to ").concat(componentName, " - do not set this, set it on the child."));
  }
}
var getPrefix$1 = {};
Object.defineProperty(getPrefix$1, "__esModule", {
  value: true
});
getPrefix$1.browserPrefixToKey = browserPrefixToKey;
getPrefix$1.browserPrefixToStyle = browserPrefixToStyle;
getPrefix$1.default = void 0;
getPrefix$1.getPrefix = getPrefix;
const prefixes = ["Moz", "Webkit", "O", "ms"];
function getPrefix() {
  var _window$document;
  let prop = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : "transform";
  if (typeof window === "undefined") return "";
  const style = (_window$document = window.document) === null || _window$document === void 0 || (_window$document = _window$document.documentElement) === null || _window$document === void 0 ? void 0 : _window$document.style;
  if (!style) return "";
  if (prop in style) return "";
  for (let i = 0; i < prefixes.length; i++) {
    if (browserPrefixToKey(prop, prefixes[i]) in style) return prefixes[i];
  }
  return "";
}
function browserPrefixToKey(prop, prefix) {
  return prefix ? "".concat(prefix).concat(kebabToTitleCase(prop)) : prop;
}
function browserPrefixToStyle(prop, prefix) {
  return prefix ? "-".concat(prefix.toLowerCase(), "-").concat(prop) : prop;
}
function kebabToTitleCase(str) {
  let out = "";
  let shouldCapitalize = true;
  for (let i = 0; i < str.length; i++) {
    if (shouldCapitalize) {
      out += str[i].toUpperCase();
      shouldCapitalize = false;
    } else if (str[i] === "-") {
      shouldCapitalize = true;
    } else {
      out += str[i];
    }
  }
  return out;
}
getPrefix$1.default = getPrefix();
Object.defineProperty(domFns, "__esModule", {
  value: true
});
domFns.addClassName = addClassName;
domFns.addEvent = addEvent;
domFns.addUserSelectStyles = addUserSelectStyles;
domFns.createCSSTransform = createCSSTransform;
domFns.createSVGTransform = createSVGTransform;
domFns.getTouch = getTouch;
domFns.getTouchIdentifier = getTouchIdentifier;
domFns.getTranslation = getTranslation;
domFns.innerHeight = innerHeight;
domFns.innerWidth = innerWidth;
domFns.matchesSelector = matchesSelector;
domFns.matchesSelectorAndParentsTo = matchesSelectorAndParentsTo;
domFns.offsetXYFromParent = offsetXYFromParent;
domFns.outerHeight = outerHeight;
domFns.outerWidth = outerWidth;
domFns.removeClassName = removeClassName;
domFns.removeEvent = removeEvent;
domFns.removeUserSelectStyles = removeUserSelectStyles;
var _shims$2 = shims;
var _getPrefix = _interopRequireWildcard$1(getPrefix$1);
function _getRequireWildcardCache$1(nodeInterop) {
  if (typeof WeakMap !== "function") return null;
  var cacheBabelInterop = /* @__PURE__ */ new WeakMap();
  var cacheNodeInterop = /* @__PURE__ */ new WeakMap();
  return (_getRequireWildcardCache$1 = function(nodeInterop2) {
    return nodeInterop2 ? cacheNodeInterop : cacheBabelInterop;
  })(nodeInterop);
}
function _interopRequireWildcard$1(obj, nodeInterop) {
  if (obj && obj.__esModule) {
    return obj;
  }
  if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
    return { default: obj };
  }
  var cache = _getRequireWildcardCache$1(nodeInterop);
  if (cache && cache.has(obj)) {
    return cache.get(obj);
  }
  var newObj = {};
  var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
  for (var key in obj) {
    if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
      var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
      if (desc && (desc.get || desc.set)) {
        Object.defineProperty(newObj, key, desc);
      } else {
        newObj[key] = obj[key];
      }
    }
  }
  newObj.default = obj;
  if (cache) {
    cache.set(obj, newObj);
  }
  return newObj;
}
let matchesSelectorFunc = "";
function matchesSelector(el, selector) {
  if (!matchesSelectorFunc) {
    matchesSelectorFunc = (0, _shims$2.findInArray)(["matches", "webkitMatchesSelector", "mozMatchesSelector", "msMatchesSelector", "oMatchesSelector"], function(method) {
      return (0, _shims$2.isFunction)(el[method]);
    });
  }
  if (!(0, _shims$2.isFunction)(el[matchesSelectorFunc])) return false;
  return el[matchesSelectorFunc](selector);
}
function matchesSelectorAndParentsTo(el, selector, baseNode) {
  let node = el;
  do {
    if (matchesSelector(node, selector)) return true;
    if (node === baseNode) return false;
    node = node.parentNode;
  } while (node);
  return false;
}
function addEvent(el, event, handler, inputOptions) {
  if (!el) return;
  const options = {
    capture: true,
    ...inputOptions
  };
  if (el.addEventListener) {
    el.addEventListener(event, handler, options);
  } else if (el.attachEvent) {
    el.attachEvent("on" + event, handler);
  } else {
    el["on" + event] = handler;
  }
}
function removeEvent(el, event, handler, inputOptions) {
  if (!el) return;
  const options = {
    capture: true,
    ...inputOptions
  };
  if (el.removeEventListener) {
    el.removeEventListener(event, handler, options);
  } else if (el.detachEvent) {
    el.detachEvent("on" + event, handler);
  } else {
    el["on" + event] = null;
  }
}
function outerHeight(node) {
  let height = node.clientHeight;
  const computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
  height += (0, _shims$2.int)(computedStyle.borderTopWidth);
  height += (0, _shims$2.int)(computedStyle.borderBottomWidth);
  return height;
}
function outerWidth(node) {
  let width = node.clientWidth;
  const computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
  width += (0, _shims$2.int)(computedStyle.borderLeftWidth);
  width += (0, _shims$2.int)(computedStyle.borderRightWidth);
  return width;
}
function innerHeight(node) {
  let height = node.clientHeight;
  const computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
  height -= (0, _shims$2.int)(computedStyle.paddingTop);
  height -= (0, _shims$2.int)(computedStyle.paddingBottom);
  return height;
}
function innerWidth(node) {
  let width = node.clientWidth;
  const computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
  width -= (0, _shims$2.int)(computedStyle.paddingLeft);
  width -= (0, _shims$2.int)(computedStyle.paddingRight);
  return width;
}
function offsetXYFromParent(evt, offsetParent, scale) {
  const isBody = offsetParent === offsetParent.ownerDocument.body;
  const offsetParentRect = isBody ? {
    left: 0,
    top: 0
  } : offsetParent.getBoundingClientRect();
  const x = (evt.clientX + offsetParent.scrollLeft - offsetParentRect.left) / scale;
  const y = (evt.clientY + offsetParent.scrollTop - offsetParentRect.top) / scale;
  return {
    x,
    y
  };
}
function createCSSTransform(controlPos, positionOffset) {
  const translation = getTranslation(controlPos, positionOffset, "px");
  return {
    [(0, _getPrefix.browserPrefixToKey)("transform", _getPrefix.default)]: translation
  };
}
function createSVGTransform(controlPos, positionOffset) {
  const translation = getTranslation(controlPos, positionOffset, "");
  return translation;
}
function getTranslation(_ref, positionOffset, unitSuffix) {
  let {
    x,
    y
  } = _ref;
  let translation = "translate(".concat(x).concat(unitSuffix, ",").concat(y).concat(unitSuffix, ")");
  if (positionOffset) {
    const defaultX = "".concat(typeof positionOffset.x === "string" ? positionOffset.x : positionOffset.x + unitSuffix);
    const defaultY = "".concat(typeof positionOffset.y === "string" ? positionOffset.y : positionOffset.y + unitSuffix);
    translation = "translate(".concat(defaultX, ", ").concat(defaultY, ")") + translation;
  }
  return translation;
}
function getTouch(e, identifier) {
  return e.targetTouches && (0, _shims$2.findInArray)(e.targetTouches, (t) => identifier === t.identifier) || e.changedTouches && (0, _shims$2.findInArray)(e.changedTouches, (t) => identifier === t.identifier);
}
function getTouchIdentifier(e) {
  if (e.targetTouches && e.targetTouches[0]) return e.targetTouches[0].identifier;
  if (e.changedTouches && e.changedTouches[0]) return e.changedTouches[0].identifier;
}
function addUserSelectStyles(doc) {
  if (!doc) return;
  let styleEl = doc.getElementById("react-draggable-style-el");
  if (!styleEl) {
    styleEl = doc.createElement("style");
    styleEl.type = "text/css";
    styleEl.id = "react-draggable-style-el";
    styleEl.innerHTML = ".react-draggable-transparent-selection *::-moz-selection {all: inherit;}\n";
    styleEl.innerHTML += ".react-draggable-transparent-selection *::selection {all: inherit;}\n";
    doc.getElementsByTagName("head")[0].appendChild(styleEl);
  }
  if (doc.body) addClassName(doc.body, "react-draggable-transparent-selection");
}
function removeUserSelectStyles(doc) {
  if (!doc) return;
  try {
    if (doc.body) removeClassName(doc.body, "react-draggable-transparent-selection");
    if (doc.selection) {
      doc.selection.empty();
    } else {
      const selection = (doc.defaultView || window).getSelection();
      if (selection && selection.type !== "Caret") {
        selection.removeAllRanges();
      }
    }
  } catch (e) {
  }
}
function addClassName(el, className) {
  if (el.classList) {
    el.classList.add(className);
  } else {
    if (!el.className.match(new RegExp("(?:^|\\s)".concat(className, "(?!\\S)")))) {
      el.className += " ".concat(className);
    }
  }
}
function removeClassName(el, className) {
  if (el.classList) {
    el.classList.remove(className);
  } else {
    el.className = el.className.replace(new RegExp("(?:^|\\s)".concat(className, "(?!\\S)"), "g"), "");
  }
}
var positionFns = {};
Object.defineProperty(positionFns, "__esModule", {
  value: true
});
positionFns.canDragX = canDragX;
positionFns.canDragY = canDragY;
positionFns.createCoreData = createCoreData;
positionFns.createDraggableData = createDraggableData;
positionFns.getBoundPosition = getBoundPosition;
positionFns.getControlPosition = getControlPosition;
positionFns.snapToGrid = snapToGrid;
var _shims$1 = shims;
var _domFns$1 = domFns;
function getBoundPosition(draggable, x, y) {
  if (!draggable.props.bounds) return [x, y];
  let {
    bounds
  } = draggable.props;
  bounds = typeof bounds === "string" ? bounds : cloneBounds(bounds);
  const node = findDOMNode(draggable);
  if (typeof bounds === "string") {
    const {
      ownerDocument
    } = node;
    const ownerWindow = ownerDocument.defaultView;
    let boundNode;
    if (bounds === "parent") {
      boundNode = node.parentNode;
    } else {
      boundNode = ownerDocument.querySelector(bounds);
    }
    if (!(boundNode instanceof ownerWindow.HTMLElement)) {
      throw new Error('Bounds selector "' + bounds + '" could not find an element.');
    }
    const boundNodeEl = boundNode;
    const nodeStyle = ownerWindow.getComputedStyle(node);
    const boundNodeStyle = ownerWindow.getComputedStyle(boundNodeEl);
    bounds = {
      left: -node.offsetLeft + (0, _shims$1.int)(boundNodeStyle.paddingLeft) + (0, _shims$1.int)(nodeStyle.marginLeft),
      top: -node.offsetTop + (0, _shims$1.int)(boundNodeStyle.paddingTop) + (0, _shims$1.int)(nodeStyle.marginTop),
      right: (0, _domFns$1.innerWidth)(boundNodeEl) - (0, _domFns$1.outerWidth)(node) - node.offsetLeft + (0, _shims$1.int)(boundNodeStyle.paddingRight) - (0, _shims$1.int)(nodeStyle.marginRight),
      bottom: (0, _domFns$1.innerHeight)(boundNodeEl) - (0, _domFns$1.outerHeight)(node) - node.offsetTop + (0, _shims$1.int)(boundNodeStyle.paddingBottom) - (0, _shims$1.int)(nodeStyle.marginBottom)
    };
  }
  if ((0, _shims$1.isNum)(bounds.right)) x = Math.min(x, bounds.right);
  if ((0, _shims$1.isNum)(bounds.bottom)) y = Math.min(y, bounds.bottom);
  if ((0, _shims$1.isNum)(bounds.left)) x = Math.max(x, bounds.left);
  if ((0, _shims$1.isNum)(bounds.top)) y = Math.max(y, bounds.top);
  return [x, y];
}
function snapToGrid(grid, pendingX, pendingY) {
  const x = Math.round(pendingX / grid[0]) * grid[0];
  const y = Math.round(pendingY / grid[1]) * grid[1];
  return [x, y];
}
function canDragX(draggable) {
  return draggable.props.axis === "both" || draggable.props.axis === "x";
}
function canDragY(draggable) {
  return draggable.props.axis === "both" || draggable.props.axis === "y";
}
function getControlPosition(e, touchIdentifier, draggableCore) {
  const touchObj = typeof touchIdentifier === "number" ? (0, _domFns$1.getTouch)(e, touchIdentifier) : null;
  if (typeof touchIdentifier === "number" && !touchObj) return null;
  const node = findDOMNode(draggableCore);
  const offsetParent = draggableCore.props.offsetParent || node.offsetParent || node.ownerDocument.body;
  return (0, _domFns$1.offsetXYFromParent)(touchObj || e, offsetParent, draggableCore.props.scale);
}
function createCoreData(draggable, x, y) {
  const isStart = !(0, _shims$1.isNum)(draggable.lastX);
  const node = findDOMNode(draggable);
  if (isStart) {
    return {
      node,
      deltaX: 0,
      deltaY: 0,
      lastX: x,
      lastY: y,
      x,
      y
    };
  } else {
    return {
      node,
      deltaX: x - draggable.lastX,
      deltaY: y - draggable.lastY,
      lastX: draggable.lastX,
      lastY: draggable.lastY,
      x,
      y
    };
  }
}
function createDraggableData(draggable, coreData) {
  const scale = draggable.props.scale;
  return {
    node: coreData.node,
    x: draggable.state.x + coreData.deltaX / scale,
    y: draggable.state.y + coreData.deltaY / scale,
    deltaX: coreData.deltaX / scale,
    deltaY: coreData.deltaY / scale,
    lastX: draggable.state.x,
    lastY: draggable.state.y
  };
}
function cloneBounds(bounds) {
  return {
    left: bounds.left,
    top: bounds.top,
    right: bounds.right,
    bottom: bounds.bottom
  };
}
function findDOMNode(draggable) {
  const node = draggable.findDOMNode();
  if (!node) {
    throw new Error("<DraggableCore>: Unmounted during event!");
  }
  return node;
}
var DraggableCore$2 = {};
var log$1 = {};
Object.defineProperty(log$1, "__esModule", {
  value: true
});
log$1.default = log;
function log() {
}
Object.defineProperty(DraggableCore$2, "__esModule", {
  value: true
});
DraggableCore$2.default = void 0;
var React = _interopRequireWildcard(React__default);
var _propTypes = _interopRequireDefault(propTypesExports);
var _reactDom = _interopRequireDefault(require$$2);
var _domFns = domFns;
var _positionFns = positionFns;
var _shims = shims;
var _log = _interopRequireDefault(log$1);
function _interopRequireDefault(obj) {
  return obj && obj.__esModule ? obj : { default: obj };
}
function _getRequireWildcardCache(nodeInterop) {
  if (typeof WeakMap !== "function") return null;
  var cacheBabelInterop = /* @__PURE__ */ new WeakMap();
  var cacheNodeInterop = /* @__PURE__ */ new WeakMap();
  return (_getRequireWildcardCache = function(nodeInterop2) {
    return nodeInterop2 ? cacheNodeInterop : cacheBabelInterop;
  })(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
  if (obj && obj.__esModule) {
    return obj;
  }
  if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
    return { default: obj };
  }
  var cache = _getRequireWildcardCache(nodeInterop);
  if (cache && cache.has(obj)) {
    return cache.get(obj);
  }
  var newObj = {};
  var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
  for (var key in obj) {
    if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
      var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
      if (desc && (desc.get || desc.set)) {
        Object.defineProperty(newObj, key, desc);
      } else {
        newObj[key] = obj[key];
      }
    }
  }
  newObj.default = obj;
  if (cache) {
    cache.set(obj, newObj);
  }
  return newObj;
}
function _defineProperty(obj, key, value) {
  key = _toPropertyKey(key);
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
function _toPropertyKey(arg) {
  var key = _toPrimitive(arg, "string");
  return typeof key === "symbol" ? key : String(key);
}
function _toPrimitive(input, hint) {
  if (typeof input !== "object" || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== void 0) {
    var res = prim.call(input, hint || "default");
    if (typeof res !== "object") return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
const eventsFor = {
  touch: {
    start: "touchstart",
    move: "touchmove",
    stop: "touchend"
  },
  mouse: {
    start: "mousedown",
    move: "mousemove",
    stop: "mouseup"
  }
};
let dragEventFor = eventsFor.mouse;
let DraggableCore$1 = class DraggableCore extends React.Component {
  constructor() {
    super(...arguments);
    _defineProperty(this, "dragging", false);
    _defineProperty(this, "lastX", NaN);
    _defineProperty(this, "lastY", NaN);
    _defineProperty(this, "touchIdentifier", null);
    _defineProperty(this, "mounted", false);
    _defineProperty(this, "handleDragStart", (e) => {
      this.props.onMouseDown(e);
      if (!this.props.allowAnyClick && typeof e.button === "number" && e.button !== 0) return false;
      const thisNode = this.findDOMNode();
      if (!thisNode || !thisNode.ownerDocument || !thisNode.ownerDocument.body) {
        throw new Error("<DraggableCore> not mounted on DragStart!");
      }
      const {
        ownerDocument
      } = thisNode;
      if (this.props.disabled || !(e.target instanceof ownerDocument.defaultView.Node) || this.props.handle && !(0, _domFns.matchesSelectorAndParentsTo)(e.target, this.props.handle, thisNode) || this.props.cancel && (0, _domFns.matchesSelectorAndParentsTo)(e.target, this.props.cancel, thisNode)) {
        return;
      }
      if (e.type === "touchstart") e.preventDefault();
      const touchIdentifier = (0, _domFns.getTouchIdentifier)(e);
      this.touchIdentifier = touchIdentifier;
      const position = (0, _positionFns.getControlPosition)(e, touchIdentifier, this);
      if (position == null) return;
      const {
        x,
        y
      } = position;
      const coreEvent = (0, _positionFns.createCoreData)(this, x, y);
      (0, _log.default)("DraggableCore: handleDragStart: %j", coreEvent);
      (0, _log.default)("calling", this.props.onStart);
      const shouldUpdate = this.props.onStart(e, coreEvent);
      if (shouldUpdate === false || this.mounted === false) return;
      if (this.props.enableUserSelectHack) (0, _domFns.addUserSelectStyles)(ownerDocument);
      this.dragging = true;
      this.lastX = x;
      this.lastY = y;
      (0, _domFns.addEvent)(ownerDocument, dragEventFor.move, this.handleDrag);
      (0, _domFns.addEvent)(ownerDocument, dragEventFor.stop, this.handleDragStop);
    });
    _defineProperty(this, "handleDrag", (e) => {
      const position = (0, _positionFns.getControlPosition)(e, this.touchIdentifier, this);
      if (position == null) return;
      let {
        x,
        y
      } = position;
      if (Array.isArray(this.props.grid)) {
        let deltaX = x - this.lastX, deltaY = y - this.lastY;
        [deltaX, deltaY] = (0, _positionFns.snapToGrid)(this.props.grid, deltaX, deltaY);
        if (!deltaX && !deltaY) return;
        x = this.lastX + deltaX, y = this.lastY + deltaY;
      }
      const coreEvent = (0, _positionFns.createCoreData)(this, x, y);
      (0, _log.default)("DraggableCore: handleDrag: %j", coreEvent);
      const shouldUpdate = this.props.onDrag(e, coreEvent);
      if (shouldUpdate === false || this.mounted === false) {
        try {
          this.handleDragStop(new MouseEvent("mouseup"));
        } catch (err) {
          const event = document.createEvent("MouseEvents");
          event.initMouseEvent("mouseup", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
          this.handleDragStop(event);
        }
        return;
      }
      this.lastX = x;
      this.lastY = y;
    });
    _defineProperty(this, "handleDragStop", (e) => {
      if (!this.dragging) return;
      const position = (0, _positionFns.getControlPosition)(e, this.touchIdentifier, this);
      if (position == null) return;
      let {
        x,
        y
      } = position;
      if (Array.isArray(this.props.grid)) {
        let deltaX = x - this.lastX || 0;
        let deltaY = y - this.lastY || 0;
        [deltaX, deltaY] = (0, _positionFns.snapToGrid)(this.props.grid, deltaX, deltaY);
        x = this.lastX + deltaX, y = this.lastY + deltaY;
      }
      const coreEvent = (0, _positionFns.createCoreData)(this, x, y);
      const shouldContinue = this.props.onStop(e, coreEvent);
      if (shouldContinue === false || this.mounted === false) return false;
      const thisNode = this.findDOMNode();
      if (thisNode) {
        if (this.props.enableUserSelectHack) (0, _domFns.removeUserSelectStyles)(thisNode.ownerDocument);
      }
      (0, _log.default)("DraggableCore: handleDragStop: %j", coreEvent);
      this.dragging = false;
      this.lastX = NaN;
      this.lastY = NaN;
      if (thisNode) {
        (0, _log.default)("DraggableCore: Removing handlers");
        (0, _domFns.removeEvent)(thisNode.ownerDocument, dragEventFor.move, this.handleDrag);
        (0, _domFns.removeEvent)(thisNode.ownerDocument, dragEventFor.stop, this.handleDragStop);
      }
    });
    _defineProperty(this, "onMouseDown", (e) => {
      dragEventFor = eventsFor.mouse;
      return this.handleDragStart(e);
    });
    _defineProperty(this, "onMouseUp", (e) => {
      dragEventFor = eventsFor.mouse;
      return this.handleDragStop(e);
    });
    _defineProperty(this, "onTouchStart", (e) => {
      dragEventFor = eventsFor.touch;
      return this.handleDragStart(e);
    });
    _defineProperty(this, "onTouchEnd", (e) => {
      dragEventFor = eventsFor.touch;
      return this.handleDragStop(e);
    });
  }
  componentDidMount() {
    this.mounted = true;
    const thisNode = this.findDOMNode();
    if (thisNode) {
      (0, _domFns.addEvent)(thisNode, eventsFor.touch.start, this.onTouchStart, {
        passive: false
      });
    }
  }
  componentWillUnmount() {
    this.mounted = false;
    const thisNode = this.findDOMNode();
    if (thisNode) {
      const {
        ownerDocument
      } = thisNode;
      (0, _domFns.removeEvent)(ownerDocument, eventsFor.mouse.move, this.handleDrag);
      (0, _domFns.removeEvent)(ownerDocument, eventsFor.touch.move, this.handleDrag);
      (0, _domFns.removeEvent)(ownerDocument, eventsFor.mouse.stop, this.handleDragStop);
      (0, _domFns.removeEvent)(ownerDocument, eventsFor.touch.stop, this.handleDragStop);
      (0, _domFns.removeEvent)(thisNode, eventsFor.touch.start, this.onTouchStart, {
        passive: false
      });
      if (this.props.enableUserSelectHack) (0, _domFns.removeUserSelectStyles)(ownerDocument);
    }
  }
  // React Strict Mode compatibility: if `nodeRef` is passed, we will use it instead of trying to find
  // the underlying DOM node ourselves. See the README for more information.
  findDOMNode() {
    var _this$props, _this$props2;
    return (_this$props = this.props) !== null && _this$props !== void 0 && _this$props.nodeRef ? (_this$props2 = this.props) === null || _this$props2 === void 0 || (_this$props2 = _this$props2.nodeRef) === null || _this$props2 === void 0 ? void 0 : _this$props2.current : _reactDom.default.findDOMNode(this);
  }
  render() {
    return /* @__PURE__ */ React.cloneElement(React.Children.only(this.props.children), {
      // Note: mouseMove handler is attached to document so it will still function
      // when the user drags quickly and leaves the bounds of the element.
      onMouseDown: this.onMouseDown,
      onMouseUp: this.onMouseUp,
      // onTouchStart is added on `componentDidMount` so they can be added with
      // {passive: false}, which allows it to cancel. See
      // https://developers.google.com/web/updates/2017/01/scrolling-intervention
      onTouchEnd: this.onTouchEnd
    });
  }
};
DraggableCore$2.default = DraggableCore$1;
_defineProperty(DraggableCore$1, "displayName", "DraggableCore");
_defineProperty(DraggableCore$1, "propTypes", {
  /**
   * `allowAnyClick` allows dragging using any mouse button.
   * By default, we only accept the left button.
   *
   * Defaults to `false`.
   */
  allowAnyClick: _propTypes.default.bool,
  children: _propTypes.default.node.isRequired,
  /**
   * `disabled`, if true, stops the <Draggable> from dragging. All handlers,
   * with the exception of `onMouseDown`, will not fire.
   */
  disabled: _propTypes.default.bool,
  /**
   * By default, we add 'user-select:none' attributes to the document body
   * to prevent ugly text selection during drag. If this is causing problems
   * for your app, set this to `false`.
   */
  enableUserSelectHack: _propTypes.default.bool,
  /**
   * `offsetParent`, if set, uses the passed DOM node to compute drag offsets
   * instead of using the parent node.
   */
  offsetParent: function(props, propName) {
    if (props[propName] && props[propName].nodeType !== 1) {
      throw new Error("Draggable's offsetParent must be a DOM Node.");
    }
  },
  /**
   * `grid` specifies the x and y that dragging should snap to.
   */
  grid: _propTypes.default.arrayOf(_propTypes.default.number),
  /**
   * `handle` specifies a selector to be used as the handle that initiates drag.
   *
   * Example:
   *
   * ```jsx
   *   let App = React.createClass({
   *       render: function () {
   *         return (
   *            <Draggable handle=".handle">
   *              <div>
   *                  <div className="handle">Click me to drag</div>
   *                  <div>This is some other content</div>
   *              </div>
   *           </Draggable>
   *         );
   *       }
   *   });
   * ```
   */
  handle: _propTypes.default.string,
  /**
   * `cancel` specifies a selector to be used to prevent drag initialization.
   *
   * Example:
   *
   * ```jsx
   *   let App = React.createClass({
   *       render: function () {
   *           return(
   *               <Draggable cancel=".cancel">
   *                   <div>
   *                     <div className="cancel">You can't drag from here</div>
   *                     <div>Dragging here works fine</div>
   *                   </div>
   *               </Draggable>
   *           );
   *       }
   *   });
   * ```
   */
  cancel: _propTypes.default.string,
  /* If running in React Strict mode, ReactDOM.findDOMNode() is deprecated.
   * Unfortunately, in order for <Draggable> to work properly, we need raw access
   * to the underlying DOM node. If you want to avoid the warning, pass a `nodeRef`
   * as in this example:
   *
   * function MyComponent() {
   *   const nodeRef = React.useRef(null);
   *   return (
   *     <Draggable nodeRef={nodeRef}>
   *       <div ref={nodeRef}>Example Target</div>
   *     </Draggable>
   *   );
   * }
   *
   * This can be used for arbitrarily nested components, so long as the ref ends up
   * pointing to the actual child DOM node and not a custom component.
   */
  nodeRef: _propTypes.default.object,
  /**
   * Called when dragging starts.
   * If this function returns the boolean false, dragging will be canceled.
   */
  onStart: _propTypes.default.func,
  /**
   * Called while dragging.
   * If this function returns the boolean false, dragging will be canceled.
   */
  onDrag: _propTypes.default.func,
  /**
   * Called when dragging stops.
   * If this function returns the boolean false, the drag will remain active.
   */
  onStop: _propTypes.default.func,
  /**
   * A workaround option which can be passed if onMouseDown needs to be accessed,
   * since it'll always be blocked (as there is internal use of onMouseDown)
   */
  onMouseDown: _propTypes.default.func,
  /**
   * `scale`, if set, applies scaling while dragging an element
   */
  scale: _propTypes.default.number,
  /**
   * These properties should be defined on the child, not here.
   */
  className: _shims.dontSetMe,
  style: _shims.dontSetMe,
  transform: _shims.dontSetMe
});
_defineProperty(DraggableCore$1, "defaultProps", {
  allowAnyClick: false,
  // by default only accept left click
  disabled: false,
  enableUserSelectHack: true,
  onStart: function() {
  },
  onDrag: function() {
  },
  onStop: function() {
  },
  onMouseDown: function() {
  },
  scale: 1
});
(function(exports) {
  Object.defineProperty(exports, "__esModule", {
    value: true
  });
  Object.defineProperty(exports, "DraggableCore", {
    enumerable: true,
    get: function() {
      return _DraggableCore.default;
    }
  });
  exports.default = void 0;
  var React2 = _interopRequireWildcard2(React__default);
  var _propTypes2 = _interopRequireDefault2(propTypesExports);
  var _reactDom2 = _interopRequireDefault2(require$$2);
  var _clsx = _interopRequireDefault2(require$$3);
  var _domFns2 = domFns;
  var _positionFns2 = positionFns;
  var _shims2 = shims;
  var _DraggableCore = _interopRequireDefault2(DraggableCore$2);
  var _log2 = _interopRequireDefault2(log$1);
  function _interopRequireDefault2(obj) {
    return obj && obj.__esModule ? obj : { default: obj };
  }
  function _getRequireWildcardCache2(nodeInterop) {
    if (typeof WeakMap !== "function") return null;
    var cacheBabelInterop = /* @__PURE__ */ new WeakMap();
    var cacheNodeInterop = /* @__PURE__ */ new WeakMap();
    return (_getRequireWildcardCache2 = function(nodeInterop2) {
      return nodeInterop2 ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
  }
  function _interopRequireWildcard2(obj, nodeInterop) {
    if (obj && obj.__esModule) {
      return obj;
    }
    if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
      return { default: obj };
    }
    var cache = _getRequireWildcardCache2(nodeInterop);
    if (cache && cache.has(obj)) {
      return cache.get(obj);
    }
    var newObj = {};
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for (var key in obj) {
      if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
        var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
        if (desc && (desc.get || desc.set)) {
          Object.defineProperty(newObj, key, desc);
        } else {
          newObj[key] = obj[key];
        }
      }
    }
    newObj.default = obj;
    if (cache) {
      cache.set(obj, newObj);
    }
    return newObj;
  }
  function _extends() {
    _extends = Object.assign ? Object.assign.bind() : function(target) {
      for (var i = 1; i < arguments.length; i++) {
        var source = arguments[i];
        for (var key in source) {
          if (Object.prototype.hasOwnProperty.call(source, key)) {
            target[key] = source[key];
          }
        }
      }
      return target;
    };
    return _extends.apply(this, arguments);
  }
  function _defineProperty2(obj, key, value) {
    key = _toPropertyKey2(key);
    if (key in obj) {
      Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
    } else {
      obj[key] = value;
    }
    return obj;
  }
  function _toPropertyKey2(arg) {
    var key = _toPrimitive2(arg, "string");
    return typeof key === "symbol" ? key : String(key);
  }
  function _toPrimitive2(input, hint) {
    if (typeof input !== "object" || input === null) return input;
    var prim = input[Symbol.toPrimitive];
    if (prim !== void 0) {
      var res = prim.call(input, hint || "default");
      if (typeof res !== "object") return res;
      throw new TypeError("@@toPrimitive must return a primitive value.");
    }
    return (hint === "string" ? String : Number)(input);
  }
  class Draggable2 extends React2.Component {
    // React 16.3+
    // Arity (props, state)
    static getDerivedStateFromProps(_ref, _ref2) {
      let {
        position
      } = _ref;
      let {
        prevPropsPosition
      } = _ref2;
      if (position && (!prevPropsPosition || position.x !== prevPropsPosition.x || position.y !== prevPropsPosition.y)) {
        (0, _log2.default)("Draggable: getDerivedStateFromProps %j", {
          position,
          prevPropsPosition
        });
        return {
          x: position.x,
          y: position.y,
          prevPropsPosition: {
            ...position
          }
        };
      }
      return null;
    }
    constructor(props) {
      super(props);
      _defineProperty2(this, "onDragStart", (e, coreData) => {
        (0, _log2.default)("Draggable: onDragStart: %j", coreData);
        const shouldStart = this.props.onStart(e, (0, _positionFns2.createDraggableData)(this, coreData));
        if (shouldStart === false) return false;
        this.setState({
          dragging: true,
          dragged: true
        });
      });
      _defineProperty2(this, "onDrag", (e, coreData) => {
        if (!this.state.dragging) return false;
        (0, _log2.default)("Draggable: onDrag: %j", coreData);
        const uiData = (0, _positionFns2.createDraggableData)(this, coreData);
        const newState = {
          x: uiData.x,
          y: uiData.y,
          slackX: 0,
          slackY: 0
        };
        if (this.props.bounds) {
          const {
            x,
            y
          } = newState;
          newState.x += this.state.slackX;
          newState.y += this.state.slackY;
          const [newStateX, newStateY] = (0, _positionFns2.getBoundPosition)(this, newState.x, newState.y);
          newState.x = newStateX;
          newState.y = newStateY;
          newState.slackX = this.state.slackX + (x - newState.x);
          newState.slackY = this.state.slackY + (y - newState.y);
          uiData.x = newState.x;
          uiData.y = newState.y;
          uiData.deltaX = newState.x - this.state.x;
          uiData.deltaY = newState.y - this.state.y;
        }
        const shouldUpdate = this.props.onDrag(e, uiData);
        if (shouldUpdate === false) return false;
        this.setState(newState);
      });
      _defineProperty2(this, "onDragStop", (e, coreData) => {
        if (!this.state.dragging) return false;
        const shouldContinue = this.props.onStop(e, (0, _positionFns2.createDraggableData)(this, coreData));
        if (shouldContinue === false) return false;
        (0, _log2.default)("Draggable: onDragStop: %j", coreData);
        const newState = {
          dragging: false,
          slackX: 0,
          slackY: 0
        };
        const controlled = Boolean(this.props.position);
        if (controlled) {
          const {
            x,
            y
          } = this.props.position;
          newState.x = x;
          newState.y = y;
        }
        this.setState(newState);
      });
      this.state = {
        // Whether or not we are currently dragging.
        dragging: false,
        // Whether or not we have been dragged before.
        dragged: false,
        // Current transform x and y.
        x: props.position ? props.position.x : props.defaultPosition.x,
        y: props.position ? props.position.y : props.defaultPosition.y,
        prevPropsPosition: {
          ...props.position
        },
        // Used for compensating for out-of-bounds drags
        slackX: 0,
        slackY: 0,
        // Can only determine if SVG after mounting
        isElementSVG: false
      };
      if (props.position && !(props.onDrag || props.onStop)) {
        console.warn("A `position` was applied to this <Draggable>, without drag handlers. This will make this component effectively undraggable. Please attach `onDrag` or `onStop` handlers so you can adjust the `position` of this element.");
      }
    }
    componentDidMount() {
      if (typeof window.SVGElement !== "undefined" && this.findDOMNode() instanceof window.SVGElement) {
        this.setState({
          isElementSVG: true
        });
      }
    }
    componentWillUnmount() {
      this.setState({
        dragging: false
      });
    }
    // React Strict Mode compatibility: if `nodeRef` is passed, we will use it instead of trying to find
    // the underlying DOM node ourselves. See the README for more information.
    findDOMNode() {
      var _this$props$nodeRef$c, _this$props;
      return (_this$props$nodeRef$c = (_this$props = this.props) === null || _this$props === void 0 || (_this$props = _this$props.nodeRef) === null || _this$props === void 0 ? void 0 : _this$props.current) !== null && _this$props$nodeRef$c !== void 0 ? _this$props$nodeRef$c : _reactDom2.default.findDOMNode(this);
    }
    render() {
      const {
        axis,
        bounds,
        children,
        defaultPosition,
        defaultClassName,
        defaultClassNameDragging,
        defaultClassNameDragged,
        position,
        positionOffset,
        scale,
        ...draggableCoreProps
      } = this.props;
      let style = {};
      let svgTransform = null;
      const controlled = Boolean(position);
      const draggable = !controlled || this.state.dragging;
      const validPosition = position || defaultPosition;
      const transformOpts = {
        // Set left if horizontal drag is enabled
        x: (0, _positionFns2.canDragX)(this) && draggable ? this.state.x : validPosition.x,
        // Set top if vertical drag is enabled
        y: (0, _positionFns2.canDragY)(this) && draggable ? this.state.y : validPosition.y
      };
      if (this.state.isElementSVG) {
        svgTransform = (0, _domFns2.createSVGTransform)(transformOpts, positionOffset);
      } else {
        style = (0, _domFns2.createCSSTransform)(transformOpts, positionOffset);
      }
      const className = (0, _clsx.default)(children.props.className || "", defaultClassName, {
        [defaultClassNameDragging]: this.state.dragging,
        [defaultClassNameDragged]: this.state.dragged
      });
      return /* @__PURE__ */ React2.createElement(_DraggableCore.default, _extends({}, draggableCoreProps, {
        onStart: this.onDragStart,
        onDrag: this.onDrag,
        onStop: this.onDragStop
      }), /* @__PURE__ */ React2.cloneElement(React2.Children.only(children), {
        className,
        style: {
          ...children.props.style,
          ...style
        },
        transform: svgTransform
      }));
    }
  }
  exports.default = Draggable2;
  _defineProperty2(Draggable2, "displayName", "Draggable");
  _defineProperty2(Draggable2, "propTypes", {
    // Accepts all props <DraggableCore> accepts.
    ..._DraggableCore.default.propTypes,
    /**
     * `axis` determines which axis the draggable can move.
     *
     *  Note that all callbacks will still return data as normal. This only
     *  controls flushing to the DOM.
     *
     * 'both' allows movement horizontally and vertically.
     * 'x' limits movement to horizontal axis.
     * 'y' limits movement to vertical axis.
     * 'none' limits all movement.
     *
     * Defaults to 'both'.
     */
    axis: _propTypes2.default.oneOf(["both", "x", "y", "none"]),
    /**
     * `bounds` determines the range of movement available to the element.
     * Available values are:
     *
     * 'parent' restricts movement within the Draggable's parent node.
     *
     * Alternatively, pass an object with the following properties, all of which are optional:
     *
     * {left: LEFT_BOUND, right: RIGHT_BOUND, bottom: BOTTOM_BOUND, top: TOP_BOUND}
     *
     * All values are in px.
     *
     * Example:
     *
     * ```jsx
     *   let App = React.createClass({
     *       render: function () {
     *         return (
     *            <Draggable bounds={{right: 300, bottom: 300}}>
     *              <div>Content</div>
     *           </Draggable>
     *         );
     *       }
     *   });
     * ```
     */
    bounds: _propTypes2.default.oneOfType([_propTypes2.default.shape({
      left: _propTypes2.default.number,
      right: _propTypes2.default.number,
      top: _propTypes2.default.number,
      bottom: _propTypes2.default.number
    }), _propTypes2.default.string, _propTypes2.default.oneOf([false])]),
    defaultClassName: _propTypes2.default.string,
    defaultClassNameDragging: _propTypes2.default.string,
    defaultClassNameDragged: _propTypes2.default.string,
    /**
     * `defaultPosition` specifies the x and y that the dragged item should start at
     *
     * Example:
     *
     * ```jsx
     *      let App = React.createClass({
     *          render: function () {
     *              return (
     *                  <Draggable defaultPosition={{x: 25, y: 25}}>
     *                      <div>I start with transformX: 25px and transformY: 25px;</div>
     *                  </Draggable>
     *              );
     *          }
     *      });
     * ```
     */
    defaultPosition: _propTypes2.default.shape({
      x: _propTypes2.default.number,
      y: _propTypes2.default.number
    }),
    positionOffset: _propTypes2.default.shape({
      x: _propTypes2.default.oneOfType([_propTypes2.default.number, _propTypes2.default.string]),
      y: _propTypes2.default.oneOfType([_propTypes2.default.number, _propTypes2.default.string])
    }),
    /**
     * `position`, if present, defines the current position of the element.
     *
     *  This is similar to how form elements in React work - if no `position` is supplied, the component
     *  is uncontrolled.
     *
     * Example:
     *
     * ```jsx
     *      let App = React.createClass({
     *          render: function () {
     *              return (
     *                  <Draggable position={{x: 25, y: 25}}>
     *                      <div>I start with transformX: 25px and transformY: 25px;</div>
     *                  </Draggable>
     *              );
     *          }
     *      });
     * ```
     */
    position: _propTypes2.default.shape({
      x: _propTypes2.default.number,
      y: _propTypes2.default.number
    }),
    /**
     * These properties should be defined on the child, not here.
     */
    className: _shims2.dontSetMe,
    style: _shims2.dontSetMe,
    transform: _shims2.dontSetMe
  });
  _defineProperty2(Draggable2, "defaultProps", {
    ..._DraggableCore.default.defaultProps,
    axis: "both",
    bounds: false,
    defaultClassName: "react-draggable",
    defaultClassNameDragging: "react-draggable-dragging",
    defaultClassNameDragged: "react-draggable-dragged",
    defaultPosition: {
      x: 0,
      y: 0
    },
    scale: 1
  });
})(Draggable$2);
const {
  default: Draggable,
  DraggableCore: DraggableCore2
} = Draggable$2;
cjs.exports = Draggable;
cjs.exports.default = Draggable;
cjs.exports.DraggableCore = DraggableCore2;
var cjsExports = cjs.exports;
const Draggable$1 = /* @__PURE__ */ getDefaultExportFromCjs(cjsExports);
var __assign$4 = function() {
  __assign$4 = Object.assign || function(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];
      for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
        t[p] = s[p];
    }
    return t;
  };
  return __assign$4.apply(this, arguments);
};
var rowSizeBase = {
  width: "100%",
  height: "10px",
  top: "0px",
  left: "0px",
  cursor: "row-resize"
};
var colSizeBase = {
  width: "10px",
  height: "100%",
  top: "0px",
  left: "0px",
  cursor: "col-resize"
};
var edgeBase = {
  width: "20px",
  height: "20px",
  position: "absolute",
  zIndex: 1
};
var styles = {
  top: __assign$4(__assign$4({}, rowSizeBase), { top: "-5px" }),
  right: __assign$4(__assign$4({}, colSizeBase), { left: void 0, right: "-5px" }),
  bottom: __assign$4(__assign$4({}, rowSizeBase), { top: void 0, bottom: "-5px" }),
  left: __assign$4(__assign$4({}, colSizeBase), { left: "-5px" }),
  topRight: __assign$4(__assign$4({}, edgeBase), { right: "-10px", top: "-10px", cursor: "ne-resize" }),
  bottomRight: __assign$4(__assign$4({}, edgeBase), { right: "-10px", bottom: "-10px", cursor: "se-resize" }),
  bottomLeft: __assign$4(__assign$4({}, edgeBase), { left: "-10px", bottom: "-10px", cursor: "sw-resize" }),
  topLeft: __assign$4(__assign$4({}, edgeBase), { left: "-10px", top: "-10px", cursor: "nw-resize" })
};
var Resizer = memo(function(props) {
  var onResizeStart = props.onResizeStart, direction = props.direction, children = props.children, replaceStyles = props.replaceStyles, className = props.className;
  var onMouseDown = useCallback(function(e) {
    onResizeStart(e, direction);
  }, [onResizeStart, direction]);
  var onTouchStart = useCallback(function(e) {
    onResizeStart(e, direction);
  }, [onResizeStart, direction]);
  var style = useMemo(function() {
    return __assign$4(__assign$4({ position: "absolute", userSelect: "none" }, styles[direction]), replaceStyles !== null && replaceStyles !== void 0 ? replaceStyles : {});
  }, [replaceStyles, direction]);
  return jsx("div", { className: className || void 0, style, onMouseDown, onTouchStart, children });
});
var __extends$1 = /* @__PURE__ */ function() {
  var extendStatics2 = function(d, b) {
    extendStatics2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
      d2.__proto__ = b2;
    } || function(d2, b2) {
      for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
    };
    return extendStatics2(d, b);
  };
  return function(d, b) {
    if (typeof b !== "function" && b !== null)
      throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
    extendStatics2(d, b);
    function __() {
      this.constructor = d;
    }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  };
}();
var __assign$3 = function() {
  __assign$3 = Object.assign || function(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];
      for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
        t[p] = s[p];
    }
    return t;
  };
  return __assign$3.apply(this, arguments);
};
var DEFAULT_SIZE = {
  width: "auto",
  height: "auto"
};
var clamp = function(n, min, max) {
  return Math.max(Math.min(n, max), min);
};
var snap = function(n, size, gridGap) {
  var v = Math.round(n / size);
  return v * size + gridGap * (v - 1);
};
var hasDirection = function(dir, target) {
  return new RegExp(dir, "i").test(target);
};
var isTouchEvent = function(event) {
  return Boolean(event.touches && event.touches.length);
};
var isMouseEvent = function(event) {
  return Boolean((event.clientX || event.clientX === 0) && (event.clientY || event.clientY === 0));
};
var findClosestSnap = function(n, snapArray, snapGap) {
  if (snapGap === void 0) {
    snapGap = 0;
  }
  var closestGapIndex = snapArray.reduce(function(prev, curr, index2) {
    return Math.abs(curr - n) < Math.abs(snapArray[prev] - n) ? index2 : prev;
  }, 0);
  var gap = Math.abs(snapArray[closestGapIndex] - n);
  return snapGap === 0 || gap < snapGap ? snapArray[closestGapIndex] : n;
};
var getStringSize = function(n) {
  n = n.toString();
  if (n === "auto") {
    return n;
  }
  if (n.endsWith("px")) {
    return n;
  }
  if (n.endsWith("%")) {
    return n;
  }
  if (n.endsWith("vh")) {
    return n;
  }
  if (n.endsWith("vw")) {
    return n;
  }
  if (n.endsWith("vmax")) {
    return n;
  }
  if (n.endsWith("vmin")) {
    return n;
  }
  return "".concat(n, "px");
};
var getPixelSize = function(size, parentSize, innerWidth2, innerHeight2) {
  if (size && typeof size === "string") {
    if (size.endsWith("px")) {
      return Number(size.replace("px", ""));
    }
    if (size.endsWith("%")) {
      var ratio = Number(size.replace("%", "")) / 100;
      return parentSize * ratio;
    }
    if (size.endsWith("vw")) {
      var ratio = Number(size.replace("vw", "")) / 100;
      return innerWidth2 * ratio;
    }
    if (size.endsWith("vh")) {
      var ratio = Number(size.replace("vh", "")) / 100;
      return innerHeight2 * ratio;
    }
  }
  return size;
};
var calculateNewMax = function(parentSize, innerWidth2, innerHeight2, maxWidth, maxHeight, minWidth, minHeight) {
  maxWidth = getPixelSize(maxWidth, parentSize.width, innerWidth2, innerHeight2);
  maxHeight = getPixelSize(maxHeight, parentSize.height, innerWidth2, innerHeight2);
  minWidth = getPixelSize(minWidth, parentSize.width, innerWidth2, innerHeight2);
  minHeight = getPixelSize(minHeight, parentSize.height, innerWidth2, innerHeight2);
  return {
    maxWidth: typeof maxWidth === "undefined" ? void 0 : Number(maxWidth),
    maxHeight: typeof maxHeight === "undefined" ? void 0 : Number(maxHeight),
    minWidth: typeof minWidth === "undefined" ? void 0 : Number(minWidth),
    minHeight: typeof minHeight === "undefined" ? void 0 : Number(minHeight)
  };
};
var normalizeToPair = function(val) {
  return Array.isArray(val) ? val : [val, val];
};
var definedProps = [
  "as",
  "ref",
  "style",
  "className",
  "grid",
  "gridGap",
  "snap",
  "bounds",
  "boundsByDirection",
  "size",
  "defaultSize",
  "minWidth",
  "minHeight",
  "maxWidth",
  "maxHeight",
  "lockAspectRatio",
  "lockAspectRatioExtraWidth",
  "lockAspectRatioExtraHeight",
  "enable",
  "handleStyles",
  "handleClasses",
  "handleWrapperStyle",
  "handleWrapperClass",
  "children",
  "onResizeStart",
  "onResize",
  "onResizeStop",
  "handleComponent",
  "scale",
  "resizeRatio",
  "snapGap"
];
var baseClassName = "__resizable_base__";
var Resizable = (
  /** @class */
  function(_super) {
    __extends$1(Resizable2, _super);
    function Resizable2(props) {
      var _a, _b, _c, _d;
      var _this = _super.call(this, props) || this;
      _this.ratio = 1;
      _this.resizable = null;
      _this.parentLeft = 0;
      _this.parentTop = 0;
      _this.resizableLeft = 0;
      _this.resizableRight = 0;
      _this.resizableTop = 0;
      _this.resizableBottom = 0;
      _this.targetLeft = 0;
      _this.targetTop = 0;
      _this.delta = {
        width: 0,
        height: 0
      };
      _this.appendBase = function() {
        if (!_this.resizable || !_this.window) {
          return null;
        }
        var parent = _this.parentNode;
        if (!parent) {
          return null;
        }
        var element = _this.window.document.createElement("div");
        element.style.width = "100%";
        element.style.height = "100%";
        element.style.position = "absolute";
        element.style.transform = "scale(0, 0)";
        element.style.left = "0";
        element.style.flex = "0 0 100%";
        if (element.classList) {
          element.classList.add(baseClassName);
        } else {
          element.className += baseClassName;
        }
        parent.appendChild(element);
        return element;
      };
      _this.removeBase = function(base) {
        var parent = _this.parentNode;
        if (!parent) {
          return;
        }
        parent.removeChild(base);
      };
      _this.state = {
        isResizing: false,
        width: (_b = (_a = _this.propsSize) === null || _a === void 0 ? void 0 : _a.width) !== null && _b !== void 0 ? _b : "auto",
        height: (_d = (_c = _this.propsSize) === null || _c === void 0 ? void 0 : _c.height) !== null && _d !== void 0 ? _d : "auto",
        direction: "right",
        original: {
          x: 0,
          y: 0,
          width: 0,
          height: 0
        },
        backgroundStyle: {
          height: "100%",
          width: "100%",
          backgroundColor: "rgba(0,0,0,0)",
          cursor: "auto",
          opacity: 0,
          position: "fixed",
          zIndex: 9999,
          top: "0",
          left: "0",
          bottom: "0",
          right: "0"
        },
        flexBasis: void 0
      };
      _this.onResizeStart = _this.onResizeStart.bind(_this);
      _this.onMouseMove = _this.onMouseMove.bind(_this);
      _this.onMouseUp = _this.onMouseUp.bind(_this);
      return _this;
    }
    Object.defineProperty(Resizable2.prototype, "parentNode", {
      get: function() {
        if (!this.resizable) {
          return null;
        }
        return this.resizable.parentNode;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Resizable2.prototype, "window", {
      get: function() {
        if (!this.resizable) {
          return null;
        }
        if (!this.resizable.ownerDocument) {
          return null;
        }
        return this.resizable.ownerDocument.defaultView;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Resizable2.prototype, "propsSize", {
      get: function() {
        return this.props.size || this.props.defaultSize || DEFAULT_SIZE;
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Resizable2.prototype, "size", {
      get: function() {
        var width = 0;
        var height = 0;
        if (this.resizable && this.window) {
          var orgWidth = this.resizable.offsetWidth;
          var orgHeight = this.resizable.offsetHeight;
          var orgPosition = this.resizable.style.position;
          if (orgPosition !== "relative") {
            this.resizable.style.position = "relative";
          }
          width = this.resizable.style.width !== "auto" ? this.resizable.offsetWidth : orgWidth;
          height = this.resizable.style.height !== "auto" ? this.resizable.offsetHeight : orgHeight;
          this.resizable.style.position = orgPosition;
        }
        return { width, height };
      },
      enumerable: false,
      configurable: true
    });
    Object.defineProperty(Resizable2.prototype, "sizeStyle", {
      get: function() {
        var _this = this;
        var size = this.props.size;
        var getSize = function(key) {
          var _a;
          if (typeof _this.state[key] === "undefined" || _this.state[key] === "auto") {
            return "auto";
          }
          if (_this.propsSize && _this.propsSize[key] && ((_a = _this.propsSize[key]) === null || _a === void 0 ? void 0 : _a.toString().endsWith("%"))) {
            if (_this.state[key].toString().endsWith("%")) {
              return _this.state[key].toString();
            }
            var parentSize = _this.getParentSize();
            var value = Number(_this.state[key].toString().replace("px", ""));
            var percent = value / parentSize[key] * 100;
            return "".concat(percent, "%");
          }
          return getStringSize(_this.state[key]);
        };
        var width = size && typeof size.width !== "undefined" && !this.state.isResizing ? getStringSize(size.width) : getSize("width");
        var height = size && typeof size.height !== "undefined" && !this.state.isResizing ? getStringSize(size.height) : getSize("height");
        return { width, height };
      },
      enumerable: false,
      configurable: true
    });
    Resizable2.prototype.getParentSize = function() {
      if (!this.parentNode) {
        if (!this.window) {
          return { width: 0, height: 0 };
        }
        return { width: this.window.innerWidth, height: this.window.innerHeight };
      }
      var base = this.appendBase();
      if (!base) {
        return { width: 0, height: 0 };
      }
      var wrapChanged = false;
      var wrap = this.parentNode.style.flexWrap;
      if (wrap !== "wrap") {
        wrapChanged = true;
        this.parentNode.style.flexWrap = "wrap";
      }
      base.style.position = "relative";
      base.style.minWidth = "100%";
      base.style.minHeight = "100%";
      var size = {
        width: base.offsetWidth,
        height: base.offsetHeight
      };
      if (wrapChanged) {
        this.parentNode.style.flexWrap = wrap;
      }
      this.removeBase(base);
      return size;
    };
    Resizable2.prototype.bindEvents = function() {
      if (this.window) {
        this.window.addEventListener("mouseup", this.onMouseUp);
        this.window.addEventListener("mousemove", this.onMouseMove);
        this.window.addEventListener("mouseleave", this.onMouseUp);
        this.window.addEventListener("touchmove", this.onMouseMove, {
          capture: true,
          passive: false
        });
        this.window.addEventListener("touchend", this.onMouseUp);
      }
    };
    Resizable2.prototype.unbindEvents = function() {
      if (this.window) {
        this.window.removeEventListener("mouseup", this.onMouseUp);
        this.window.removeEventListener("mousemove", this.onMouseMove);
        this.window.removeEventListener("mouseleave", this.onMouseUp);
        this.window.removeEventListener("touchmove", this.onMouseMove, true);
        this.window.removeEventListener("touchend", this.onMouseUp);
      }
    };
    Resizable2.prototype.componentDidMount = function() {
      if (!this.resizable || !this.window) {
        return;
      }
      var computedStyle = this.window.getComputedStyle(this.resizable);
      this.setState({
        width: this.state.width || this.size.width,
        height: this.state.height || this.size.height,
        flexBasis: computedStyle.flexBasis !== "auto" ? computedStyle.flexBasis : void 0
      });
    };
    Resizable2.prototype.componentWillUnmount = function() {
      if (this.window) {
        this.unbindEvents();
      }
    };
    Resizable2.prototype.createSizeForCssProperty = function(newSize, kind) {
      var propsSize = this.propsSize && this.propsSize[kind];
      return this.state[kind] === "auto" && this.state.original[kind] === newSize && (typeof propsSize === "undefined" || propsSize === "auto") ? "auto" : newSize;
    };
    Resizable2.prototype.calculateNewMaxFromBoundary = function(maxWidth, maxHeight) {
      var boundsByDirection = this.props.boundsByDirection;
      var direction = this.state.direction;
      var widthByDirection = boundsByDirection && hasDirection("left", direction);
      var heightByDirection = boundsByDirection && hasDirection("top", direction);
      var boundWidth;
      var boundHeight;
      if (this.props.bounds === "parent") {
        var parent_1 = this.parentNode;
        if (parent_1) {
          boundWidth = widthByDirection ? this.resizableRight - this.parentLeft : parent_1.offsetWidth + (this.parentLeft - this.resizableLeft);
          boundHeight = heightByDirection ? this.resizableBottom - this.parentTop : parent_1.offsetHeight + (this.parentTop - this.resizableTop);
        }
      } else if (this.props.bounds === "window") {
        if (this.window) {
          boundWidth = widthByDirection ? this.resizableRight : this.window.innerWidth - this.resizableLeft;
          boundHeight = heightByDirection ? this.resizableBottom : this.window.innerHeight - this.resizableTop;
        }
      } else if (this.props.bounds) {
        boundWidth = widthByDirection ? this.resizableRight - this.targetLeft : this.props.bounds.offsetWidth + (this.targetLeft - this.resizableLeft);
        boundHeight = heightByDirection ? this.resizableBottom - this.targetTop : this.props.bounds.offsetHeight + (this.targetTop - this.resizableTop);
      }
      if (boundWidth && Number.isFinite(boundWidth)) {
        maxWidth = maxWidth && maxWidth < boundWidth ? maxWidth : boundWidth;
      }
      if (boundHeight && Number.isFinite(boundHeight)) {
        maxHeight = maxHeight && maxHeight < boundHeight ? maxHeight : boundHeight;
      }
      return { maxWidth, maxHeight };
    };
    Resizable2.prototype.calculateNewSizeFromDirection = function(clientX, clientY) {
      var scale = this.props.scale || 1;
      var _a = normalizeToPair(this.props.resizeRatio || 1), resizeRatioX = _a[0], resizeRatioY = _a[1];
      var _b = this.state, direction = _b.direction, original = _b.original;
      var _c = this.props, lockAspectRatio = _c.lockAspectRatio, lockAspectRatioExtraHeight = _c.lockAspectRatioExtraHeight, lockAspectRatioExtraWidth = _c.lockAspectRatioExtraWidth;
      var newWidth = original.width;
      var newHeight = original.height;
      var extraHeight = lockAspectRatioExtraHeight || 0;
      var extraWidth = lockAspectRatioExtraWidth || 0;
      if (hasDirection("right", direction)) {
        newWidth = original.width + (clientX - original.x) * resizeRatioX / scale;
        if (lockAspectRatio) {
          newHeight = (newWidth - extraWidth) / this.ratio + extraHeight;
        }
      }
      if (hasDirection("left", direction)) {
        newWidth = original.width - (clientX - original.x) * resizeRatioX / scale;
        if (lockAspectRatio) {
          newHeight = (newWidth - extraWidth) / this.ratio + extraHeight;
        }
      }
      if (hasDirection("bottom", direction)) {
        newHeight = original.height + (clientY - original.y) * resizeRatioY / scale;
        if (lockAspectRatio) {
          newWidth = (newHeight - extraHeight) * this.ratio + extraWidth;
        }
      }
      if (hasDirection("top", direction)) {
        newHeight = original.height - (clientY - original.y) * resizeRatioY / scale;
        if (lockAspectRatio) {
          newWidth = (newHeight - extraHeight) * this.ratio + extraWidth;
        }
      }
      return { newWidth, newHeight };
    };
    Resizable2.prototype.calculateNewSizeFromAspectRatio = function(newWidth, newHeight, max, min) {
      var _a = this.props, lockAspectRatio = _a.lockAspectRatio, lockAspectRatioExtraHeight = _a.lockAspectRatioExtraHeight, lockAspectRatioExtraWidth = _a.lockAspectRatioExtraWidth;
      var computedMinWidth = typeof min.width === "undefined" ? 10 : min.width;
      var computedMaxWidth = typeof max.width === "undefined" || max.width < 0 ? newWidth : max.width;
      var computedMinHeight = typeof min.height === "undefined" ? 10 : min.height;
      var computedMaxHeight = typeof max.height === "undefined" || max.height < 0 ? newHeight : max.height;
      var extraHeight = lockAspectRatioExtraHeight || 0;
      var extraWidth = lockAspectRatioExtraWidth || 0;
      if (lockAspectRatio) {
        var extraMinWidth = (computedMinHeight - extraHeight) * this.ratio + extraWidth;
        var extraMaxWidth = (computedMaxHeight - extraHeight) * this.ratio + extraWidth;
        var extraMinHeight = (computedMinWidth - extraWidth) / this.ratio + extraHeight;
        var extraMaxHeight = (computedMaxWidth - extraWidth) / this.ratio + extraHeight;
        var lockedMinWidth = Math.max(computedMinWidth, extraMinWidth);
        var lockedMaxWidth = Math.min(computedMaxWidth, extraMaxWidth);
        var lockedMinHeight = Math.max(computedMinHeight, extraMinHeight);
        var lockedMaxHeight = Math.min(computedMaxHeight, extraMaxHeight);
        newWidth = clamp(newWidth, lockedMinWidth, lockedMaxWidth);
        newHeight = clamp(newHeight, lockedMinHeight, lockedMaxHeight);
      } else {
        newWidth = clamp(newWidth, computedMinWidth, computedMaxWidth);
        newHeight = clamp(newHeight, computedMinHeight, computedMaxHeight);
      }
      return { newWidth, newHeight };
    };
    Resizable2.prototype.setBoundingClientRect = function() {
      var adjustedScale = 1 / (this.props.scale || 1);
      if (this.props.bounds === "parent") {
        var parent_2 = this.parentNode;
        if (parent_2) {
          var parentRect = parent_2.getBoundingClientRect();
          this.parentLeft = parentRect.left * adjustedScale;
          this.parentTop = parentRect.top * adjustedScale;
        }
      }
      if (this.props.bounds && typeof this.props.bounds !== "string") {
        var targetRect = this.props.bounds.getBoundingClientRect();
        this.targetLeft = targetRect.left * adjustedScale;
        this.targetTop = targetRect.top * adjustedScale;
      }
      if (this.resizable) {
        var _a = this.resizable.getBoundingClientRect(), left = _a.left, top_1 = _a.top, right = _a.right, bottom = _a.bottom;
        this.resizableLeft = left * adjustedScale;
        this.resizableRight = right * adjustedScale;
        this.resizableTop = top_1 * adjustedScale;
        this.resizableBottom = bottom * adjustedScale;
      }
    };
    Resizable2.prototype.onResizeStart = function(event, direction) {
      if (!this.resizable || !this.window) {
        return;
      }
      var clientX = 0;
      var clientY = 0;
      if (event.nativeEvent && isMouseEvent(event.nativeEvent)) {
        clientX = event.nativeEvent.clientX;
        clientY = event.nativeEvent.clientY;
      } else if (event.nativeEvent && isTouchEvent(event.nativeEvent)) {
        clientX = event.nativeEvent.touches[0].clientX;
        clientY = event.nativeEvent.touches[0].clientY;
      }
      if (this.props.onResizeStart) {
        if (this.resizable) {
          var startResize = this.props.onResizeStart(event, direction, this.resizable);
          if (startResize === false) {
            return;
          }
        }
      }
      if (this.props.size) {
        if (typeof this.props.size.height !== "undefined" && this.props.size.height !== this.state.height) {
          this.setState({ height: this.props.size.height });
        }
        if (typeof this.props.size.width !== "undefined" && this.props.size.width !== this.state.width) {
          this.setState({ width: this.props.size.width });
        }
      }
      this.ratio = typeof this.props.lockAspectRatio === "number" ? this.props.lockAspectRatio : this.size.width / this.size.height;
      var flexBasis;
      var computedStyle = this.window.getComputedStyle(this.resizable);
      if (computedStyle.flexBasis !== "auto") {
        var parent_3 = this.parentNode;
        if (parent_3) {
          var dir = this.window.getComputedStyle(parent_3).flexDirection;
          this.flexDir = dir.startsWith("row") ? "row" : "column";
          flexBasis = computedStyle.flexBasis;
        }
      }
      this.setBoundingClientRect();
      this.bindEvents();
      var state = {
        original: {
          x: clientX,
          y: clientY,
          width: this.size.width,
          height: this.size.height
        },
        isResizing: true,
        backgroundStyle: __assign$3(__assign$3({}, this.state.backgroundStyle), { cursor: this.window.getComputedStyle(event.target).cursor || "auto" }),
        direction,
        flexBasis
      };
      this.setState(state);
    };
    Resizable2.prototype.onMouseMove = function(event) {
      var _this = this;
      if (!this.state.isResizing || !this.resizable || !this.window) {
        return;
      }
      if (this.window.TouchEvent && isTouchEvent(event)) {
        try {
          event.preventDefault();
          event.stopPropagation();
        } catch (e) {
        }
      }
      var _a = this.props, maxWidth = _a.maxWidth, maxHeight = _a.maxHeight, minWidth = _a.minWidth, minHeight = _a.minHeight;
      var clientX = isTouchEvent(event) ? event.touches[0].clientX : event.clientX;
      var clientY = isTouchEvent(event) ? event.touches[0].clientY : event.clientY;
      var _b = this.state, direction = _b.direction, original = _b.original, width = _b.width, height = _b.height;
      var parentSize = this.getParentSize();
      var max = calculateNewMax(parentSize, this.window.innerWidth, this.window.innerHeight, maxWidth, maxHeight, minWidth, minHeight);
      maxWidth = max.maxWidth;
      maxHeight = max.maxHeight;
      minWidth = max.minWidth;
      minHeight = max.minHeight;
      var _c = this.calculateNewSizeFromDirection(clientX, clientY), newHeight = _c.newHeight, newWidth = _c.newWidth;
      var boundaryMax = this.calculateNewMaxFromBoundary(maxWidth, maxHeight);
      if (this.props.snap && this.props.snap.x) {
        newWidth = findClosestSnap(newWidth, this.props.snap.x, this.props.snapGap);
      }
      if (this.props.snap && this.props.snap.y) {
        newHeight = findClosestSnap(newHeight, this.props.snap.y, this.props.snapGap);
      }
      var newSize = this.calculateNewSizeFromAspectRatio(newWidth, newHeight, { width: boundaryMax.maxWidth, height: boundaryMax.maxHeight }, { width: minWidth, height: minHeight });
      newWidth = newSize.newWidth;
      newHeight = newSize.newHeight;
      if (this.props.grid) {
        var newGridWidth = snap(newWidth, this.props.grid[0], this.props.gridGap ? this.props.gridGap[0] : 0);
        var newGridHeight = snap(newHeight, this.props.grid[1], this.props.gridGap ? this.props.gridGap[1] : 0);
        var gap = this.props.snapGap || 0;
        var w = gap === 0 || Math.abs(newGridWidth - newWidth) <= gap ? newGridWidth : newWidth;
        var h = gap === 0 || Math.abs(newGridHeight - newHeight) <= gap ? newGridHeight : newHeight;
        newWidth = w;
        newHeight = h;
      }
      var delta = {
        width: newWidth - original.width,
        height: newHeight - original.height
      };
      this.delta = delta;
      if (width && typeof width === "string") {
        if (width.endsWith("%")) {
          var percent = newWidth / parentSize.width * 100;
          newWidth = "".concat(percent, "%");
        } else if (width.endsWith("vw")) {
          var vw = newWidth / this.window.innerWidth * 100;
          newWidth = "".concat(vw, "vw");
        } else if (width.endsWith("vh")) {
          var vh = newWidth / this.window.innerHeight * 100;
          newWidth = "".concat(vh, "vh");
        }
      }
      if (height && typeof height === "string") {
        if (height.endsWith("%")) {
          var percent = newHeight / parentSize.height * 100;
          newHeight = "".concat(percent, "%");
        } else if (height.endsWith("vw")) {
          var vw = newHeight / this.window.innerWidth * 100;
          newHeight = "".concat(vw, "vw");
        } else if (height.endsWith("vh")) {
          var vh = newHeight / this.window.innerHeight * 100;
          newHeight = "".concat(vh, "vh");
        }
      }
      var newState = {
        width: this.createSizeForCssProperty(newWidth, "width"),
        height: this.createSizeForCssProperty(newHeight, "height")
      };
      if (this.flexDir === "row") {
        newState.flexBasis = newState.width;
      } else if (this.flexDir === "column") {
        newState.flexBasis = newState.height;
      }
      var widthChanged = this.state.width !== newState.width;
      var heightChanged = this.state.height !== newState.height;
      var flexBaseChanged = this.state.flexBasis !== newState.flexBasis;
      var changed = widthChanged || heightChanged || flexBaseChanged;
      if (changed) {
        flushSync(function() {
          _this.setState(newState);
        });
      }
      if (this.props.onResize) {
        if (changed) {
          this.props.onResize(event, direction, this.resizable, delta);
        }
      }
    };
    Resizable2.prototype.onMouseUp = function(event) {
      var _a, _b;
      var _c = this.state, isResizing = _c.isResizing, direction = _c.direction;
      _c.original;
      if (!isResizing || !this.resizable) {
        return;
      }
      if (this.props.onResizeStop) {
        this.props.onResizeStop(event, direction, this.resizable, this.delta);
      }
      if (this.props.size) {
        this.setState({ width: (_a = this.props.size.width) !== null && _a !== void 0 ? _a : "auto", height: (_b = this.props.size.height) !== null && _b !== void 0 ? _b : "auto" });
      }
      this.unbindEvents();
      this.setState({
        isResizing: false,
        backgroundStyle: __assign$3(__assign$3({}, this.state.backgroundStyle), { cursor: "auto" })
      });
    };
    Resizable2.prototype.updateSize = function(size) {
      var _a, _b;
      this.setState({ width: (_a = size.width) !== null && _a !== void 0 ? _a : "auto", height: (_b = size.height) !== null && _b !== void 0 ? _b : "auto" });
    };
    Resizable2.prototype.renderResizer = function() {
      var _this = this;
      var _a = this.props, enable = _a.enable, handleStyles = _a.handleStyles, handleClasses = _a.handleClasses, handleWrapperStyle = _a.handleWrapperStyle, handleWrapperClass = _a.handleWrapperClass, handleComponent = _a.handleComponent;
      if (!enable) {
        return null;
      }
      var resizers = Object.keys(enable).map(function(dir) {
        if (enable[dir] !== false) {
          return jsx(Resizer, { direction: dir, onResizeStart: _this.onResizeStart, replaceStyles: handleStyles && handleStyles[dir], className: handleClasses && handleClasses[dir], children: handleComponent && handleComponent[dir] ? handleComponent[dir] : null }, dir);
        }
        return null;
      });
      return jsx("div", { className: handleWrapperClass, style: handleWrapperStyle, children: resizers });
    };
    Resizable2.prototype.render = function() {
      var _this = this;
      var extendsProps = Object.keys(this.props).reduce(function(acc, key) {
        if (definedProps.indexOf(key) !== -1) {
          return acc;
        }
        acc[key] = _this.props[key];
        return acc;
      }, {});
      var style = __assign$3(__assign$3(__assign$3({ position: "relative", userSelect: this.state.isResizing ? "none" : "auto" }, this.props.style), this.sizeStyle), { maxWidth: this.props.maxWidth, maxHeight: this.props.maxHeight, minWidth: this.props.minWidth, minHeight: this.props.minHeight, boxSizing: "border-box", flexShrink: 0 });
      if (this.state.flexBasis) {
        style.flexBasis = this.state.flexBasis;
      }
      var Wrapper = this.props.as || "div";
      return jsxs(Wrapper, __assign$3({ style, className: this.props.className }, extendsProps, {
        // `ref` is after `extendsProps` to ensure this one wins over a version
        // passed in
        ref: function(c) {
          if (c) {
            _this.resizable = c;
          }
        },
        children: [this.state.isResizing && jsx("div", { style: this.state.backgroundStyle }), this.props.children, this.renderResizer()]
      }));
    };
    Resizable2.defaultProps = {
      as: "div",
      onResizeStart: function() {
      },
      onResize: function() {
      },
      onResizeStop: function() {
      },
      enable: {
        top: true,
        right: true,
        bottom: true,
        left: true,
        topRight: true,
        bottomRight: true,
        bottomLeft: true,
        topLeft: true
      },
      style: {},
      grid: [1, 1],
      gridGap: [0, 0],
      lockAspectRatio: false,
      lockAspectRatioExtraWidth: 0,
      lockAspectRatioExtraHeight: 0,
      scale: 1,
      resizeRatio: 1,
      snapGap: 0
    };
    return Resizable2;
  }(PureComponent)
);
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.

See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
var extendStatics = function(d, b) {
  extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
    d2.__proto__ = b2;
  } || function(d2, b2) {
    for (var p in b2) if (b2.hasOwnProperty(p)) d2[p] = b2[p];
  };
  return extendStatics(d, b);
};
function __extends(d, b) {
  extendStatics(d, b);
  function __() {
    this.constructor = d;
  }
  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign$2 = function() {
  __assign$2 = Object.assign || function __assign2(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];
      for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
    }
    return t;
  };
  return __assign$2.apply(this, arguments);
};
function __rest(s, e) {
  var t = {};
  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
    t[p] = s[p];
  if (s != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
      if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
        t[p[i]] = s[p[i]];
    }
  return t;
}
var resizableStyle = {
  width: "auto",
  height: "auto",
  display: "inline-block",
  position: "absolute",
  top: 0,
  left: 0
};
var getEnableResizingByFlag = function(flag) {
  return {
    bottom: flag,
    bottomLeft: flag,
    bottomRight: flag,
    left: flag,
    right: flag,
    top: flag,
    topLeft: flag,
    topRight: flag
  };
};
var Rnd = (
  /** @class */
  function(_super) {
    __extends(Rnd2, _super);
    function Rnd2(props) {
      var _this = _super.call(this, props) || this;
      _this.resizingPosition = { x: 0, y: 0 };
      _this.offsetFromParent = { left: 0, top: 0 };
      _this.resizableElement = { current: null };
      _this.originalPosition = { x: 0, y: 0 };
      _this.state = {
        resizing: false,
        bounds: {
          top: 0,
          right: 0,
          bottom: 0,
          left: 0
        },
        maxWidth: props.maxWidth,
        maxHeight: props.maxHeight
      };
      _this.onResizeStart = _this.onResizeStart.bind(_this);
      _this.onResize = _this.onResize.bind(_this);
      _this.onResizeStop = _this.onResizeStop.bind(_this);
      _this.onDragStart = _this.onDragStart.bind(_this);
      _this.onDrag = _this.onDrag.bind(_this);
      _this.onDragStop = _this.onDragStop.bind(_this);
      _this.getMaxSizesFromProps = _this.getMaxSizesFromProps.bind(_this);
      return _this;
    }
    Rnd2.prototype.componentDidMount = function() {
      this.updateOffsetFromParent();
      var _a = this.offsetFromParent, left = _a.left, top = _a.top;
      var _b = this.getDraggablePosition(), x = _b.x, y = _b.y;
      this.draggable.setState({
        x: x - left,
        y: y - top
      });
      this.forceUpdate();
    };
    Rnd2.prototype.getDraggablePosition = function() {
      var _a = this.draggable.state, x = _a.x, y = _a.y;
      return { x, y };
    };
    Rnd2.prototype.getParent = function() {
      return this.resizable && this.resizable.parentNode;
    };
    Rnd2.prototype.getParentSize = function() {
      return this.resizable.getParentSize();
    };
    Rnd2.prototype.getMaxSizesFromProps = function() {
      var maxWidth = typeof this.props.maxWidth === "undefined" ? Number.MAX_SAFE_INTEGER : this.props.maxWidth;
      var maxHeight = typeof this.props.maxHeight === "undefined" ? Number.MAX_SAFE_INTEGER : this.props.maxHeight;
      return { maxWidth, maxHeight };
    };
    Rnd2.prototype.getSelfElement = function() {
      return this.resizable && this.resizable.resizable;
    };
    Rnd2.prototype.getOffsetHeight = function(boundary) {
      var scale = this.props.scale;
      switch (this.props.bounds) {
        case "window":
          return window.innerHeight / scale;
        case "body":
          return document.body.offsetHeight / scale;
        default:
          return boundary.offsetHeight;
      }
    };
    Rnd2.prototype.getOffsetWidth = function(boundary) {
      var scale = this.props.scale;
      switch (this.props.bounds) {
        case "window":
          return window.innerWidth / scale;
        case "body":
          return document.body.offsetWidth / scale;
        default:
          return boundary.offsetWidth;
      }
    };
    Rnd2.prototype.onDragStart = function(e, data) {
      if (this.props.onDragStart) {
        this.props.onDragStart(e, data);
      }
      var pos = this.getDraggablePosition();
      this.originalPosition = pos;
      if (!this.props.bounds)
        return;
      var parent = this.getParent();
      var scale = this.props.scale;
      var boundary;
      if (this.props.bounds === "parent") {
        boundary = parent;
      } else if (this.props.bounds === "body") {
        var parentRect_1 = parent.getBoundingClientRect();
        var parentLeft_1 = parentRect_1.left;
        var parentTop_1 = parentRect_1.top;
        var bodyRect = document.body.getBoundingClientRect();
        var left_1 = -(parentLeft_1 - parent.offsetLeft * scale - bodyRect.left) / scale;
        var top_1 = -(parentTop_1 - parent.offsetTop * scale - bodyRect.top) / scale;
        var right = (document.body.offsetWidth - this.resizable.size.width * scale) / scale + left_1;
        var bottom = (document.body.offsetHeight - this.resizable.size.height * scale) / scale + top_1;
        return this.setState({ bounds: { top: top_1, right, bottom, left: left_1 } });
      } else if (this.props.bounds === "window") {
        if (!this.resizable)
          return;
        var parentRect_2 = parent.getBoundingClientRect();
        var parentLeft_2 = parentRect_2.left;
        var parentTop_2 = parentRect_2.top;
        var left_2 = -(parentLeft_2 - parent.offsetLeft * scale) / scale;
        var top_2 = -(parentTop_2 - parent.offsetTop * scale) / scale;
        var right = (window.innerWidth - this.resizable.size.width * scale) / scale + left_2;
        var bottom = (window.innerHeight - this.resizable.size.height * scale) / scale + top_2;
        return this.setState({ bounds: { top: top_2, right, bottom, left: left_2 } });
      } else if (typeof this.props.bounds === "string") {
        boundary = document.querySelector(this.props.bounds);
      } else if (this.props.bounds instanceof HTMLElement) {
        boundary = this.props.bounds;
      }
      if (!(boundary instanceof HTMLElement) || !(parent instanceof HTMLElement)) {
        return;
      }
      var boundaryRect = boundary.getBoundingClientRect();
      var boundaryLeft = boundaryRect.left;
      var boundaryTop = boundaryRect.top;
      var parentRect = parent.getBoundingClientRect();
      var parentLeft = parentRect.left;
      var parentTop = parentRect.top;
      var left = (boundaryLeft - parentLeft) / scale;
      var top = boundaryTop - parentTop;
      if (!this.resizable)
        return;
      this.updateOffsetFromParent();
      var offset = this.offsetFromParent;
      this.setState({
        bounds: {
          top: top - offset.top,
          right: left + (boundary.offsetWidth - this.resizable.size.width) - offset.left / scale,
          bottom: top + (boundary.offsetHeight - this.resizable.size.height) - offset.top,
          left: left - offset.left / scale
        }
      });
    };
    Rnd2.prototype.onDrag = function(e, data) {
      if (!this.props.onDrag)
        return;
      var _a = this.offsetFromParent, left = _a.left, top = _a.top;
      if (!this.props.dragAxis || this.props.dragAxis === "both") {
        return this.props.onDrag(e, __assign$2(__assign$2({}, data), { x: data.x + left, y: data.y + top }));
      } else if (this.props.dragAxis === "x") {
        return this.props.onDrag(e, __assign$2(__assign$2({}, data), { x: data.x + left, y: this.originalPosition.y + top, deltaY: 0 }));
      } else if (this.props.dragAxis === "y") {
        return this.props.onDrag(e, __assign$2(__assign$2({}, data), { x: this.originalPosition.x + left, y: data.y + top, deltaX: 0 }));
      }
    };
    Rnd2.prototype.onDragStop = function(e, data) {
      if (!this.props.onDragStop)
        return;
      var _a = this.offsetFromParent, left = _a.left, top = _a.top;
      if (!this.props.dragAxis || this.props.dragAxis === "both") {
        return this.props.onDragStop(e, __assign$2(__assign$2({}, data), { x: data.x + left, y: data.y + top }));
      } else if (this.props.dragAxis === "x") {
        return this.props.onDragStop(e, __assign$2(__assign$2({}, data), { x: data.x + left, y: this.originalPosition.y + top, deltaY: 0 }));
      } else if (this.props.dragAxis === "y") {
        return this.props.onDragStop(e, __assign$2(__assign$2({}, data), { x: this.originalPosition.x + left, y: data.y + top, deltaX: 0 }));
      }
    };
    Rnd2.prototype.onResizeStart = function(e, dir, elementRef) {
      e.stopPropagation();
      this.setState({
        resizing: true
      });
      var scale = this.props.scale;
      var offset = this.offsetFromParent;
      var pos = this.getDraggablePosition();
      this.resizingPosition = { x: pos.x + offset.left, y: pos.y + offset.top };
      this.originalPosition = pos;
      if (this.props.bounds) {
        var parent_1 = this.getParent();
        var boundary = void 0;
        if (this.props.bounds === "parent") {
          boundary = parent_1;
        } else if (this.props.bounds === "body") {
          boundary = document.body;
        } else if (this.props.bounds === "window") {
          boundary = window;
        } else if (typeof this.props.bounds === "string") {
          boundary = document.querySelector(this.props.bounds);
        } else if (this.props.bounds instanceof HTMLElement) {
          boundary = this.props.bounds;
        }
        var self_1 = this.getSelfElement();
        if (self_1 instanceof Element && (boundary instanceof HTMLElement || boundary === window) && parent_1 instanceof HTMLElement) {
          var _a = this.getMaxSizesFromProps(), maxWidth = _a.maxWidth, maxHeight = _a.maxHeight;
          var parentSize = this.getParentSize();
          if (maxWidth && typeof maxWidth === "string") {
            if (maxWidth.endsWith("%")) {
              var ratio = Number(maxWidth.replace("%", "")) / 100;
              maxWidth = parentSize.width * ratio;
            } else if (maxWidth.endsWith("px")) {
              maxWidth = Number(maxWidth.replace("px", ""));
            }
          }
          if (maxHeight && typeof maxHeight === "string") {
            if (maxHeight.endsWith("%")) {
              var ratio = Number(maxHeight.replace("%", "")) / 100;
              maxHeight = parentSize.height * ratio;
            } else if (maxHeight.endsWith("px")) {
              maxHeight = Number(maxHeight.replace("px", ""));
            }
          }
          var selfRect = self_1.getBoundingClientRect();
          var selfLeft = selfRect.left;
          var selfTop = selfRect.top;
          var boundaryRect = this.props.bounds === "window" ? { left: 0, top: 0 } : boundary.getBoundingClientRect();
          var boundaryLeft = boundaryRect.left;
          var boundaryTop = boundaryRect.top;
          var offsetWidth = this.getOffsetWidth(boundary);
          var offsetHeight = this.getOffsetHeight(boundary);
          var hasLeft = dir.toLowerCase().endsWith("left");
          var hasRight = dir.toLowerCase().endsWith("right");
          var hasTop = dir.startsWith("top");
          var hasBottom = dir.startsWith("bottom");
          if ((hasLeft || hasTop) && this.resizable) {
            var max = (selfLeft - boundaryLeft) / scale + this.resizable.size.width;
            this.setState({ maxWidth: max > Number(maxWidth) ? maxWidth : max });
          }
          if (hasRight || this.props.lockAspectRatio && !hasLeft && !hasTop) {
            var max = offsetWidth + (boundaryLeft - selfLeft) / scale;
            this.setState({ maxWidth: max > Number(maxWidth) ? maxWidth : max });
          }
          if ((hasTop || hasLeft) && this.resizable) {
            var max = (selfTop - boundaryTop) / scale + this.resizable.size.height;
            this.setState({
              maxHeight: max > Number(maxHeight) ? maxHeight : max
            });
          }
          if (hasBottom || this.props.lockAspectRatio && !hasTop && !hasLeft) {
            var max = offsetHeight + (boundaryTop - selfTop) / scale;
            this.setState({
              maxHeight: max > Number(maxHeight) ? maxHeight : max
            });
          }
        }
      } else {
        this.setState({
          maxWidth: this.props.maxWidth,
          maxHeight: this.props.maxHeight
        });
      }
      if (this.props.onResizeStart) {
        this.props.onResizeStart(e, dir, elementRef);
      }
    };
    Rnd2.prototype.onResize = function(e, direction, elementRef, delta) {
      var _this = this;
      var newPos = { x: this.originalPosition.x, y: this.originalPosition.y };
      var left = -delta.width;
      var top = -delta.height;
      var directions = ["top", "left", "topLeft", "bottomLeft", "topRight"];
      if (directions.includes(direction)) {
        if (direction === "bottomLeft") {
          newPos.x += left;
        } else if (direction === "topRight") {
          newPos.y += top;
        } else {
          newPos.x += left;
          newPos.y += top;
        }
      }
      var draggableState = this.draggable.state;
      if (newPos.x !== draggableState.x || newPos.y !== draggableState.y) {
        flushSync(function() {
          _this.draggable.setState(newPos);
        });
      }
      this.updateOffsetFromParent();
      var offset = this.offsetFromParent;
      var x = this.getDraggablePosition().x + offset.left;
      var y = this.getDraggablePosition().y + offset.top;
      this.resizingPosition = { x, y };
      if (!this.props.onResize)
        return;
      this.props.onResize(e, direction, elementRef, delta, {
        x,
        y
      });
    };
    Rnd2.prototype.onResizeStop = function(e, direction, elementRef, delta) {
      this.setState({
        resizing: false
      });
      var _a = this.getMaxSizesFromProps(), maxWidth = _a.maxWidth, maxHeight = _a.maxHeight;
      this.setState({ maxWidth, maxHeight });
      if (this.props.onResizeStop) {
        this.props.onResizeStop(e, direction, elementRef, delta, this.resizingPosition);
      }
    };
    Rnd2.prototype.updateSize = function(size) {
      if (!this.resizable)
        return;
      this.resizable.updateSize({ width: size.width, height: size.height });
    };
    Rnd2.prototype.updatePosition = function(position) {
      this.draggable.setState(position);
    };
    Rnd2.prototype.updateOffsetFromParent = function() {
      var scale = this.props.scale;
      var parent = this.getParent();
      var self2 = this.getSelfElement();
      if (!parent || self2 === null) {
        return {
          top: 0,
          left: 0
        };
      }
      var parentRect = parent.getBoundingClientRect();
      var parentLeft = parentRect.left;
      var parentTop = parentRect.top;
      var selfRect = self2.getBoundingClientRect();
      var position = this.getDraggablePosition();
      var scrollLeft = parent.scrollLeft;
      var scrollTop = parent.scrollTop;
      this.offsetFromParent = {
        left: selfRect.left - parentLeft + scrollLeft - position.x * scale,
        top: selfRect.top - parentTop + scrollTop - position.y * scale
      };
    };
    Rnd2.prototype.render = function() {
      var _this = this;
      var _a = this.props, disableDragging = _a.disableDragging, style = _a.style, dragHandleClassName = _a.dragHandleClassName, position = _a.position, onMouseDown = _a.onMouseDown, onMouseUp = _a.onMouseUp, dragAxis = _a.dragAxis, dragGrid = _a.dragGrid, bounds = _a.bounds, enableUserSelectHack = _a.enableUserSelectHack, cancel = _a.cancel, children = _a.children;
      _a.onResizeStart;
      _a.onResize;
      _a.onResizeStop;
      _a.onDragStart;
      _a.onDrag;
      _a.onDragStop;
      var resizeHandleStyles = _a.resizeHandleStyles, resizeHandleClasses = _a.resizeHandleClasses, resizeHandleComponent = _a.resizeHandleComponent, enableResizing = _a.enableResizing, resizeGrid = _a.resizeGrid, resizeHandleWrapperClass = _a.resizeHandleWrapperClass, resizeHandleWrapperStyle = _a.resizeHandleWrapperStyle, scale = _a.scale, allowAnyClick = _a.allowAnyClick, dragPositionOffset = _a.dragPositionOffset, resizableProps = __rest(_a, ["disableDragging", "style", "dragHandleClassName", "position", "onMouseDown", "onMouseUp", "dragAxis", "dragGrid", "bounds", "enableUserSelectHack", "cancel", "children", "onResizeStart", "onResize", "onResizeStop", "onDragStart", "onDrag", "onDragStop", "resizeHandleStyles", "resizeHandleClasses", "resizeHandleComponent", "enableResizing", "resizeGrid", "resizeHandleWrapperClass", "resizeHandleWrapperStyle", "scale", "allowAnyClick", "dragPositionOffset"]);
      var defaultValue = this.props.default ? __assign$2({}, this.props.default) : void 0;
      delete resizableProps.default;
      var cursorStyle = disableDragging || dragHandleClassName ? { cursor: "auto" } : { cursor: "move" };
      var innerStyle = __assign$2(__assign$2(__assign$2({}, resizableStyle), cursorStyle), style);
      var _b = this.offsetFromParent, left = _b.left, top = _b.top;
      var draggablePosition;
      if (position) {
        draggablePosition = {
          x: position.x - left,
          y: position.y - top
        };
      }
      var pos = this.state.resizing ? void 0 : draggablePosition;
      var dragAxisOrUndefined = this.state.resizing ? "both" : dragAxis;
      return createElement(
        Draggable$1,
        {
          ref: function(c) {
            if (!c)
              return;
            _this.draggable = c;
          },
          handle: dragHandleClassName ? ".".concat(dragHandleClassName) : void 0,
          defaultPosition: defaultValue,
          onMouseDown,
          // @ts-expect-error
          onMouseUp,
          onStart: this.onDragStart,
          onDrag: this.onDrag,
          onStop: this.onDragStop,
          axis: dragAxisOrUndefined,
          disabled: disableDragging,
          grid: dragGrid,
          bounds: bounds ? this.state.bounds : void 0,
          position: pos,
          enableUserSelectHack,
          cancel,
          scale,
          allowAnyClick,
          nodeRef: this.resizableElement,
          positionOffset: dragPositionOffset
        },
        createElement(Resizable, __assign$2({}, resizableProps, { ref: function(c) {
          if (!c)
            return;
          _this.resizable = c;
          _this.resizableElement.current = c.resizable;
        }, defaultSize: defaultValue, size: this.props.size, enable: typeof enableResizing === "boolean" ? getEnableResizingByFlag(enableResizing) : enableResizing, onResizeStart: this.onResizeStart, onResize: this.onResize, onResizeStop: this.onResizeStop, style: innerStyle, minWidth: this.props.minWidth, minHeight: this.props.minHeight, maxWidth: this.state.resizing ? this.state.maxWidth : this.props.maxWidth, maxHeight: this.state.resizing ? this.state.maxHeight : this.props.maxHeight, grid: resizeGrid, handleWrapperClass: resizeHandleWrapperClass, handleWrapperStyle: resizeHandleWrapperStyle, lockAspectRatio: this.props.lockAspectRatio, lockAspectRatioExtraWidth: this.props.lockAspectRatioExtraWidth, lockAspectRatioExtraHeight: this.props.lockAspectRatioExtraHeight, handleStyles: resizeHandleStyles, handleClasses: resizeHandleClasses, handleComponent: resizeHandleComponent, scale: this.props.scale }), children)
      );
    };
    Rnd2.defaultProps = {
      maxWidth: Number.MAX_SAFE_INTEGER,
      maxHeight: Number.MAX_SAFE_INTEGER,
      scale: 1,
      onResizeStart: function() {
      },
      onResize: function() {
      },
      onResizeStop: function() {
      },
      onDragStart: function() {
      },
      onDrag: function() {
      },
      onDragStop: function() {
      }
    };
    return Rnd2;
  }(PureComponent)
);
const RESIZING_DISABLED = {
  bottom: false,
  bottomLeft: false,
  bottomRight: false,
  left: false,
  right: false,
  top: false,
  topLeft: false,
  topRight: false
};
const RESIZING_ENABLED = {
  bottom: true,
  bottomLeft: true,
  bottomRight: true,
  left: true,
  right: true,
  top: true,
  topLeft: true,
  topRight: true
};
const MIN_WINDOW_HEIGHT = 30;
const MIN_WINDOW_WIDTH = 166;
const rndDefaults = {
  cancel: ".cancel",
  dragHandleClassName: "handle",
  enableUserSelectHack: false,
  minHeight: `${MIN_WINDOW_HEIGHT}px`,
  minWidth: `${MIN_WINDOW_WIDTH}px`,
  // bounds: "window",
  resizeHandleStyles: {
    bottom: {
      bottom: "-3px",
      cursor: "ns-resize",
      height: "6px"
    },
    bottomLeft: {
      bottom: "-3px",
      cursor: "nesw-resize",
      height: "12px",
      left: "-3px",
      width: "12px"
    },
    bottomRight: {
      bottom: "-3px",
      cursor: "nwse-resize",
      height: "12px",
      right: "-3px",
      width: "12px"
    },
    left: {
      cursor: "ew-resize",
      left: "-3px",
      width: "6px"
    },
    right: {
      cursor: "ew-resize",
      right: "-3px",
      width: "6px"
    },
    top: {
      cursor: "ns-resize",
      height: "6px",
      top: "-3px"
    },
    topLeft: {
      cursor: "nwse-resize",
      height: "12px",
      left: "-3px",
      top: "-3px",
      width: "12px"
    },
    topRight: {
      cursor: "nesw-resize",
      height: "12px",
      right: "-3px",
      top: "-3px",
      width: "12px"
    }
  }
};
const useMinMaxRef = (id) => {
  const { windows } = useContext();
  const { maximized = false, minimized = false } = windows[id] || {};
  const blockAutoPositionRef = useRef(false);
  useEffect(() => {
    blockAutoPositionRef.current = Boolean(maximized || minimized);
  }, [maximized, minimized]);
  return blockAutoPositionRef;
};
const cascadePosition = (id, windows, stackOrder = [], offset = 0, view) => {
  const parentPositionWindow = stackOrder.find((stackPid) => stackPid !== id) || "";
  const { componentWindow } = (windows == null ? void 0 : windows[parentPositionWindow]) || {};
  const {
    x = 0,
    y = 0,
    width = 0,
    height = 0
  } = (componentWindow == null ? void 0 : componentWindow.getBoundingClientRect()) || {};
  const viewportWidth = (view == null ? void 0 : view.width) ? pxToNum(view.width) : viewWidth();
  const viewportHeight = (view == null ? void 0 : view.height) ? pxToNum(view.height) : viewHeight();
  const isOffscreen = x + offset + width > viewportWidth || y + offset + height > viewportHeight;
  return !isOffscreen && (x || y) ? {
    x: x + offset,
    y: y + offset
  } : void 0;
};
const centerPosition = ({ height, width }, viewport) => {
  const vh = viewport ? pxToNum(viewport.height) : viewHeight() - WIN_TASKBAR_HEIGHT;
  const vw = viewport ? pxToNum(viewport.width) : viewWidth();
  return {
    x: Math.floor(vw / 2 - pxToNum(width) / 2),
    y: Math.floor(vh / 2 - pxToNum(height) / 2)
  };
};
const WINDOW_OFFSCREEN_BUFFER_PX = {
  BOTTOM: 15,
  LEFT: 150,
  RIGHT: 50,
  TOP: 15
};
const isWindowOutsideBounds = (windowState, bounds, checkOffscreen = false) => {
  const { position, size } = windowState || {};
  const { x = 0, y = 0 } = position || {};
  const { height = 0, width = 0 } = size || {};
  if (checkOffscreen) {
    return x + WINDOW_OFFSCREEN_BUFFER_PX.RIGHT > bounds.x || x + pxToNum(width) - WINDOW_OFFSCREEN_BUFFER_PX.LEFT < 0 || y + WINDOW_OFFSCREEN_BUFFER_PX.BOTTOM > bounds.y || y + WINDOW_OFFSCREEN_BUFFER_PX.TOP < 0;
  }
  return x < 0 || y < 0 || x + pxToNum(width) > bounds.x || y + pxToNum(height) > bounds.y;
};
const minMaxSize = (size, lockAspectRatio) => {
  const desiredHeight = Number(size.height);
  const desiredWidth = Number(size.width);
  const [vh, vw] = [viewHeight(), viewWidth()];
  const vhWithoutTaskbar = vh - WIN_TASKBAR_HEIGHT;
  const height = Math.max(
    MIN_WINDOW_HEIGHT,
    Math.min(desiredHeight, vhWithoutTaskbar)
  );
  const width = Math.max(MIN_WINDOW_WIDTH, Math.min(desiredWidth, vw));
  if (!lockAspectRatio) return { height, width };
  const isDesiredHeight = desiredHeight === height;
  const isDesiredWidth = desiredWidth === width;
  if (!isDesiredHeight && !isDesiredWidth) {
    if (desiredHeight > desiredWidth) {
      return {
        height,
        width: Math.round(width / (vhWithoutTaskbar / height))
      };
    }
    return {
      height: Math.round(height / (vw / width)),
      width
    };
  }
  if (!isDesiredHeight) {
    return {
      height,
      width: Math.round(width / (desiredHeight / height))
    };
  }
  if (!isDesiredWidth) {
    return {
      height: Math.round(height / (desiredWidth / width)),
      width
    };
  }
  return { height, width };
};
const parseSnap = (snapInfo, parentSize, relatedWindows, windowStates) => {
  const { type, index: index2, widthPercent = 100, heightPercent = 100 } = snapInfo;
  const parentWidth = pxToNum(parentSize.width);
  const parentHeight = pxToNum(parentSize.height);
  let x = 0, y = 0, width = widthPercent / 100 * parentWidth, height = heightPercent / 100 * parentHeight;
  switch (type) {
    case "twoColumns":
      x = index2 === 0 ? 0 : parentWidth - width;
      break;
    case "threeColumns":
      if (relatedWindows) {
        relatedWindows.forEach(
          ([someWindowID, someWindowInfo], thatWindowIndex) => {
            if (!someWindowInfo.snap || typeof someWindowInfo.snap !== "object")
              return;
            const thisWindowWidth = someWindowInfo.snap.widthPercent / 100 * parentWidth;
            if (index2 > thatWindowIndex) {
              x = x + thisWindowWidth;
            }
          }
        );
      }
      break;
    case "fourGrid":
      x = index2 % 2 * (parentWidth / 2);
      y = Math.floor(index2 / 2) * (parentHeight / 2);
      break;
    case "threeLeftOneRight":
      x = index2 === 3 ? parentWidth / 2 : parentWidth / 3 * index2;
      y = index2 === 3 ? 0 : parentHeight / 3 * index2;
      break;
    case "threeRightOneLeft":
      x = index2 === 0 ? 0 : parentWidth / 3 * (index2 - 1) + parentWidth / 2;
      y = index2 === 0 ? 0 : parentHeight / 3 * (index2 - 1);
      break;
    case "fiveLeftGridRight":
      x = index2 === 0 ? 0 : parentWidth / 2 + (index2 - 1) % 2 * (parentWidth / 4);
      y = index2 === 0 ? 0 : Math.floor((index2 - 1) / 2) * (parentHeight / 2);
      break;
    case "fiveRightGridLeft":
      x = index2 === 4 ? parentWidth / 2 : index2 % 2 * (parentWidth / 4);
      y = index2 === 4 ? 0 : Math.floor(index2 / 2) * (parentHeight / 2);
      break;
  }
  width = widthPercent / 100 * parentWidth, height = heightPercent / 100 * parentHeight;
  return {
    width,
    height,
    x,
    y
  };
};
var FUNC_ERROR_TEXT = "Expected a function";
var NAN = 0 / 0;
var symbolTag = "[object Symbol]";
var reTrim = /^\s+|\s+$/g;
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
var reIsBinary = /^0b[01]+$/i;
var reIsOctal = /^0o[0-7]+$/i;
var freeParseInt = parseInt;
var freeGlobal = typeof commonjsGlobal == "object" && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
var freeSelf = typeof self == "object" && self && self.Object === Object && self;
var root = freeGlobal || freeSelf || Function("return this")();
var objectProto = Object.prototype;
var objectToString = objectProto.toString;
var nativeMax = Math.max, nativeMin = Math.min;
var now = function() {
  return root.Date.now();
};
function debounce(func, wait, options) {
  var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
  if (typeof func != "function") {
    throw new TypeError(FUNC_ERROR_TEXT);
  }
  wait = toNumber(wait) || 0;
  if (isObject(options)) {
    leading = !!options.leading;
    maxing = "maxWait" in options;
    maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
    trailing = "trailing" in options ? !!options.trailing : trailing;
  }
  function invokeFunc(time) {
    var args = lastArgs, thisArg = lastThis;
    lastArgs = lastThis = void 0;
    lastInvokeTime = time;
    result = func.apply(thisArg, args);
    return result;
  }
  function leadingEdge(time) {
    lastInvokeTime = time;
    timerId = setTimeout(timerExpired, wait);
    return leading ? invokeFunc(time) : result;
  }
  function remainingWait(time) {
    var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, result2 = wait - timeSinceLastCall;
    return maxing ? nativeMin(result2, maxWait - timeSinceLastInvoke) : result2;
  }
  function shouldInvoke(time) {
    var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime;
    return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
  }
  function timerExpired() {
    var time = now();
    if (shouldInvoke(time)) {
      return trailingEdge(time);
    }
    timerId = setTimeout(timerExpired, remainingWait(time));
  }
  function trailingEdge(time) {
    timerId = void 0;
    if (trailing && lastArgs) {
      return invokeFunc(time);
    }
    lastArgs = lastThis = void 0;
    return result;
  }
  function cancel() {
    if (timerId !== void 0) {
      clearTimeout(timerId);
    }
    lastInvokeTime = 0;
    lastArgs = lastCallTime = lastThis = timerId = void 0;
  }
  function flush() {
    return timerId === void 0 ? result : trailingEdge(now());
  }
  function debounced() {
    var time = now(), isInvoking = shouldInvoke(time);
    lastArgs = arguments;
    lastThis = this;
    lastCallTime = time;
    if (isInvoking) {
      if (timerId === void 0) {
        return leadingEdge(lastCallTime);
      }
      if (maxing) {
        timerId = setTimeout(timerExpired, wait);
        return invokeFunc(lastCallTime);
      }
    }
    if (timerId === void 0) {
      timerId = setTimeout(timerExpired, wait);
    }
    return result;
  }
  debounced.cancel = cancel;
  debounced.flush = flush;
  return debounced;
}
function isObject(value) {
  var type = typeof value;
  return !!value && (type == "object" || type == "function");
}
function isObjectLike(value) {
  return !!value && typeof value == "object";
}
function isSymbol(value) {
  return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;
}
function toNumber(value) {
  if (typeof value == "number") {
    return value;
  }
  if (isSymbol(value)) {
    return NAN;
  }
  if (isObject(value)) {
    var other = typeof value.valueOf == "function" ? value.valueOf() : value;
    value = isObject(other) ? other + "" : other;
  }
  if (typeof value != "string") {
    return value === 0 ? value : +value;
  }
  value = value.replace(reTrim, "");
  var isBinary = reIsBinary.test(value);
  return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
}
var lodash_debounce = debounce;
const debounce$1 = /* @__PURE__ */ getDefaultExportFromCjs(lodash_debounce);
const useDraggable = (id, size) => {
  const {
    sizes: {
      window: { cascadeOffset }
    }
  } = useTheme();
  const { windows } = useContext();
  const { autoSizing, closing, componentWindow, initialRelativePosition } = windows[id] || {};
  const { events: RD_Events } = useContext$1();
  const { stackOrder, windowStates: { [id]: windowState } = {} } = useContext$2();
  const { position: sessionPosition, size: sessionSize } = windowState || {};
  const { WindowsViewAreaSize } = useContext$3();
  const isOffscreen = useMemo(
    () => isWindowOutsideBounds(windowState, {
      x: pxToNum(WindowsViewAreaSize == null ? void 0 : WindowsViewAreaSize.width) || viewWidth(),
      y: pxToNum(WindowsViewAreaSize == null ? void 0 : WindowsViewAreaSize.height) || viewHeight()
    }),
    [windowState, WindowsViewAreaSize]
  );
  const [position, setPosition] = useState(
    () => !isOffscreen && sessionPosition || cascadePosition(
      id,
      windows,
      stackOrder,
      cascadeOffset,
      WindowsViewAreaSize
    ) || centerPosition(size, WindowsViewAreaSize)
  );
  const blockAutoPositionRef = useMinMaxRef(id);
  const positionRef = useRef(position);
  useEffect(() => {
    positionRef.current = position;
  }, [position]);
  useEffect(() => {
    const monitorViewportResize = debounce$1((newWindowsViewSize) => {
      const bounds = {
        x: pxToNum(newWindowsViewSize.width) || viewWidth(),
        y: pxToNum(newWindowsViewSize.height) || viewHeight()
      };
      if (isWindowOutsideBounds(
        { position: positionRef.current, size },
        bounds,
        true
      )) {
        setPosition(({ x, y }) => {
          const xOffset = bounds.x - WINDOW_OFFSCREEN_BUFFER_PX.RIGHT;
          const yOffset = bounds.y - WINDOW_OFFSCREEN_BUFFER_PX.BOTTOM;
          const newX = x > xOffset ? xOffset : x;
          const newY = y > yOffset ? yOffset : y;
          if (newX !== x || newY !== y) {
            return { x: newX, y: newY };
          }
          return { x, y };
        });
      }
    }, 20);
    const registeredEvents = [
      RD_Events.on("event:elements/resize/windowsview", monitorViewportResize)
    ];
    return () => {
      registeredEvents.forEach(RD_Events.removeListenerByID);
      monitorViewportResize.cancel();
    };
  }, [size, RD_Events]);
  useLayoutEffect(() => {
    if (autoSizing && !closing && sessionSize && !sessionPosition && !blockAutoPositionRef.current) {
      setPosition(centerPosition(sessionSize));
    }
  }, [autoSizing, blockAutoPositionRef, closing, sessionPosition, sessionSize]);
  useLayoutEffect(() => {
    if (initialRelativePosition && componentWindow && size) {
      setPosition(
        calcInitialPosition(componentWindow, initialRelativePosition, size)
      );
    }
  }, [componentWindow, initialRelativePosition, size]);
  return [position, setPosition];
};
const useDefaultSize = (id) => {
  const { windows: { [id]: currentWindow } = {} } = useContext();
  const { defaultSize, snap: snap2 = false } = currentWindow || {};
  const { WindowsViewArea, WindowsViewAreaSize } = useContext$3();
  const isSnap = useMemo(() => snap2 && typeof snap2 === "object", [snap2]);
  const data = useMemo(() => {
    if (isSnap) {
      const parentSize = WindowsViewArea ? getElementSize(WindowsViewArea) : WindowsViewAreaSize;
      return parseSnap(snap2, parentSize);
    }
    return null;
  }, [isSnap, snap2, WindowsViewArea]);
  return useMemo(() => {
    if (isSnap && data) {
      return {
        height: data.height,
        // Cast to number
        width: data.width
        // Cast to number
      };
    }
    return defaultSize ? {
      height: defaultSize.height,
      width: defaultSize.width
    } : DEFAULT_WINDOW_SIZE;
  }, [isSnap, data, defaultSize]);
};
const useResizable = (id, autoSizing = false) => {
  const defaultSize = useDefaultSize(id);
  const { events: RD_Events } = useContext$1();
  const {
    windowStates: {
      [id]: { size: stateSize = defaultSize } = {},
      ...otherWindowStates
    } = {}
  } = useContext$2();
  const { disableAnimations } = useContext$4();
  const {
    windows: {
      [id]: {
        lockAspectRatio = false,
        snap: snap2 = false,
        closing = false,
        maximized = false
      } = {},
      ...otherWindows
    },
    setSnap
  } = useContext();
  const { Events: RD_WindowEvents } = useContext$5();
  const { WindowsViewArea, WindowsViewAreaSize } = useContext$3();
  const [size, setSize] = useState(
    () => minMaxSize(stateSize, lockAspectRatio)
  );
  const blockAutoSizeRef = useMinMaxRef(id);
  const isSnap = !closing && snap2 && typeof snap2 === "object" && typeof snap2 !== "boolean";
  const onResize = useCallback(
    (newSize) => {
      if (isSnap) {
        const currentWindowsViewSize = WindowsViewArea ? getElementSize(WindowsViewArea) : WindowsViewAreaSize;
        const newWidthPercent = pxToNum(newSize.width) / pxToNum(currentWindowsViewSize.width);
        const newHeightPercent = pxToNum(newSize.height) / pxToNum(currentWindowsViewSize.height);
        const newHeightPercentNice = newHeightPercent * 100;
        const newWidthPercentNice = newWidthPercent * 100;
        const availableWidthPercent = 100 - newWidthPercentNice;
        const relatedWindows = Object.entries(otherWindows).filter(
          ([id2, { snap: someWindowSnap, closing: closing2 }]) => {
            return !closing2 && someWindowSnap && typeof someWindowSnap !== "boolean" && typeof snap2 !== "boolean" && someWindowSnap.type === (snap2 == null ? void 0 : snap2.type) && someWindowSnap.index !== (snap2 == null ? void 0 : snap2.index);
          }
        );
        setSnap(id, {
          ...snap2,
          widthPercent: newWidthPercentNice,
          heightPercent: newHeightPercentNice
        });
        relatedWindows.forEach(([someWindowID, { snap: someWindowSnap }]) => {
          const newSnap = {
            ...someWindowSnap
          };
          if (snap2.type === "twoColumns") {
            newSnap.widthPercent = availableWidthPercent;
          } else if (snap2.type === "threeColumns") {
            newSnap.widthPercent = Math.abs(
              availableWidthPercent - newSnap.widthPercent
            );
          }
          setSnap(someWindowID, {
            ...someWindowSnap,
            ...newSnap
          });
          RD_Events.emit(
            "event:elements/resize/windowsview",
            currentWindowsViewSize
          );
        });
      }
    },
    [
      isSnap,
      WindowsViewArea,
      WindowsViewAreaSize,
      id,
      RD_Events,
      otherWindows,
      setSnap,
      snap2
    ]
  );
  useLayoutEffect(() => {
    const registeredEvents = [
      RD_WindowEvents.on(
        `event:window/resize`,
        ({ size: newSize, ...other }) => {
          if (other.user_resize) {
            onResize(newSize);
          }
        }
      )
    ];
    return () => {
      registeredEvents.forEach(RD_Events.removeListenerByID);
    };
  }, [onResize, RD_Events, id]);
  const announceNewSize = useCallback(
    ({
      size: size2,
      maximized: maximized2 = false,
      user_resize = false
    }) => {
      const eventMsg = {
        maximized: maximized2,
        size: size2,
        user_resize
      };
      RD_WindowEvents.emit("event:window/resize", eventMsg);
      RD_Events.emit(
        ["event:windows/resize", `event:windows/resize:${id}`],
        eventMsg
      );
    },
    [RD_WindowEvents, RD_Events]
  );
  useLayoutEffect(() => {
    if (maximized) {
      if (disableAnimations) {
        window.requestAnimationFrame(
          () => announceNewSize({
            size: getElementSize(WindowsViewArea),
            maximized: true
          })
        );
      } else {
        setTimeout(() => {
          window.requestAnimationFrame(
            () => announceNewSize({
              size: getElementSize(WindowsViewArea),
              maximized: true
            })
          );
        }, TRANSITIONS_IN_MILLISECONDS.WINDOW + 150);
      }
    }
    const registeredEvents = [];
    const monitorViewportResize = (newWindowsViewSize) => {
      if (maximized) {
        if (disableAnimations) {
          window.requestAnimationFrame(
            () => announceNewSize({ size: newWindowsViewSize, maximized: true })
          );
        } else {
          setTimeout(() => {
            window.requestAnimationFrame(
              () => announceNewSize({
                size: newWindowsViewSize,
                maximized: true
              })
            );
          }, TRANSITIONS_IN_MILLISECONDS.WINDOW + 150);
        }
      }
    };
    if (maximized) {
      registeredEvents.push(
        RD_Events.on("event:elements/resize/windowsview", monitorViewportResize)
      );
    }
    return () => {
      registeredEvents.forEach(RD_Events.removeListenerByID);
    };
  }, [id, disableAnimations, maximized, WindowsViewArea, announceNewSize]);
  useLayoutEffect(() => {
    if (!maximized) {
      announceNewSize({ size, user_resize: false, maximized: false });
    }
  }, [maximized, size, id, announceNewSize]);
  useLayoutEffect(() => {
    if (autoSizing && !blockAutoSizeRef.current) {
      setSize(minMaxSize(stateSize, lockAspectRatio));
    }
  }, [autoSizing, blockAutoSizeRef, lockAspectRatio, stateSize]);
  return [size, setSize];
};
const enableIframeCapture = (enable = true) => document.querySelectorAll("iframe").forEach((iframe) => {
  iframe.style.pointerEvents = enable ? "initial" : "none";
});
const useRnd = (id) => {
  const {
    windows: {
      [id]: {
        snap: snap2 = false,
        allowResizing = true,
        autoSizing = false,
        lockAspectRatio = false,
        maximized = false
      } = {},
      ...otherWindows
    },
    setSnap
  } = useContext();
  const { events: RD_Events } = useContext$1();
  const { Events: RD_WindowEvents } = useContext$5();
  const { setWindowStates } = useContext$2();
  const { onMaximize } = useWindowActions(id);
  const { WindowsViewArea, getLatestSize } = useContext$3();
  const [size, setSize] = useResizable(id, autoSizing);
  const [position, setPosition] = useDraggable(id, size);
  const isSnap = snap2 && typeof snap2 === "object";
  useLayoutEffect(() => {
    const updateSnapDetails = (windowsViewSize) => {
      if (isSnap) {
        const relatedWindows = Object.entries(otherWindows).filter(
          ([id2, { snap: someWindowSnap, closing }]) => {
            return !closing && someWindowSnap && typeof someWindowSnap === "object" && someWindowSnap.type === snap2.type && someWindowSnap.index !== snap2.index;
          }
        );
        const parsedSnap = parseSnap(
          snap2,
          windowsViewSize,
          relatedWindows
        );
        if (position.x !== parsedSnap.x || position.y !== parsedSnap.y) {
          setPosition({
            x: parsedSnap.x,
            y: parsedSnap.y
          });
        }
        if (size.width !== parsedSnap.width || size.height !== parsedSnap.height) {
          setSize({
            width: parsedSnap.width || 0,
            height: parsedSnap.height || 0
          });
        }
      }
    };
    const registeredEvents = [
      RD_Events.on("event:elements/resize/windowsview", updateSnapDetails)
    ];
    return () => {
      registeredEvents.forEach(RD_Events.removeListenerByID);
    };
  }, [
    snap2,
    otherWindows,
    position,
    WindowsViewArea,
    RD_Events,
    isSnap,
    size,
    setPosition,
    setSize
  ]);
  const updateWindowState = useCallback(
    (newPosition, newSize) => {
      setWindowStates((currentWindowStates) => ({
        ...currentWindowStates,
        [id]: {
          ...currentWindowStates[id],
          position: newPosition,
          size: newSize
        }
      }));
    },
    [id, setWindowStates]
  );
  useEffect(() => {
    if (isSnap) {
      const parentSize = WindowsViewArea ? getElementSize(WindowsViewArea) : getLatestSize("WindowsViewArea");
      const relatedWindows = Object.entries(otherWindows).filter(
        ([id2, { snap: someWindowSnap, closing }]) => {
          return !closing && someWindowSnap && typeof someWindowSnap === "object" && someWindowSnap.type === snap2.type && someWindowSnap.index !== snap2.index;
        }
      );
      const parsedSnap = parseSnap(
        snap2,
        parentSize,
        relatedWindows
      );
      if (position.x !== parsedSnap.x || position.y !== parsedSnap.y) {
        setPosition({
          x: parsedSnap.x,
          y: parsedSnap.y
        });
      }
      if (size.width !== parsedSnap.width || size.height !== parsedSnap.height) {
        setSize({
          width: parsedSnap.width || 0,
          height: parsedSnap.height || 0
        });
      }
    }
  }, [WindowsViewArea, getLatestSize, snap2]);
  const disableIframeCapture = useCallback(
    () => enableIframeCapture(false),
    []
  );
  const onDragStart = useCallback(
    (event, { x, y }) => {
      disableIframeCapture();
      setSnap(id, false);
      if (maximized) {
        setPosition((prevPos) => ({
          ...prevPos,
          y: 0
        }));
        onMaximize();
      }
      const startPosition = { x, y };
      const eventMsg = { position: startPosition, id };
      RD_WindowEvents.emit("event:window/drag_start", eventMsg);
      RD_Events.emit(
        ["event:windows/drag_start", `event:windows/drag_start:${id}`],
        eventMsg
      );
    },
    [disableIframeCapture, setSnap, id, maximized, RD_WindowEvents, RD_Events, setPosition, onMaximize]
  );
  const onDragStop = useCallback(
    (_event, { x, y }) => {
      enableIframeCapture();
      const newPosition = { x, y };
      const windowsContainerSize = WindowsViewArea ? getElementSize(WindowsViewArea) : getLatestSize("WindowsViewArea");
      if (!isWindowOutsideBounds(
        { position: newPosition, size },
        {
          x: pxToNum(windowsContainerSize.width),
          y: pxToNum(windowsContainerSize.height)
        },
        true
      )) {
        const isSnap2 = snap2 && typeof snap2 === "object";
        setPosition((currentPos) => {
          const differences = {
            x: Math.abs(newPosition.x - currentPos.x),
            y: Math.abs(newPosition.y - currentPos.y)
          };
          if (differences.x >= 5 || differences.y >= 5) {
            if (isSnap2) {
              const windowsContainerSize2 = WindowsViewArea ? getElementSize(WindowsViewArea) : getLatestSize("WindowsViewArea");
              const data = parseSnap(snap2, windowsContainerSize2);
              setSize({
                width: data.width || 0,
                height: data.height || 0
              });
              setPosition({
                x: data.x || 0,
                y: data.y || 0
              });
              const relatedWindows = Object.entries(otherWindows).filter(
                ([id2, { snap: someWindowSnap, closing }]) => {
                  return !closing && someWindowSnap && typeof someWindowSnap === "object" && someWindowSnap.type === snap2.type && someWindowSnap.index !== snap2.index;
                }
              );
              relatedWindows.forEach(
                ([someWindowID, someWindowSnap], thatWindowIndex) => {
                  let newSnap;
                  if (typeof someWindowSnap === "object" && someWindowSnap !== null) {
                    const snapInfo = { ...someWindowSnap };
                    if (snapInfo.type === "threeColumns") {
                      snapInfo.type = "twoColumns";
                      snapInfo.widthPercent = 50;
                      snapInfo.index = thatWindowIndex;
                    } else if (snapInfo.type === "twoColumns") {
                      newSnap = false;
                    } else {
                      newSnap = snapInfo;
                    }
                    newSnap = snapInfo;
                  } else {
                    newSnap = false;
                  }
                  setSnap(someWindowID, newSnap);
                }
              );
              setSnap(id, false);
            }
          }
          return newPosition;
        });
        updateWindowState(newPosition, size);
        const eventMsg = { position: newPosition, id };
        RD_WindowEvents.emit("event:window/drag_stop", eventMsg);
        RD_Events.emit(
          ["event:windows/drag_stop", `event:windows/drag_stop:${id}`],
          eventMsg
        );
      }
    },
    [
      WindowsViewArea,
      getLatestSize,
      size,
      snap2,
      setPosition,
      updateWindowState,
      RD_Events,
      RD_WindowEvents,
      id,
      setSize,
      otherWindows,
      setSnap
    ]
  );
  const onResizeStart = useCallback(
    (event, direction, ref) => {
      disableIframeCapture();
      const currentSize = {
        width: pxToNum(ref.style.width),
        height: pxToNum(ref.style.height)
      };
      const eventMsg = { size: currentSize, id };
      RD_WindowEvents.emit("event:window/resize_start", eventMsg);
      RD_Events.emit(
        ["event:windows/resize_start", `event:windows/resize_start:${id}`],
        eventMsg
      );
    },
    [RD_Events, RD_WindowEvents, id, disableIframeCapture]
  );
  const onResizeStop = useCallback(
    (_event, _direction, { style: { height, width, transform } }, _delta, resizePosition) => {
      const [, x, y] = transform.match(/translate\((-?\d+)px, (-?\d+)px\)/) || [];
      const newPosition = typeof x === "string" && typeof y === "string" ? { x: pxToNum(x), y: pxToNum(y) } : resizePosition;
      enableIframeCapture();
      const newSize = { height: pxToNum(height), width: pxToNum(width) };
      if (newPosition.y < 0) {
        newSize.height += newPosition.y;
        newPosition.y = 0;
      }
      setPosition(newPosition);
      setSize(newSize);
      updateWindowState(newPosition, newSize);
      const eventMsg = {
        position: newPosition,
        size: newSize,
        id
      };
      RD_WindowEvents.emit("event:window/resize_stop", eventMsg);
      RD_Events.emit(
        ["event:windows/resize_stop", `event:windows/resize_stop:${id}`],
        eventMsg
      );
    },
    [id, setPosition, setSize, RD_Events, RD_WindowEvents, updateWindowState]
  );
  const enableResizing = useMemo(
    () => allowResizing && !maximized ? RESIZING_ENABLED : RESIZING_DISABLED,
    [allowResizing, maximized]
  );
  const onDrag = useCallback(
    (_event, { x, y }) => {
      const newPosition = { x, y };
      const eventMsg = {
        position: newPosition,
        id
      };
      RD_WindowEvents.emit("event:window/drag", eventMsg);
      RD_Events.emit(
        ["event:windows/drag", `event:windows/drag:${id}`],
        eventMsg
      );
    },
    [RD_Events, RD_WindowEvents, id]
  );
  const onResize = useCallback(
    (_event, _direction, { style: { height, width } }, _delta, resizePosition) => {
      const newPosition = resizePosition;
      const newSize = { height: pxToNum(height), width: pxToNum(width) };
      if (isSnap) {
        const parentSize = WindowsViewArea ? getElementSize(WindowsViewArea) : getLatestSize("WindowsViewArea");
        const relatedWindows = Object.entries(otherWindows).filter(
          ([id2, { snap: someWindowSnap, closing }]) => {
            return !closing && someWindowSnap && typeof someWindowSnap === "object" && someWindowSnap.type === snap2.type && someWindowSnap.index !== snap2.index;
          }
        );
        setTimeout(() => {
          const parsedSnap = parseSnap(
            snap2,
            parentSize,
            relatedWindows
          );
          if (position.x !== parsedSnap.x || position.y !== parsedSnap.y) {
            console.log("POSITION CHANGE");
            setPosition({
              x: parsedSnap.x || 0,
              y: parsedSnap.y || 0
            });
          }
          if (newSize.width !== parsedSnap.width || newSize.height !== parsedSnap.height) {
            setSize({
              width: parsedSnap.width || 0,
              height: parsedSnap.height || 0
            });
          }
        }, TRANSITIONS_IN_MILLISECONDS.WINDOW + 50);
      }
      const eventMsg = {
        position: newPosition,
        size: newSize,
        id,
        user_resize: true
      };
      RD_WindowEvents.emit("event:window/resize", eventMsg);
      RD_Events.emit(
        ["event:windows/resize", `event:windows/resize:${id}`],
        eventMsg
      );
    },
    [
      RD_WindowEvents,
      RD_Events,
      WindowsViewArea,
      getLatestSize,
      id,
      isSnap,
      otherWindows,
      position,
      setPosition,
      setSize,
      snap2
    ]
  );
  return {
    disableDragging: maximized,
    enableResizing,
    lockAspectRatio,
    onDrag,
    onDragStart,
    onDragStop,
    onResize,
    onResizeStart,
    onResizeStop,
    position,
    size,
    ...rndDefaults
  };
};
const reRouteFocus = (focusElement) => (element) => {
  element == null ? void 0 : element.setAttribute("tabindex", FOCUSABLE_ELEMENT.tabIndex.toString());
  element == null ? void 0 : element.addEventListener("contextmenu", haltEvent);
  element == null ? void 0 : element.addEventListener("mousedown", (event) => {
    event.preventDefault();
    focusElement == null ? void 0 : focusElement.focus(PREVENT_SCROLL);
  });
};
const RndWindow = ({ children, id, zIndex, ...extraProps }) => {
  const {
    linkElement,
    windows: { [id]: currentWindow }
  } = useContext();
  const { previewID } = useContext$2();
  const { disableAnimations } = useContext$4();
  const { Component, componentWindow, maximized, minimized } = currentWindow || {};
  const rndRef = useRef(null);
  const rndProps = useRnd(id);
  const isPreview = previewID !== false;
  const isPreviewAndNotOnUs = isPreview && previewID !== id;
  const style = useMemo(
    () => ({
      pointerEvents: minimized ? "none" : void 0,
      zIndex,
      // position: disableAnimations ? "absolute" : undefined,
      transform: "none",
      willChange: "transform",
      // willChange: !disableAnimations ? "transform" : "top,left",
      display: disableAnimations && minimized && (isPreview ? isPreviewAndNotOnUs : true) ? "none" : void 0,
      width: maximized ? "100%" : void 0,
      height: maximized ? "100%" : void 0
    }),
    [minimized, zIndex, disableAnimations, isPreview, isPreviewAndNotOnUs, maximized]
  );
  const linkComponentWindow = useCallback(
    (rndEntry) => {
      var _a, _b;
      rndRef.current = rndEntry;
      const rndWindowElements = ((_b = (_a = rndEntry == null ? void 0 : rndEntry.resizableElement) == null ? void 0 : _a.current) == null ? void 0 : _b.children) || [];
      const [windowContainer] = rndWindowElements;
      if (Component && !componentWindow && windowContainer) {
        linkElement(id, "componentWindow", windowContainer);
      }
    },
    [Component, componentWindow, id, linkElement]
  );
  useEffect(() => {
    var _a, _b;
    if (!maximized) {
      const { current: currentRndWindow } = rndRef;
      const rndWindowElements = ((_b = (_a = currentRndWindow == null ? void 0 : currentRndWindow.resizableElement) == null ? void 0 : _a.current) == null ? void 0 : _b.children) || [];
      const [windowContainer, resizeHandleContainer] = rndWindowElements;
      const resizeHandles = [...(resizeHandleContainer == null ? void 0 : resizeHandleContainer.children) || []];
      resizeHandles.forEach(reRouteFocus(windowContainer));
    }
  }, [maximized]);
  return /* @__PURE__ */ jsx(
    Rnd,
    {
      ref: linkComponentWindow,
      style,
      ...rndProps,
      position: maximized && disableAnimations ? { x: 0, y: 0 } : rndProps.position,
      size: maximized && disableAnimations ? { width: "100%", height: "100%" } : rndProps.size,
      ...extraProps,
      children
    }
  );
};
const RndWindow$1 = memo(RndWindow);
const StyledWindow = styled(m.section)`
  background-color: ${({ $backgroundColor, theme }) => $backgroundColor || theme.colors.window.background};
  box-shadow: ${({ $showShadows, $isForeground, theme }) => $showShadows ? $isForeground ? theme.colors.window.shadow : theme.colors.window.shadowInactive : "none"};
  contain: strict;
  ${({ $isPreview, $previewOnMe }) => $isPreview && !$previewOnMe && `opacity: 0.5!important;`}
  ${({ $isPreview, $previewOnMe }) => $isPreview && $previewOnMe && `border: 2px dashed #3af2a2;`}
  border-radius: ${({ $rounded }) => $rounded ? "6px" : "0"};
  height: 100%;
  outline: ${({ $isForeground, theme }) => `${theme.sizes.window.outline} solid ${$isForeground ? theme.colors.window.outline : theme.colors.window.outlineInactive}`};
  overflow: hidden;
  position: relative;
  width: 100%;
`;
const styledBorder = ({
  $foreground,
  theme
}) => $foreground ? `1px solid ${theme.colors.titleBar.background}` : `1px solid ${theme.colors.titleBar.backgroundInactive}`;
const StyledTitlebar = styled.header`
  ${defaultStyles}
  background-color: ${({ $foreground, theme }) => $foreground ? theme.colors.titleBar.background : theme.colors.titleBar.backgroundInactive};
  border-bottom: ${styledBorder};
  display: flex;
  height: ${({ theme }) => theme.sizes.titleBar.height}px;
  position: relative;
  top: 0;
  z-index: 2;
  user-select: none;
  pointer-events: all;
  box-sizing: border-box;
  font-variant-numeric: tabular-nums;
  text-rendering: optimizelegibility;

  &:active {
    cursor: grabbing;
  }
  
  > button {
    align-items: center;
    color: ${({ $foreground, theme }) => $foreground ? theme.colors.titleBar.text : theme.colors.titleBar.textInactive};
    display: flex;
    flex-grow: 1;
    font-size: ${({ theme }) => theme.sizes.titleBar.fontSize};
    font-weight: 400;
    min-width: 0;

    figure {
      align-items: center;
      display: flex;
      margin-left: 8px;
      min-width: inherit;
      pointer-events: none;
      position: relative;
      top: -1px;

      picture {
        height: ${({ theme }) => theme.sizes.titleBar.iconSize};
        margin-right: ${({ theme }) => theme.sizes.titleBar.iconMarginRight};
        width: ${({ theme }) => theme.sizes.titleBar.iconSize};
      }

      img,
      picture {
        pointer-events: all;
      }

      figcaption {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }

  nav {
    display: flex;

    button {
      border-left: ${styledBorder};
      box-sizing: content-box;
      display: flex;
      place-content: center;
      place-items: center;
      width: ${({ theme }) => theme.sizes.titleBar.buttonWidth};

      svg {
        fill: ${({ $foreground, theme }) => $foreground ? theme.colors.titleBar.text : theme.colors.titleBar.buttonInactive};
        margin: 0 1px 2px 0;
        width: ${({ theme }) => theme.sizes.titleBar.buttonIconWidth};
      }

      &.minimize {
        svg {
          margin-bottom: 1px;
          margin-right: 0;
        }
      }

      &:hover {
        background-color: ${({ theme }) => theme.colors.titleBar.backgroundHover};

        svg {
          fill: ${({ theme }) => theme.colors.titleBar.text};
        }

        &.close {
          background-color: ${({ theme }) => theme.colors.titleBar.closeHover};
          transition: background-color 0.25s ease;
        }
      }

      &:active {
        background-color: rgb(51, 51, 51);

        &.close {
          background-color: rgb(139, 10, 20);
        }
      }

      &:disabled {
        svg {
          fill: ${({ $foreground }) => $foreground ? "rgb(50, 50, 50)" : "rgb(60, 60, 60)"};
        }

        &:hover {
          background-color: inherit;
        }
      }
    }
  }
`;
const MAX_MOVES = 12;
const useDoubleClick = (handler, singleClick = false) => {
  const timer = useRef();
  const moveCount = useRef(0);
  const onClick = useCallback(
    (event) => {
      const runHandler = () => {
        event.stopPropagation();
        handler(event);
      };
      const clearTimer = () => {
        if (timer.current) {
          clearTimeout(timer.current);
          timer.current = void 0;
        }
      };
      const clearWhenPointerMoved = () => {
        if (moveCount.current >= MAX_MOVES) {
          clearTimer();
        }
        if (timer.current === void 0) {
          event.target.removeEventListener(
            "pointermove",
            clearWhenPointerMoved
          );
          moveCount.current = 0;
        } else {
          moveCount.current += 1;
        }
      };
      if (singleClick) {
        runHandler();
      } else if (timer.current === void 0) {
        timer.current = window.setTimeout(
          clearTimer,
          TRANSITIONS_IN_MILLISECONDS.DOUBLE_CLICK
        );
        event.target.addEventListener("pointermove", clearWhenPointerMoved, {
          passive: true
        });
      } else {
        clearTimer();
        runHandler();
      }
    },
    [handler, singleClick]
  );
  return { onClick };
};
const StyledMoveButton = styled(Button)`
  ${defaultStyles}
  &:active {
    cursor: grabbing;
  }
`;
var Popover = {};
var PopoverPortal$1 = {};
Object.defineProperty(PopoverPortal$1, "__esModule", { value: true });
PopoverPortal$1.PopoverPortal = void 0;
var react_1$5 = React__default;
var react_dom_1 = require$$2;
var PopoverPortal = function(_a) {
  var container = _a.container, element = _a.element, scoutElement = _a.scoutElement, children = _a.children;
  react_1$5.useLayoutEffect(function() {
    container.appendChild(element);
    container.appendChild(scoutElement);
    return function() {
      container.removeChild(element);
      container.removeChild(scoutElement);
    };
  }, [container, element, scoutElement]);
  return react_dom_1.createPortal(children, element);
};
PopoverPortal$1.PopoverPortal = PopoverPortal;
var util = {};
(function(exports) {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.getNudgedPopoverRect = exports.getNewPopoverRect = exports.popoverRectForPosition = exports.createContainer = exports.rectsAreEqual = exports.EMPTY_CLIENT_RECT = void 0;
  exports.EMPTY_CLIENT_RECT = {
    top: 0,
    left: 0,
    bottom: 0,
    height: 0,
    right: 0,
    width: 0
  };
  var rectsAreEqual = function(rectA, rectB) {
    return rectA === rectB || (rectA === null || rectA === void 0 ? void 0 : rectA.bottom) === (rectB === null || rectB === void 0 ? void 0 : rectB.bottom) && (rectA === null || rectA === void 0 ? void 0 : rectA.height) === (rectB === null || rectB === void 0 ? void 0 : rectB.height) && (rectA === null || rectA === void 0 ? void 0 : rectA.left) === (rectB === null || rectB === void 0 ? void 0 : rectB.left) && (rectA === null || rectA === void 0 ? void 0 : rectA.right) === (rectB === null || rectB === void 0 ? void 0 : rectB.right) && (rectA === null || rectA === void 0 ? void 0 : rectA.top) === (rectB === null || rectB === void 0 ? void 0 : rectB.top) && (rectA === null || rectA === void 0 ? void 0 : rectA.width) === (rectB === null || rectB === void 0 ? void 0 : rectB.width);
  };
  exports.rectsAreEqual = rectsAreEqual;
  var createContainer = function(containerStyle, containerClassName) {
    var container = window.document.createElement("div");
    if (containerClassName)
      container.className = containerClassName;
    Object.assign(container.style, containerStyle);
    return container;
  };
  exports.createContainer = createContainer;
  var popoverRectForPosition = function(position, childRect, popoverRect, padding, align) {
    var targetMidX = childRect.left + childRect.width / 2;
    var targetMidY = childRect.top + childRect.height / 2;
    var width = popoverRect.width, height = popoverRect.height;
    var top;
    var left;
    switch (position) {
      case "left":
        top = targetMidY - height / 2;
        left = childRect.left - padding - width;
        if (align === "start") {
          top = childRect.top;
        }
        if (align === "end") {
          top = childRect.bottom - height;
        }
        break;
      case "bottom":
        top = childRect.bottom + padding;
        left = targetMidX - width / 2;
        if (align === "start") {
          left = childRect.left;
        }
        if (align === "end") {
          left = childRect.right - width;
        }
        break;
      case "right":
        top = targetMidY - height / 2;
        left = childRect.right + padding;
        if (align === "start") {
          top = childRect.top;
        }
        if (align === "end") {
          top = childRect.bottom - height;
        }
        break;
      default:
        top = childRect.top - height - padding;
        left = targetMidX - width / 2;
        if (align === "start") {
          left = childRect.left;
        }
        if (align === "end") {
          left = childRect.right - width;
        }
        break;
    }
    return { top, left, width, height, right: left + width, bottom: top + height };
  };
  exports.popoverRectForPosition = popoverRectForPosition;
  var getNewPopoverRect = function(_a, boundaryInset) {
    var position = _a.position, align = _a.align, childRect = _a.childRect, popoverRect = _a.popoverRect, boundaryRect = _a.boundaryRect, padding = _a.padding, reposition = _a.reposition;
    var rect = exports.popoverRectForPosition(position, childRect, popoverRect, padding, align);
    var boundaryViolation = reposition && (position === "top" && rect.top < boundaryRect.top + boundaryInset || position === "left" && rect.left < boundaryRect.left + boundaryInset || position === "right" && rect.right > boundaryRect.right - boundaryInset || position === "bottom" && rect.bottom > boundaryRect.bottom - boundaryInset);
    return {
      rect,
      boundaryViolation
    };
  };
  exports.getNewPopoverRect = getNewPopoverRect;
  var getNudgedPopoverRect = function(popoverRect, boundaryRect, boundaryInset) {
    var topBoundary = boundaryRect.top + boundaryInset;
    var leftBoundary = boundaryRect.left + boundaryInset;
    var rightBoundary = boundaryRect.right - boundaryInset;
    var bottomBoundary = boundaryRect.bottom - boundaryInset;
    var top = popoverRect.top < topBoundary ? topBoundary : popoverRect.top;
    top = top + popoverRect.height > bottomBoundary ? bottomBoundary - popoverRect.height : top;
    var left = popoverRect.left < leftBoundary ? leftBoundary : popoverRect.left;
    left = left + popoverRect.width > rightBoundary ? rightBoundary - popoverRect.width : left;
    return {
      top,
      left,
      width: popoverRect.width,
      height: popoverRect.height,
      right: left + popoverRect.width,
      bottom: top + popoverRect.height
    };
  };
  exports.getNudgedPopoverRect = getNudgedPopoverRect;
})(util);
var usePopover$1 = {};
var useElementRef$1 = {};
Object.defineProperty(useElementRef$1, "__esModule", { value: true });
useElementRef$1.useElementRef = void 0;
var react_1$4 = React__default;
var util_1$1 = util;
var useElementRef = function(containerClassName, containerStyle) {
  var ref = react_1$4.useRef();
  var element = react_1$4.useMemo(function() {
    return util_1$1.createContainer(containerStyle, containerClassName);
  }, [containerClassName, containerStyle]);
  ref.current = element;
  return ref;
};
useElementRef$1.useElementRef = useElementRef;
Object.defineProperty(usePopover$1, "__esModule", { value: true });
usePopover$1.usePopover = void 0;
var react_1$3 = React__default;
var util_1 = util;
var useElementRef_1 = useElementRef$1;
var POPOVER_STYLE = {
  position: "fixed",
  overflow: "visible",
  top: "0px",
  left: "0px"
};
var SCOUT_STYLE = {
  position: "fixed",
  top: "0px",
  left: "0px",
  width: "0px",
  height: "0px",
  visibility: "hidden"
};
var usePopover = function(_a) {
  var isOpen = _a.isOpen, childRef = _a.childRef, positions = _a.positions, containerClassName = _a.containerClassName, parentElement = _a.parentElement, contentLocation = _a.contentLocation, align = _a.align, padding = _a.padding, reposition = _a.reposition, boundaryInset = _a.boundaryInset, boundaryElement = _a.boundaryElement, onPositionPopover = _a.onPositionPopover;
  var popoverRef = useElementRef_1.useElementRef(containerClassName, POPOVER_STYLE);
  var scoutRef = useElementRef_1.useElementRef("react-tiny-popover-scout", SCOUT_STYLE);
  var positionPopover = react_1$3.useCallback(function(_a2) {
    var _b, _c;
    var _d = _a2 === void 0 ? {} : _a2, _e = _d.positionIndex, positionIndex = _e === void 0 ? 0 : _e, _f = _d.parentRect, parentRect = _f === void 0 ? parentElement.getBoundingClientRect() : _f, _g = _d.childRect, childRect = _g === void 0 ? (_b = childRef === null || childRef === void 0 ? void 0 : childRef.current) === null || _b === void 0 ? void 0 : _b.getBoundingClientRect() : _g, _h = _d.scoutRect, scoutRect = _h === void 0 ? (_c = scoutRef === null || scoutRef === void 0 ? void 0 : scoutRef.current) === null || _c === void 0 ? void 0 : _c.getBoundingClientRect() : _h, _j = _d.popoverRect, popoverRect = _j === void 0 ? popoverRef.current.getBoundingClientRect() : _j, _k = _d.boundaryRect, boundaryRect = _k === void 0 ? boundaryElement === parentElement ? parentRect : boundaryElement.getBoundingClientRect() : _k;
    if (!childRect || !parentRect || !isOpen) {
      return;
    }
    if (contentLocation) {
      var _l = typeof contentLocation === "function" ? contentLocation({
        childRect,
        popoverRect,
        parentRect,
        boundaryRect,
        padding,
        nudgedTop: 0,
        nudgedLeft: 0,
        boundaryInset,
        violations: util_1.EMPTY_CLIENT_RECT,
        hasViolations: false
      }) : contentLocation, inputTop = _l.top, inputLeft = _l.left;
      var left_1 = Math.round(parentRect.left + inputLeft - scoutRect.left);
      var top_1 = Math.round(parentRect.top + inputTop - scoutRect.top);
      popoverRef.current.style.transform = "translate(" + left_1 + "px, " + top_1 + "px)";
      onPositionPopover({
        childRect,
        popoverRect,
        parentRect,
        boundaryRect,
        padding,
        nudgedTop: 0,
        nudgedLeft: 0,
        boundaryInset,
        violations: util_1.EMPTY_CLIENT_RECT,
        hasViolations: false
      });
      return;
    }
    var isExhausted = positionIndex === positions.length;
    var position = isExhausted ? positions[0] : positions[positionIndex];
    var _m = util_1.getNewPopoverRect({
      childRect,
      popoverRect,
      boundaryRect,
      position,
      align,
      padding,
      reposition
    }, boundaryInset), rect = _m.rect, boundaryViolation = _m.boundaryViolation;
    if (boundaryViolation && reposition && !isExhausted) {
      positionPopover({
        positionIndex: positionIndex + 1,
        childRect,
        popoverRect,
        parentRect,
        boundaryRect
      });
      return;
    }
    var top = rect.top, left = rect.left, width = rect.width, height = rect.height;
    var shouldNudge = reposition && !isExhausted;
    var _o = util_1.getNudgedPopoverRect(rect, boundaryRect, boundaryInset), nudgedLeft = _o.left, nudgedTop = _o.top;
    var finalTop = top;
    var finalLeft = left;
    if (shouldNudge) {
      finalTop = nudgedTop;
      finalLeft = nudgedLeft;
    }
    finalTop = Math.round(finalTop - scoutRect.top);
    finalLeft = Math.round(finalLeft - scoutRect.left);
    popoverRef.current.style.transform = "translate(" + finalLeft + "px, " + finalTop + "px)";
    var potentialViolations = {
      top: boundaryRect.top + boundaryInset - finalTop,
      left: boundaryRect.left + boundaryInset - finalLeft,
      right: finalLeft + width - boundaryRect.right + boundaryInset,
      bottom: finalTop + height - boundaryRect.bottom + boundaryInset
    };
    onPositionPopover({
      childRect,
      popoverRect: {
        top: finalTop,
        left: finalLeft,
        width,
        height,
        right: finalLeft + width,
        bottom: finalTop + height
      },
      parentRect,
      boundaryRect,
      position,
      align,
      padding,
      nudgedTop: nudgedTop - top,
      nudgedLeft: nudgedLeft - left,
      boundaryInset,
      violations: {
        top: potentialViolations.top <= 0 ? 0 : potentialViolations.top,
        left: potentialViolations.left <= 0 ? 0 : potentialViolations.left,
        right: potentialViolations.right <= 0 ? 0 : potentialViolations.right,
        bottom: potentialViolations.bottom <= 0 ? 0 : potentialViolations.bottom
      },
      hasViolations: potentialViolations.top > 0 || potentialViolations.left > 0 || potentialViolations.right > 0 || potentialViolations.bottom > 0
    });
  }, [
    parentElement,
    childRef,
    scoutRef,
    popoverRef,
    boundaryElement,
    isOpen,
    contentLocation,
    positions,
    align,
    padding,
    reposition,
    boundaryInset,
    onPositionPopover
  ]);
  return {
    positionPopover,
    popoverRef,
    scoutRef
  };
};
usePopover$1.usePopover = usePopover;
var useMemoizedArray$1 = {};
Object.defineProperty(useMemoizedArray$1, "__esModule", { value: true });
useMemoizedArray$1.useMemoizedArray = void 0;
var react_1$2 = React__default;
var useMemoizedArray = function(externalArray) {
  var prevArrayRef = react_1$2.useRef(externalArray);
  var array = react_1$2.useMemo(function() {
    if (prevArrayRef.current === externalArray)
      return prevArrayRef.current;
    if (prevArrayRef.current.length !== externalArray.length) {
      prevArrayRef.current = externalArray;
      return externalArray;
    }
    for (var i = 0; i < externalArray.length; i += 1) {
      if (externalArray[i] !== prevArrayRef.current[i]) {
        prevArrayRef.current = externalArray;
        return externalArray;
      }
    }
    return prevArrayRef.current;
  }, [externalArray]);
  return array;
};
useMemoizedArray$1.useMemoizedArray = useMemoizedArray;
var useArrowContainer$1 = {};
var __assign$1 = commonjsGlobal && commonjsGlobal.__assign || function() {
  __assign$1 = Object.assign || function(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];
      for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
        t[p] = s[p];
    }
    return t;
  };
  return __assign$1.apply(this, arguments);
};
Object.defineProperty(useArrowContainer$1, "__esModule", { value: true });
useArrowContainer$1.useArrowContainer = void 0;
var react_1$1 = React__default;
var useArrowContainer = function(_a) {
  var childRect = _a.childRect, popoverRect = _a.popoverRect, position = _a.position, arrowSize = _a.arrowSize, arrowColor = _a.arrowColor;
  var arrowContainerStyle = react_1$1.useMemo(function() {
    return {
      padding: arrowSize
    };
  }, [arrowSize]);
  var arrowStyle = react_1$1.useMemo(function() {
    return __assign$1({ position: "absolute" }, function() {
      var arrowWidth = arrowSize * 2;
      var top = childRect.top - popoverRect.top + childRect.height / 2 - arrowWidth / 2;
      var left = childRect.left - popoverRect.left + childRect.width / 2 - arrowWidth / 2;
      var lowerBound = arrowSize;
      var leftUpperBound = popoverRect.width - arrowSize;
      var topUpperBound = popoverRect.height - arrowSize;
      left = left < lowerBound ? lowerBound : left;
      left = left + arrowWidth > leftUpperBound ? leftUpperBound - arrowWidth : left;
      top = top < lowerBound ? lowerBound : top;
      top = top + arrowWidth > topUpperBound ? topUpperBound - arrowWidth : top;
      top = Number.isNaN(top) ? 0 : top;
      left = Number.isNaN(left) ? 0 : left;
      switch (position) {
        case "right":
          return {
            borderTop: arrowSize + "px solid transparent",
            borderBottom: arrowSize + "px solid transparent",
            borderRight: arrowSize + "px solid " + arrowColor,
            left: 0,
            top
          };
        case "left":
          return {
            borderTop: arrowSize + "px solid transparent",
            borderBottom: arrowSize + "px solid transparent",
            borderLeft: arrowSize + "px solid " + arrowColor,
            right: 0,
            top
          };
        case "bottom":
          return {
            borderLeft: arrowSize + "px solid transparent",
            borderRight: arrowSize + "px solid transparent",
            borderBottom: arrowSize + "px solid " + arrowColor,
            top: 0,
            left
          };
        case "top":
          return {
            borderLeft: arrowSize + "px solid transparent",
            borderRight: arrowSize + "px solid transparent",
            borderTop: arrowSize + "px solid " + arrowColor,
            bottom: 0,
            left
          };
        default:
          return {
            display: "hidden"
          };
      }
    }());
  }, [
    arrowColor,
    arrowSize,
    childRect.height,
    childRect.left,
    childRect.top,
    childRect.width,
    popoverRect.height,
    popoverRect.left,
    popoverRect.top,
    popoverRect.width,
    position
  ]);
  return {
    arrowContainerStyle,
    arrowStyle
  };
};
useArrowContainer$1.useArrowContainer = useArrowContainer;
var ArrowContainer$1 = {};
var __assign = commonjsGlobal && commonjsGlobal.__assign || function() {
  __assign = Object.assign || function(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];
      for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
        t[p] = s[p];
    }
    return t;
  };
  return __assign.apply(this, arguments);
};
Object.defineProperty(ArrowContainer$1, "__esModule", { value: true });
ArrowContainer$1.ArrowContainer = void 0;
var jsx_runtime_1 = require$$0;
var react_1 = React__default;
var useArrowContainer_1 = useArrowContainer$1;
var ArrowContainer = function(_a) {
  var childRect = _a.childRect, popoverRect = _a.popoverRect, position = _a.position, arrowColor = _a.arrowColor, arrowSize = _a.arrowSize, arrowClassName = _a.arrowClassName, externalArrowStyle = _a.arrowStyle, className = _a.className, children = _a.children, externalArrowContainerStyle = _a.style;
  var _b = useArrowContainer_1.useArrowContainer({
    childRect,
    popoverRect,
    position,
    arrowColor,
    arrowSize
  }), arrowContainerStyle = _b.arrowContainerStyle, arrowStyle = _b.arrowStyle;
  var mergedContainerStyle = react_1.useMemo(function() {
    return __assign(__assign({}, arrowContainerStyle), externalArrowContainerStyle);
  }, [arrowContainerStyle, externalArrowContainerStyle]);
  var mergedArrowStyle = react_1.useMemo(function() {
    return __assign(__assign({}, arrowStyle), externalArrowStyle);
  }, [arrowStyle, externalArrowStyle]);
  return jsx_runtime_1.jsxs("div", __assign({ className, style: mergedContainerStyle }, { children: [jsx_runtime_1.jsx("div", { style: mergedArrowStyle, className: arrowClassName }, void 0), children] }), void 0);
};
ArrowContainer$1.ArrowContainer = ArrowContainer;
(function(exports) {
  var __assign2 = commonjsGlobal && commonjsGlobal.__assign || function() {
    __assign2 = Object.assign || function(t) {
      for (var s, i = 1, n = arguments.length; i < n; i++) {
        s = arguments[i];
        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
          t[p] = s[p];
      }
      return t;
    };
    return __assign2.apply(this, arguments);
  };
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.Popover = exports.usePopover = exports.ArrowContainer = exports.useArrowContainer = void 0;
  var jsx_runtime_12 = require$$0;
  var react_12 = React__default;
  var PopoverPortal_1 = PopoverPortal$1;
  var util_12 = util;
  var usePopover_1 = usePopover$1;
  Object.defineProperty(exports, "usePopover", { enumerable: true, get: function() {
    return usePopover_1.usePopover;
  } });
  var useMemoizedArray_1 = useMemoizedArray$1;
  var useArrowContainer_12 = useArrowContainer$1;
  Object.defineProperty(exports, "useArrowContainer", { enumerable: true, get: function() {
    return useArrowContainer_12.useArrowContainer;
  } });
  var ArrowContainer_1 = ArrowContainer$1;
  Object.defineProperty(exports, "ArrowContainer", { enumerable: true, get: function() {
    return ArrowContainer_1.ArrowContainer;
  } });
  var DEFAULT_POSITIONS = ["top", "left", "right", "bottom"];
  var PopoverInternal = react_12.forwardRef(function(_a, externalRef) {
    var isOpen = _a.isOpen, children = _a.children, content = _a.content, _b = _a.positions, externalPositions = _b === void 0 ? DEFAULT_POSITIONS : _b, _c = _a.align, align = _c === void 0 ? "center" : _c, _d = _a.padding, padding = _d === void 0 ? 0 : _d, _e = _a.reposition, reposition = _e === void 0 ? true : _e, _f = _a.parentElement, parentElement = _f === void 0 ? window.document.body : _f, _g = _a.boundaryElement, boundaryElement = _g === void 0 ? parentElement : _g, _h = _a.containerClassName, containerClassName = _h === void 0 ? "react-tiny-popover-container" : _h, containerStyle = _a.containerStyle, contentLocation = _a.contentLocation, _j = _a.boundaryInset, boundaryInset = _j === void 0 ? 0 : _j, onClickOutside = _a.onClickOutside, _k = _a.clickOutsideCapture, clickOutsideCapture = _k === void 0 ? false : _k;
    var positions = useMemoizedArray_1.useMemoizedArray(externalPositions);
    var prevIsOpen = react_12.useRef(false);
    var prevPositions = react_12.useRef();
    var prevContentLocation = react_12.useRef();
    var prevReposition = react_12.useRef(reposition);
    var childRef = react_12.useRef();
    var _l = react_12.useState({
      align,
      nudgedLeft: 0,
      nudgedTop: 0,
      position: positions[0],
      padding,
      childRect: util_12.EMPTY_CLIENT_RECT,
      popoverRect: util_12.EMPTY_CLIENT_RECT,
      parentRect: util_12.EMPTY_CLIENT_RECT,
      boundaryRect: util_12.EMPTY_CLIENT_RECT,
      boundaryInset,
      violations: util_12.EMPTY_CLIENT_RECT,
      hasViolations: false
    }), popoverState = _l[0], setPopoverState = _l[1];
    var onPositionPopover = react_12.useCallback(function(popoverState2) {
      return setPopoverState(popoverState2);
    }, []);
    var _m = usePopover_1.usePopover({
      isOpen,
      childRef,
      containerClassName,
      parentElement,
      boundaryElement,
      contentLocation,
      positions,
      align,
      padding,
      boundaryInset,
      reposition,
      onPositionPopover
    }), positionPopover = _m.positionPopover, popoverRef = _m.popoverRef, scoutRef = _m.scoutRef;
    react_12.useLayoutEffect(function() {
      var shouldUpdate = true;
      var updatePopover = function() {
        var _a2, _b2;
        if (isOpen && shouldUpdate) {
          var childRect = (_a2 = childRef === null || childRef === void 0 ? void 0 : childRef.current) === null || _a2 === void 0 ? void 0 : _a2.getBoundingClientRect();
          var popoverRect = (_b2 = popoverRef === null || popoverRef === void 0 ? void 0 : popoverRef.current) === null || _b2 === void 0 ? void 0 : _b2.getBoundingClientRect();
          if (childRect != null && popoverRect != null && (!util_12.rectsAreEqual(childRect, {
            top: popoverState.childRect.top,
            left: popoverState.childRect.left,
            width: popoverState.childRect.width,
            height: popoverState.childRect.height,
            bottom: popoverState.childRect.top + popoverState.childRect.height,
            right: popoverState.childRect.left + popoverState.childRect.width
          }) || popoverRect.width !== popoverState.popoverRect.width || popoverRect.height !== popoverState.popoverRect.height || popoverState.padding !== padding || popoverState.align !== align || positions !== prevPositions.current || contentLocation !== prevContentLocation.current || reposition !== prevReposition.current)) {
            positionPopover();
          }
          if (positions !== prevPositions.current) {
            prevPositions.current = positions;
          }
          if (contentLocation !== prevContentLocation.current) {
            prevContentLocation.current = contentLocation;
          }
          if (reposition !== prevReposition.current) {
            prevReposition.current = reposition;
          }
          if (shouldUpdate) {
            window.requestAnimationFrame(updatePopover);
          }
        }
        prevIsOpen.current = isOpen;
      };
      window.requestAnimationFrame(updatePopover);
      return function() {
        shouldUpdate = false;
      };
    }, [
      align,
      contentLocation,
      isOpen,
      padding,
      popoverRef,
      popoverState.align,
      popoverState.childRect.height,
      popoverState.childRect.left,
      popoverState.childRect.top,
      popoverState.childRect.width,
      popoverState.padding,
      popoverState.popoverRect.height,
      popoverState.popoverRect.width,
      positionPopover,
      positions,
      reposition
    ]);
    react_12.useEffect(function() {
      var popoverElement = popoverRef.current;
      Object.assign(popoverElement.style, containerStyle);
      return function() {
        Object.keys(containerStyle !== null && containerStyle !== void 0 ? containerStyle : {}).forEach(function(key) {
          return delete popoverElement.style[key];
        });
      };
    }, [containerStyle, isOpen, popoverRef]);
    var handleOnClickOutside = react_12.useCallback(function(e) {
      var _a2, _b2;
      if (isOpen && !((_a2 = popoverRef.current) === null || _a2 === void 0 ? void 0 : _a2.contains(e.target)) && !((_b2 = childRef.current) === null || _b2 === void 0 ? void 0 : _b2.contains(e.target))) {
        onClickOutside === null || onClickOutside === void 0 ? void 0 : onClickOutside(e);
      }
    }, [isOpen, onClickOutside, popoverRef]);
    var handleWindowResize = react_12.useCallback(function() {
      if (childRef.current) {
        window.requestAnimationFrame(function() {
          return positionPopover();
        });
      }
    }, [positionPopover]);
    react_12.useEffect(function() {
      var body = parentElement.ownerDocument.body;
      body.addEventListener("click", handleOnClickOutside, clickOutsideCapture);
      body.addEventListener("contextmenu", handleOnClickOutside, clickOutsideCapture);
      body.addEventListener("resize", handleWindowResize);
      return function() {
        body.removeEventListener("click", handleOnClickOutside, clickOutsideCapture);
        body.removeEventListener("contextmenu", handleOnClickOutside, clickOutsideCapture);
        body.removeEventListener("resize", handleWindowResize);
      };
    }, [clickOutsideCapture, handleOnClickOutside, handleWindowResize, parentElement]);
    var handleRef = react_12.useCallback(function(node) {
      childRef.current = node;
      if (externalRef != null) {
        if (typeof externalRef === "object") {
          externalRef.current = node;
        } else if (typeof externalRef === "function") {
          externalRef(node);
        }
      }
    }, [externalRef]);
    var renderChild = function() {
      return react_12.cloneElement(children, {
        ref: handleRef
      });
    };
    var renderPopover = function() {
      if (!isOpen)
        return null;
      return jsx_runtime_12.jsx(PopoverPortal_1.PopoverPortal, __assign2({ element: popoverRef.current, scoutElement: scoutRef.current, container: parentElement }, { children: typeof content === "function" ? content(popoverState) : content }), void 0);
    };
    return jsx_runtime_12.jsxs(jsx_runtime_12.Fragment, { children: [renderChild(), renderPopover()] }, void 0);
  });
  exports.Popover = react_12.forwardRef(function(props, ref) {
    if (typeof window === "undefined")
      return props.children;
    return jsx_runtime_12.jsx(PopoverInternal, __assign2({}, props, { ref }), void 0);
  });
})(Popover);
const fadein = keyframes`
  from {
    transform-origin: top;
    transform: scale(0.8);
    opacity: 0;
  }
  to {
    transform-origin: top;
    transform: scale(1);
    opacity: 1;
  }
`;
const StyledSnapOptions = styled.div`
  box-sizing: border-box;
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  grid-template-rows: repeat(3, minmax(0, 1fr));
  grid-column-gap: 8px;
  grid-row-gap: 8px;
  background: #222;
  border: solid 1px rgba(150, 150, 150, 0.2);
  border-radius: 6px;
  transform-origin: center;
  animation: ${fadein} 0.3s ease-in-out;
  min-width: 150px;
  min-height: 100px;
`;
const StyledSnapper = styled.div`
  box-sizing: border-box;
  transition: all ease-in-out 100ms;
  background: #4e4e4e;
  border: solid 1px #777;
  &:hover {
    background: #4cc2ff;
    border: solid 1px #4cc2ff;
  }
`;
const StyledSnapLayout = styled.div`
display: grid;
grid-column-gap: 3px;
grid-row-gap: 3px;

&:nth-child(1) {
  grid-template-columns: auto auto;
}

&:nth-child(2) {
  grid-template-columns: auto auto auto;

  .snapper:first-child {
    grid-column-end: span 2;
  }
}

&:nth-child(3) {
  grid-template-columns: auto auto auto;
}

&:nth-child(4) {
  grid-template-columns: auto auto;
  grid-template-rows: auto auto;

  ${StyledSnapper}:first-child {
    grid-row: 1 / span 2;
  }
}

&:nth-child(5) {
  grid-template-columns: auto auto;
  grid-template-rows: auto auto;
  grid-column-gap: 4px;
}

&:nth-child(6) {
  grid-template-columns: auto auto auto auto auto auto auto;

  ${StyledSnapper} {
    grid-column-end: span 2;
  }

  ${StyledSnapper}:nth-child(2) {
    grid-column: 3 / span 3;
  }
}
}
`;
const SnapOptions = ({ id, onFocus, onUnfocus }) => {
  const {
    windows: { [id]: currentWindow },
    setSnap
  } = useContext();
  return /* @__PURE__ */ jsx(
    StyledSnapOptions,
    {
      onMouseEnter: onFocus,
      onMouseLeave: onUnfocus,
      onBlurCapture: onUnfocus,
      children: /* @__PURE__ */ jsxs(StyledSnapLayout, { children: [
        /* @__PURE__ */ jsx(
          StyledSnapper,
          {
            onClick: () => {
              setSnap(id, {
                type: "twoColumns",
                index: 0,
                widthPercent: 50
              });
            }
          }
        ),
        /* @__PURE__ */ jsx(
          StyledSnapper,
          {
            onClick: () => {
              setSnap(id, {
                type: "twoColumns",
                index: 1,
                widthPercent: 50
              });
            }
          }
        )
      ] })
    }
  );
};
const SnapOptions$1 = memo(SnapOptions);
const Titlebar = ({ id }) => {
  const {
    windows: { [id]: currentWindow }
  } = useContext();
  const {
    allowResizing = true,
    closing,
    componentWindow,
    hideMaximizeButton,
    hideMinimizeButton,
    hideTitlebarIcon,
    icon,
    titlebarIcon,
    title,
    renderTitle,
    maximized
  } = currentWindow || {};
  const { foregroundId } = useContext$2();
  const isForeground = id === foregroundId;
  const { onClose, onMaximize, onMinimize } = useWindowActions(id);
  const onClickClose = useDoubleClick(onClose);
  const onClickMaximize = useDoubleClick(onMaximize);
  const { menu, setMenu } = useContext$6();
  const titlebarContextMenu = useTitlebarContextMenu(id);
  const touchStartTimeRef = useRef(0);
  const touchStartPositionRef = useRef();
  const touchesRef = useRef();
  const [showSnapOptions, setShowSnapOptions] = useState(0);
  const onTouchEnd = useCallback(
    (event) => {
      const { x, y } = (componentWindow == null ? void 0 : componentWindow.getBoundingClientRect()) || {};
      if (Date.now() - touchStartTimeRef.current >= LONG_PRESS_DELAY_MS && touchStartPositionRef.current && touchStartPositionRef.current.x === x && touchStartPositionRef.current.y === y) {
        titlebarContextMenu.onContextMenuCapture(
          Object.assign(event, {
            touches: touchesRef.current
          })
        );
      }
    },
    [componentWindow, titlebarContextMenu]
  );
  const onTouchStart = useCallback(
    ({ touches }) => {
      if (componentWindow) {
        componentWindow.blur();
        componentWindow.focus(PREVENT_SCROLL);
        touchStartTimeRef.current = Date.now();
        touchStartPositionRef.current = componentWindow.getBoundingClientRect();
        touchesRef.current = touches;
      }
    },
    [componentWindow]
  );
  const renderIcon = useMemo(() => {
    if (!icon && !titlebarIcon) return false;
    const actualIcon = titlebarIcon || icon;
    if (typeof actualIcon === "string") {
      return /* @__PURE__ */ jsx(Icon, { alt: title, imgSize: 16, src: actualIcon, ...onClickClose });
    } else if (React__default.isValidElement(actualIcon)) {
      return React__default.cloneElement(actualIcon, { ...onClickClose });
    } else if (typeof actualIcon === "function") {
      const IconComponent = actualIcon;
      return /* @__PURE__ */ jsx(IconComponent, { ...onClickClose });
    }
  }, [icon, titlebarIcon, onClickClose, title]);
  useCallback(() => {
    setShowSnapOptions((prevOpt) => Math.max(prevOpt - 1, 0));
  }, [setShowSnapOptions]);
  useCallback(() => {
    setShowSnapOptions((prevOpt) => {
      const newOpt = prevOpt + 1;
      if (newOpt > 3) {
        return 1;
      }
      return newOpt;
    });
  }, [setShowSnapOptions]);
  return /* @__PURE__ */ jsxs(
    StyledTitlebar,
    {
      $foreground: isForeground,
      className: rndDefaults.dragHandleClassName,
      onDragOver: haltEvent,
      onDrop: haltEvent,
      ...titlebarContextMenu,
      children: [
        /* @__PURE__ */ jsx(
          StyledMoveButton,
          {
            ...!hideMaximizeButton && allowResizing && !closing ? onClickMaximize : {},
            onMouseDownCapture: ({ button }) => {
              if (button === 0 && Object.keys(menu).length > 0) {
                setMenu(/* @__PURE__ */ Object.create(null));
              }
            },
            onMouseUpCapture: () => {
              if (componentWindow && componentWindow !== document.activeElement) {
                componentWindow.focus(PREVENT_SCROLL);
              }
            },
            onTouchEndCapture: onTouchEnd,
            onTouchStartCapture: onTouchStart,
            children: /* @__PURE__ */ jsxs("figure", { children: [
              !hideTitlebarIcon && renderIcon !== false && /* @__PURE__ */ jsx("picture", { children: renderIcon }),
              /* @__PURE__ */ jsx("figcaption", { children: renderTitle ? renderTitle : title })
            ] })
          }
        ),
        /* @__PURE__ */ jsxs("nav", { className: "cancel", children: [
          !hideMinimizeButton && /* @__PURE__ */ jsx(
            Button,
            {
              className: "minimize",
              onClick: () => onMinimize(),
              ...label("Minimize"),
              children: /* @__PURE__ */ jsx(MinimizeIcon, {})
            }
          ),
          !hideMaximizeButton && /* @__PURE__ */ jsx(
            Popover.Popover,
            {
              isOpen: showSnapOptions > 0,
              containerStyle: {
                zIndex: "5000"
              },
              positions: ["bottom", "top", "left", "right"],
              content: /* @__PURE__ */ jsx(
                SnapOptions$1,
                {
                  id,
                  onFocus: () => setShowSnapOptions(2),
                  onUnfocus: () => setTimeout(() => setShowSnapOptions(0), 200)
                }
              ),
              children: /* @__PURE__ */ jsx(
                Button,
                {
                  className: "maximize",
                  disabled: !allowResizing,
                  onClick: onMaximize,
                  ...label(maximized ? "Restore Down" : "Maximize"),
                  children: maximized ? /* @__PURE__ */ jsx(MaximizedIcon, {}) : /* @__PURE__ */ jsx(MaximizeIcon, {})
                }
              )
            }
          ),
          /* @__PURE__ */ jsx(
            Button,
            {
              $short: hideMaximizeButton && hideMinimizeButton,
              className: "close",
              onClick: onClose,
              ...label("Close"),
              children: /* @__PURE__ */ jsx(CloseIcon, {})
            }
          )
        ] })
      ]
    }
  );
};
const Titlebar$1 = memo(Titlebar);
const useFocusable = (id, callbackEvents, focusElement) => {
  const {
    foregroundId,
    previewID,
    prependToStack,
    setForegroundId,
    stackOrder = []
  } = useContext$2();
  const { events: RD_Events } = useContext$1();
  const {
    windows: { [id]: currentRDWindow }
  } = useContext();
  const [underPreview, setUnderPreview] = useState(false);
  const { Events: RD_WindowEvents } = useContext$5();
  const {
    closing,
    componentWindow = focusElement,
    minimized,
    taskbarEntry
  } = currentRDWindow || {};
  const zIndex = useMemo(
    () => previewID !== false && previewID == id ? 1e3 : underPreview && minimized ? 1 : stackOrder.length + (minimized ? 1 : -stackOrder.indexOf(id)) + 1,
    [previewID, id, underPreview, minimized, stackOrder]
  );
  useEffect(() => {
    let timeoutId;
    if (!previewID) {
      timeoutId = setTimeout(() => {
        setUnderPreview(false);
      }, TRANSITIONS_IN_MILLISECONDS.WINDOW + 100);
    } else {
      setUnderPreview(true);
    }
    return () => {
      if (timeoutId) {
        clearTimeout(timeoutId);
      }
    };
  }, [previewID]);
  const onBlurCapture = useCallback(
    (event) => {
      var _a;
      const { relatedTarget } = event;
      const focusedElement = relatedTarget;
      const focusedOnTaskbarEntry = relatedTarget === taskbarEntry;
      const focusedOnTaskbarPeek = focusedElement && ((_a = taskbarEntry == null ? void 0 : taskbarEntry.previousSibling) == null ? void 0 : _a.contains(focusedElement));
      const focusedOnInsideWindow = focusedElement && (componentWindow == null ? void 0 : componentWindow.contains(focusedElement));
      setForegroundId((currentForegroundId) => {
        if (currentForegroundId === id && !focusedOnTaskbarEntry && !focusedOnInsideWindow) {
          if (focusedOnTaskbarPeek) {
            componentWindow == null ? void 0 : componentWindow.focus(PREVENT_SCROLL);
          } else {
            RD_WindowEvents.emit("event:window/unfocus", id, event);
            RD_Events.emit(
              ["event:windows/unfocus", `event:windows/unfocus:${id}`],
              id,
              event
            );
          }
          return focusedOnTaskbarPeek ? currentForegroundId : "";
        }
        return currentForegroundId;
      });
    },
    [
      callbackEvents,
      componentWindow,
      id,
      setForegroundId,
      taskbarEntry,
      RD_Events,
      RD_WindowEvents
    ]
  );
  const moveToFront = useCallback(
    (event) => {
      const { relatedTarget } = event || {};
      if (componentWindow == null ? void 0 : componentWindow.contains(document.activeElement)) {
        prependToStack(id);
        setForegroundId(id);
      } else if (!relatedTarget || document.activeElement === taskbarEntry) {
        componentWindow == null ? void 0 : componentWindow.focus(PREVENT_SCROLL);
      }
    },
    [
      callbackEvents,
      componentWindow,
      id,
      prependToStack,
      setForegroundId,
      taskbarEntry
    ]
  );
  useLayoutEffect(() => {
    if (id === foregroundId) {
      RD_WindowEvents.emit("event:window/focus", id);
      RD_Events.emit(["event:windows/focus", `event:windows/focus:${id}`], id);
    }
  }, [foregroundId, id, RD_Events, RD_WindowEvents]);
  useLayoutEffect(() => {
    if (id === foregroundId) moveToFront();
  }, [foregroundId, id, moveToFront]);
  useLayoutEffect(() => {
    if (componentWindow && !closing && !minimized) {
      setForegroundId(id);
    }
  }, [closing, componentWindow, id, minimized, setForegroundId]);
  useLayoutEffect(() => {
    prependToStack(id);
    setForegroundId(id);
  }, [id, prependToStack, setForegroundId]);
  return useMemo(
    () => ({
      onBlurCapture,
      onClickCapture: moveToFront,
      onFocusCapture: moveToFront,
      zIndex,
      ...FOCUSABLE_ELEMENT
    }),
    [moveToFront, onBlurCapture, zIndex]
  );
};
const active = {
  height: "inherit",
  opacity: 1,
  scale: 1,
  width: "inherit"
};
const preview = {
  opacity: 0.15,
  scale: 0.98
};
const preview_hover = {
  opacity: 1,
  scale: 1,
  boxShadow: "rgb(255, 255, 255) 0px 0px 20px inset"
};
const exit = {
  opacity: 0,
  scale: 0.95
};
const initial = {
  ...exit,
  height: "inherit",
  width: "inherit"
};
const fullScaleInitial = {
  ...initial,
  scale: 1
};
const baseMaximize = {
  opacity: 1,
  scale: 1
};
const baseMinimize = {
  opacity: 0,
  scale: 0.3
};
const useWindowTransitions = (id, noInitialScaling = false) => {
  const { disableAnimations } = useContext$4();
  const { windows: { [id]: curWindow } = {} } = useContext();
  const { closing, componentWindow, maximized, minimized, taskbarEntry, snap: snap2 } = curWindow || {};
  const { WindowsViewArea, WindowsViewAreaSize } = useContext$3();
  const { Events: RD_WindowEvents } = useContext$5();
  const { previewID } = useContext$2();
  const [maximize, setMaximize] = useState(
    /* @__PURE__ */ Object.create(null)
  );
  const [minimize, setMinimize] = useState(
    /* @__PURE__ */ Object.create(null)
  );
  useState(
    Object.create(active)
  );
  useState({ x: 0, y: 0 });
  const [isVisible, setIsVisible] = useState(true);
  const { events: RD_Events } = useContext$1();
  const visibilityTimeoutRef = useRef(null);
  const getBasePos = useCallback(() => {
    if (!componentWindow || closing) return { x: 0, y: 0 };
    const { x: windowX = 0, y: windowY = 0 } = componentWindow.getBoundingClientRect();
    const { x: viewX = 0, y: viewY = 0 } = WindowsViewArea ? WindowsViewArea.getBoundingClientRect() : { x: 0, y: 0 };
    return {
      x: -windowX + viewX,
      y: -windowY + viewY
    };
  }, [WindowsViewArea, closing, componentWindow]);
  useLayoutEffect(() => {
    if (!componentWindow || closing) return;
    const basePos = getBasePos();
    setMaximize({
      ...baseMaximize,
      ...WindowsViewArea ? getElementSize(WindowsViewArea) : WindowsViewAreaSize,
      x: basePos.x,
      y: basePos.y
    });
  }, [closing, getBasePos, componentWindow, maximized, WindowsViewArea]);
  useLayoutEffect(() => {
    if (!taskbarEntry || !componentWindow || closing) return;
    const {
      height: taskbarHeight = 0,
      width: taskbarWidth = 0,
      x: taskbarX = 0,
      y: taskbarY = 0
    } = taskbarEntry.getBoundingClientRect();
    const {
      height: windowHeight = 0,
      width: windowWidth = 0,
      x: windowX = 0,
      y: windowY = 0
    } = componentWindow.getBoundingClientRect();
    const x = Math.round(
      taskbarX - windowX - windowWidth / 2 + taskbarWidth / 2
    );
    const y = Math.round(
      taskbarY - windowY - windowHeight / 2 + taskbarHeight / 2
    );
    if (!(x === 0 && y === 0)) {
      setMinimize({ ...baseMinimize, x, y });
    }
  }, [closing, componentWindow, minimized, taskbarEntry]);
  useEffect(() => {
    const monitorViewportResize = (newWindowsViewSize) => {
      if (maximized) {
        setMaximize((currentMaximize) => {
          return {
            ...currentMaximize,
            ...newWindowsViewSize
          };
        });
      }
    };
    const registeredEvents = [];
    if (maximized) {
      registeredEvents.push(
        RD_Events.on("event:elements/resize/windowsview", monitorViewportResize)
      );
    }
    return () => {
      registeredEvents.forEach(RD_Events.removeListenerByID);
    };
  }, [id, maximized, WindowsViewArea, RD_Events, RD_WindowEvents]);
  useEffect(() => {
    if (visibilityTimeoutRef.current) {
      clearTimeout(visibilityTimeoutRef.current);
    }
    if (minimized) {
      visibilityTimeoutRef.current = setTimeout(() => {
        setIsVisible(false);
      }, TRANSITIONS_IN_MILLISECONDS.WINDOW + 150);
    } else {
      setIsVisible(true);
    }
    return () => {
      if (visibilityTimeoutRef.current) {
        clearTimeout(visibilityTimeoutRef.current);
      }
    };
  }, [minimized]);
  const isPreview = previewID !== false;
  return {
    animate: (() => {
      if (!disableAnimations) {
        if (!closing && maximized && isPreview && previewID === id)
          return "phover_maximize";
        if (isPreview && previewID === id) return "preview_hover";
        if (minimized) return "minimize";
        if (!closing && maximized && isPreview && previewID !== id)
          return "preview_maximize";
        if (!closing && maximized) return "maximize";
      }
      if (isPreview && previewID !== id && !minimized) return "preview";
      return "active";
    })(),
    exit: "exit",
    initial: "initial",
    transition: {
      duration: isPreview ? TRANSITIONS_IN_SECONDS.WINDOW / 2 : TRANSITIONS_IN_SECONDS.WINDOW,
      ease: [0.05, 0.1, 0.7, 0.3]
    },
    variants: {
      active,
      exit,
      initial: noInitialScaling ? fullScaleInitial : initial,
      preview,
      preview_hover,
      maximize,
      preview_maximize: {
        ...maximize,
        ...preview
      },
      phover_maximize: {
        ...preview_hover,
        ...maximize
      },
      minimize
      // snap: snapVar,
    }
    // style: { display: isVisible ? "block" : "none" }, // Conditionally render based on visibility
  };
};
const UP = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAKElEQVR42mOgMRgF6enp/ynSDMMUaEZgsjST5RJsikk2AKc4bcAoAADI7y5FsB5j/QAAAABJRU5ErkJggg==";
const DOWN = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAK0lEQVR42mOgARgF6enp/0kRZ8KvGMEnyQUwjMwn0xBMzWQZQlmA0h6MAgAuqCnfdOk/ZQAAAABJRU5ErkJggg==";
const LEFT = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAG0lEQVR42mPAD0ZBenr6fxge4ppHuiGEwSgAAGJiLkXUVlYDAAAAAElFTkSuQmCC";
const RIGHT = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAG0lEQVR42mPADkZBenr6fxgeZoYMV82Ug1EAAPiTLkWjutmQAAAAAElFTkSuQmCC";
const colorScheme = {
  dark: {
    active: "rgb(166, 166, 166)",
    blendMode: "color-burn",
    buttonHover: "rgb(55, 55, 55)",
    thumb: "rgb(77, 77, 77)",
    thumbHover: "rgb(122, 122, 122)",
    track: "rgb(23, 23, 23)"
  },
  light: {
    active: "rgb(96, 96, 96)",
    blendMode: "color-dodge",
    buttonHover: "rgb(218, 218, 218)",
    thumb: "rgb(205, 205, 205)",
    thumbHover: "rgb(166, 166, 166)",
    track: "rgb(240, 240, 240)"
  }
};
const ScrollBars = ({
  size = DEFAULT_SCROLLBAR_WIDTH,
  verticalX = 0,
  verticalY = 0,
  scheme = "dark",
  scrollbarGutter = true
} = {}) => css`
  overflow: auto;
  ${scrollbarGutter && "scrollbar-gutter: stable;"}

  @supports not selector(::-webkit-scrollbar) {
    scrollbar-color: ${colorScheme[scheme].thumb} ${colorScheme[scheme].track};
  }

  &::-webkit-scrollbar {
    height: ${size}px;
    width: ${size}px;
  }

  &::-webkit-scrollbar-corner,
  &::-webkit-scrollbar-track {
    background-color: ${colorScheme[scheme].track};
  }

  &::-webkit-scrollbar-thumb {
    background-clip: padding-box;
    background-color: ${colorScheme[scheme].thumb};
  }

  &::-webkit-scrollbar-thumb:vertical {
    background-clip: padding-box;
    background-color: ${colorScheme[scheme].thumb};
    border-left: 1px solid transparent;
    border-right: 1px solid transparent;
  }

  &::-webkit-scrollbar-thumb:horizontal {
    border-bottom: 1px solid transparent;
    border-top: 1px solid transparent;
  }

  &::-webkit-scrollbar-thumb:hover {
    background-color: ${colorScheme[scheme].thumbHover};
  }

  &::-webkit-scrollbar-thumb:active {
    background-color: ${colorScheme[scheme].active};
  }

  &::-webkit-scrollbar-button:single-button {
    background-clip: padding-box;
    background-color: ${colorScheme[scheme].track};
    background-position: center 4px;
    background-repeat: no-repeat;
    background-size: 10px;
    border: 1px solid ${colorScheme[scheme].track};
    display: block;
    height: ${size ? `${size}px` : "initial"};

    &:hover {
      background-color: ${colorScheme[scheme].buttonHover};
    }

    &:active {
      background-color: ${colorScheme[scheme].active};
    }
  }

  &::-webkit-scrollbar-button:single-button:vertical:decrement,
  &::-webkit-scrollbar-button:single-button:vertical:increment {
    background-position-x: ${verticalX === 0 ? "center" : `${verticalX}px`};
    background-position-y: ${verticalY === 0 ? "center" : `${verticalY}px`};
    background-size: 16px;
    border-bottom: 0;
    border-top: 0;
    image-rendering: pixelated;
  }

  &::-webkit-scrollbar-button:single-button:vertical:decrement {
    background-image: url(${UP});
  }

  &::-webkit-scrollbar-button:single-button:vertical:increment {
    background-image: url(${DOWN});
  }

  &::-webkit-scrollbar-button:single-button:horizontal:decrement,
  &::-webkit-scrollbar-button:single-button:horizontal:increment {
    background-position: center;
    background-size: 16px;
    border-left: 0;
    border-right: 0;
    image-rendering: pixelated;
  }

  &::-webkit-scrollbar-button:single-button:horizontal:decrement {
    background-image: url(${LEFT});
  }

  &::-webkit-scrollbar-button:single-button:horizontal:increment {
    background-image: url(${RIGHT});
  }

  &::-webkit-scrollbar-button:single-button:vertical:decrement:active,
  &::-webkit-scrollbar-button:single-button:vertical:increment:active,
  &::-webkit-scrollbar-button:single-button:horizontal:decrement:active,
  &::-webkit-scrollbar-button:single-button:horizontal:increment:active {
    background-blend-mode: ${colorScheme[scheme].blendMode};
  }
`;
const StyledPeekViewport = styled.div`
  ${defaultStyles}
  background-color: inherit;
  height: inherit;
  width: inherit;
`;
const StyledWindowWrapper = styled.div`
  ${defaultStyles}
  display: flex;
  flex-direction: column;
  position: relative;
  width: 100%;
  height: 100%;
  justify-content: center;
`;
const StyledWindowContent = styled.div`
  ${ScrollBars({ scrollbarGutter: false })}
  flex: 1;
  height: 100%;
  width: 100%;
  position: relative;
  display: flex;
  overflow: auto;
`;
const Window = ({ children, id }) => {
  const {
    linkElement,
    windows: { [id]: currentWindow }
  } = useContext();
  const {
    backgroundColor,
    Component,
    hideTitlebar,
    peekElement,
    maximized,
    snap: snap2
  } = currentWindow || {};
  const { disableAnimations } = useContext$4();
  const { foregroundId } = useContext$2();
  const isForeground = id === foregroundId;
  const { zIndex, ...focusableProps } = useFocusable(id);
  const { previewID } = useContext$2();
  const windowTransitions = useWindowTransitions(id, maximized);
  const linkViewportEntry = useCallback(
    (viewportEntry) => {
      if (Component && !peekElement && viewportEntry) {
        linkElement(id, "peekElement", viewportEntry);
      }
    },
    [Component, id, linkElement, peekElement]
  );
  const isSnap = snap2 && typeof snap2 === "object";
  const isPreview = previewID !== false;
  const isPreviewAndNotOnUs = isPreview && previewID !== id;
  return /* @__PURE__ */ jsx(Provider, { rd_window_id: id, id, children: /* @__PURE__ */ jsx(RndWindow$1, { id, zIndex, "data-rd-type": "rd_rnd_window", children: /* @__PURE__ */ jsx(
    StyledWindow,
    {
      as: disableAnimations && "section",
      $rounded: !maximized && !isSnap,
      $showShadows: !disableAnimations && isForeground && !maximized && !isSnap,
      $backgroundColor: backgroundColor,
      $isForeground: isForeground,
      ...disableAnimations && isPreview && {
        style: {
          opacity: isPreviewAndNotOnUs ? "0.12" : "1"
        }
      },
      ...focusableProps,
      ...!disableAnimations && windowTransitions || {},
      "data-rd-type": "rd_window",
      children: /* @__PURE__ */ jsx(
        StyledPeekViewport,
        {
          "data-rd-type": "rd_link_viewport_entry",
          ref: linkViewportEntry,
          children: /* @__PURE__ */ jsxs(StyledWindowWrapper, { "data-rd-type": "rd_window_wrapper", children: [
            !hideTitlebar && /* @__PURE__ */ jsx(Titlebar$1, { id }),
            /* @__PURE__ */ jsx(StyledWindowContent, { "data-rd-type": "rd_window_content", children })
          ] })
        }
      )
    }
  ) }) });
};
const MemoWindow = memo(Window);
const WindowWithContext = ({ children, id, ...others }) => {
  return /* @__PURE__ */ jsx(Provider, { rd_window_id: id, id, children: /* @__PURE__ */ jsx(MemoWindow, { id, ...others, children }) });
};
const index = memo(WindowWithContext);
export {
  index as default
};
//# sourceMappingURL=index-DHqG8dyW.js.map